以猜测一个学生的分数为例子说明:
#if猜测分数-------------------------
score=90
guess_score=int(input('score:'))
if guess_score==score:
print('Great!')
elif guess_score>score:
print('Guess smaller!')
else:
print('Guess bigger!')
运行:
#while 允许猜测3次-------------------------
#if猜测分数
score=90
count=0
while count<3:
guess_score=int(input('score:'))
if guess_score==score:
print('Great!')
break
elif guess_score>score:
print('Guess smaller!')
else:
print('Guess bigger!')
count+=1
else:
print('byebye!')
运行:
# for 允许最多猜测3次-------------------------
#if猜测分数
score=90
count=0
for count in range(3):
guess_score=int(input('score:'))
if guess_score==score:
print('Great!')
break
elif guess_score>score:
print('Guess smaller!')
else:
print('Guess bigger!')
count+=1
else:
print('byebye!')
#3次猜不对,选择是否再猜-------------------------
score=90
count=0
while count<3:
guess_score=int(input('score:'))
if guess_score==score:
print('Great!')
break
elif guess_score>score:
print('Guess smaller!')
else:
print('Guess bigger!')
count+=1
if count==3:
continu=input("do you continue?")
if continu=='y':
count=0
else:
print('byebye!')
运行: