一、第一个Python程序
创建一个名为Hello.py的程序,出处“Hello World!"
print("Hello World!")
二、变量/字符串
声明变量名:name 并赋值为:”fockrock“
name = "fockrock"
变量定义的规则
- 变量名只能是 字母、数字或下划线的任意组合;
- 变量名的第一个字符不能是数字;
- 以下关键字不能声明为变量名:
[‘and’, ‘as’, ‘assert’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘exec’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘not’, ‘or’, ‘pass’, ‘print’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]
变量赋值
name = 'FockRock'
name2 = name
print("My name is ", name, name2)
name = "Jeck"
print(name, name2)
变量name的值被更新成了“Jack”,name2仍为“ForkRock”
三、用户输入
input获取用户输入
name = input("What's your name?")
四、字符串拼接
1. 用“+”拼接
name = "fockrock"
print("My name is " + name + "!")
输出:My name is fockrock !
2.使用%
name = 'fockrock'
print("My name is %s!" % name)
3.使用{} .format
name = 'fockrock'
print("My name is {name}!".format(name=name))
字符串是 %s;整数 %d;浮点数%f
四、条件表达式if…else
猜年龄游戏
'''在程序里设定好你的年龄,然后启动程序让用户猜测,用户输入后,根据他的输入提示用户输入的是否正确,
如果错误,提示是猜大了还是小了'''
age = 33
guess = int(input("The age you guess:"))
if guess == age:
print('Congratulations on the correct answer!')
elif guess > age:
print('The answer is bigger!')
elif guess < age:
print('The answer is smaller!')
五、for循环
循环十次
for i in range(10):
print("loop:", i)
输出:
loop: 0
loop: 1
loop: 2
loop: 3
loop: 4
loop: 5
loop: 6
loop: 7
loop: 8
loop: 9
需求一:遇到小于5的循环次数就不走了,直接跳入下一次循环
for i in range(10):
if i<5:
continue
print("loop:", i )
需求二:还是上面的程序,但是遇到大于5的循环次数就不走了,直接退出
for i in range(10):
if i>5:
break
print("loop:", i )
回到上面猜年龄的游戏,如何实现让用户不断的猜年龄,但只给最多3次机会,再猜不对询问是否继续,如果回答不是”n“,则继续游戏,否则退出程序
# 预设正确答案33
age = 33
# 初始化回答次数
count = 0
while count <= 3:
count += 1
if count <= 3:
guess = int(input("The age you guess:"))
if guess == age:
print('Congratulations on the correct answer!')
break
elif guess > age:
print('The answer is bigger!')
elif guess < age:
print('The answer is smaller!')
else:
# 回答超过3次,询问是否继续
asw = input('Do you want go on? If not , Please type "n":')
if asw != 'n':
# 回答不是n count值重置为0
count = 0
else:
print('Nice to see you again')
break