流程控制与循环
Python 通过if、elif和else控制流程分支,通过whlie和for还进行循环
一、单分支语句
name = input('Please enter your name:')
gender = input('Please enter your gender:(male/female)')
age = int(input('Please enter your age:'))
if gender == 'female' and age == 28 :
print("Hello,"+name+".I like girls.")
Please enter your name:Lucy
Please enter your gender:(male/female)female
Please enter your age:30
二、多分支语句
name = input('Please enter your name:')
gender = input('Please enter your gender:(male/female)')
age = int(input('Please enter your age:'))
if gender == 'female' and age == 28 :
print("Hello,"+name+".I like girls.")
elif gender == 'female' :
print("Hello,"+name+".cradle snatcher is good.")
elif gender == 'male' :
print('Conduct gay act together!')
else :
print('The input is wrong and try again')
Please enter your name:viki
Please enter your gender:(male/female)female
Please enter your age:28
Hello,viki.I like girls.
练习–猜年龄
age_of_guess = 36
guess = int(input('>>:'))
if guess > age_of_guess :
print('猜错了,往小了猜')
elif guess < age_of_guess :
print('猜错了,往大了猜')
else :
print('恭喜你猜对了!')
>>:42
猜错了,往小了猜
练习–猜年龄2
给定一个年龄,3次猜的机会,猜中或者3次机会使用完后,询问是否继续游戏
age = 28
count = 0
while count < 3 :
u_guess = int(input("请输入年龄:")) #3次循环猜年龄
if u_guess == age :
print("you win!")
count = 2 #猜中后直接进入下次游戏询问
elif u_guess < age :
print("It\'s bigger that.")
else:
print("It\'s smaller that.")
if count == 2: #询问是否继续游戏
print("Do you want to play angin?(y/n)")
answer = input("")
if answer == "y":
count = 0
continue
else:
exit()
count += 1
随机给定一个年龄,3次猜的机会,猜中或者3次机会使用完后,询问是否继续游戏
import random
def run():
list1 = range(100)
return random.choice(list1)
count = 0
while count < 3:
age = run()
print(age)
while count < 3 : # 给定age后开始一轮3次机会的游戏
u_guess = int(input("请输入年龄:"))
if u_guess == age :
print("you win!")
break #猜中后结束本轮游戏,进行询问是否再玩
elif u_guess < age :
print("It\'s bigger that.")
else:
print("It\'s smaller that.")
count += 1 #一轮游戏循环
print("Do you want to play angin?(y/n)")
answer = input("")
if answer == "y": #询问是否继续游戏
count = 0
continue #返回第一层循环
else:
exit()