#This is a guess the number game.
import random
secretnumber=random.randint(1,20)
print('I am thinking of a number between 1 and 20. ')
#Ask the player to guess 6 times.
for guesstaken in range(1,7):
print('Take a guess.')
guess=int(input())
if guess
print('Your guess is too low.')
elif guess>secretnumber:
print('Your guess is too high.')
else:
break
if guess==secretnumber:
print('Good job!You guessed my number in '+str(guesstaken)+' guesses!')
else:
print('Nope.The number I was thinking of was '+str(secretnumber))
逐行解释:
1.
#This is a guess the number game.
import random
secretnumber=random.randint(1,20)
首行是注释语句。引用random函数库,将1到20内产生的一个随机数赋值给secretnumber。
2.
print('I am thinking of a number between 1 and 20. ')
在电脑屏幕上打印出print内部的一句话。(I am thinking of a number between 1 and 20.)
3.
for guesstaken in range(1,7):
这里是一个for循环,guesstaken分别取1,2,3,4,5,6这几个数,以此进入循环,若循环进行至6运行完毕之后,则循环结束。
4.
print('Take a guess.')
guess=int(input())
首先在屏幕上打印出‘Take a guess’提示用户输入数字,运用int函数将字符串数据类型转换为整型。
5.
if guess
print('Your guess is too low.')
elif guess>secretnumber:
print('Your guess is too high.')
else:
break
当guesstaken在(1,6)的范围内,这里是一个if的条件判断语句,输入的guess和secertnumber对它们的大小关系进行判断,如果输入的数字小于我们在设定的值,屏幕上提示,猜的数字太小了。如果输入的数字大于我们设定的值,屏幕上提示,猜的数字太大了。如果猜的数字恰好等于我们猜的数字,则退出循环。
6.
if guess==secretnumber:
print('Good job!You guessed my number in '+str(guesstaken)+' guesses!')
else:
print('Nope.The number I was thinking of was '+str(secretnumber))
这里是一个if-else条件判断,只有当guesstaken在1-6内数字区完或者猜的数字和我们设定的数字相等时才执行这个if-else条件判断句。
领取专属 10元无门槛券
私享最新 技术干货