1. 程式人生 > >python之循環1

python之循環1

繼續 all while 思路 lease tin 個數字 any \n

循環:while,for

for 循環:

for i in range(0,10,2):

循環體

備註:range裏面的2,是步長,就是 i 取值為:0 ,2,4,6,8;默認為1,for i in range(10)==for i in range (0,10)==for i in range (0,10,1)

結束循環:break:結束當前循環

continue:跳出本次循環,進入下一次循環

寫個循環:猜一個數字的大小

思路:給出一個數字猜大小,當猜的數字大於給出的數字,返回猜的數字過大;當猜的數字小於給出的數字,則返回猜的數字過小,當猜的數字等於給出的數字,則返回成功

猜的次數限制為3次,當第三次還猜不對的時,詢問是否繼續猜字遊戲,當輸入非‘n’和‘N’時,可以繼續猜三次。

good_number=57
guess_count=0
while guess_count<3:
guess_number=int(input(‘Please input your guess_number: ‘))
if guess_number==good_number:
print(‘Good!!!You got it !!!‘)
break
elif guess_number<good_number:
print(‘Too bad!!!You guessed it was small.‘)
else:
print(‘Too bad!!!You guessed it was big.‘)

guess_count+=1

if guess_count==3:
print(‘You have guessed wrong three times,do you want to keep guessing...‘)
continue_game=input(‘If you want to continue playing,you can enter any character or enter directly;\n‘
"If you do not want to continue playing, please enter ‘n ‘.\n")
if continue_game!=‘n‘and continue_game!=‘N‘:
guess_count=0

python之循環1