循环语句--for

时间:2021-12-07 23:00:15

1、guess_age优化版v1.py

 #coding=utf-8
age = 22 for i in range(10):
if i < 3:
guess_num = int(input('input your guess num:'))
if guess_num == age:
print ('Congratulations!you got it.')
break #不往后走了,跳出整个loop
elif guess_num > age:
print ('Think smaller!')
else:
print ('Think big...')
else:
print ('Try too many times...')
break

2、guess_age优化版v1.py

 #coding=utf-8
age = 22 for i in range(10):
print ('loop_i:',i)
if i < 3:
guess_num = int(input('input your guess num:'))
if guess_num == age:
print ('Congratulations!you got it.')
break #不往后走了,跳出整个loop
elif guess_num > age:
print ('Think smaller!')
else:
print ('Think big...')
else:
continue_confirm = input('Do you want to continue because you are stupid:')
if continue_confirm == 'y':
'''这个地方i虽然被重新赋值了,但是从下面的结果来看(标红的),
等到返回for循环的时候因为range的值此时是4,又把i给重新赋值了,
所以看到的是loop_i=4而不是loop_i=0,从这里我们可以看出每次的循环是in后面的序列给i赋值的'''
i = 0
print ('new i:',i)
else:
print('bye')
break

测试结果:

loop_i: 0
input your guess num:1
Think big...
loop_i: 1
input your guess num:1
Think big...
loop_i: 2
input your guess num:1
Think big...
loop_i: 3
Do you want to continue because you are stupid:y
new i: 0
loop_i: 4
Do you want to continue because you are stupid:y
new i: 0
loop_i: 5
Do you want to continue because you are stupid:
 
guess_age优化版v1.py这个程序并没有实现想要的结果,继续优化
 
3、guess_age优化版v3.py
 #coding=utf-8

 age = 22
counter = 0
for i in range(10):
print ('counter:',counter)
if counter < 3:
guess_num = int(input('input your guess num:'))
if guess_num == age:
print ('Congratulations!you got it.')
break #不往后走了,跳出整个loop
elif guess_num > age:
print ('Think smaller!')
else:
print ('Think big...')
else:
continue_confirm = input('Do you want to continue because you are stupid:')
if continue_confirm == 'y':
counter = 0
continue #跳出当次循环
else:
print('bye')
break
counter += 1
结果:
counter: 0
input your guess num:1
Think big...
counter: 1
input your guess num:1
Think big...
counter: 2
input your guess num:1
Think big...
counter: 3
Do you want to continue because you are stupid:y
counter: 0
input your guess num:1
Think big...
counter: 1
input your guess num:1
Think big...
counter: 2
input your guess num:1
Think big...
counter: 3
Do you want to continue because you are stupid:y
counter: 0
input your guess num:1
Think big...
counter: 1
input your guess num:1
Think big...