一、输入和输出
i = input("Hi") #获取输入结果,默认为字符串格式
print("Hello World!") #打印文字
二、if...else判断语句
_username = "daizhi"
_password = "513577" #输入正确的账号密码
username = input("username:")
password = input("password:")
if _username == username and _password == password:
print("Welcome user %s login..." % (username)) #如果账号和密码都正确显示一段文字
else:
print("invalid username or password!") #其他情况显示其他文字
三、while循环语句
猜年龄游戏,有三次机会,猜大了猜小了分别提示不同的话
age = 23 #正确答案
count = 0
while count < 3:
guess_age = int(input("guess age:"))
if guess_age == age:
print("Congratulation! You got the right answer!") #猜对了
break
elif guess_age > age:
print("Think smaller...") #猜大了
else:
print("Too small!") #猜小了
count +=1 #每次循环count加1
else:
print("Sorry! You have used all chances") #机会用光,退出程序
while语句的流程为:当条件被触发时,进行下面的流程,如果遇到break/continue就结束当次循环,区别是,continue结束当次循环后后面语句不再执行,重新开始循环;而break是调出所有循环。
四、for循环语句
仍然以猜数字游戏为例
age = 23
for count in range(0,3): #默认count=0,从0开始,大于等于3时结束,步长默认为1
guess_age = int(input("guess age:")) #强制转换字符串为整数
if guess_age == age:
print("Congratulation! You got the right answer!")
break #结束循环
elif guess_age > age:
print("Think smaller...")
else:
print("Too small!")
if count == 3:
continue_confirm = input('''Do you want to keep guessing? Y/N
''') #当猜到第三次时,询问是否继续
if continue_confirm != "N":
count = 0 #如果答案不为N则count归零,继续循环