我刚刚开始用python开发你自己的电脑游戏。这是第3章的示例代码:
1 # This is a Guess the Number game.
2 import random
3
4 guessesTaken = 0
5
6 print('Hello! What is your name?')
7 myName = input()
8
9 number = random.randint(1, 20)
10 print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
11
12 for guessesTaken in range(6):
13 print('Take a guess.') # Four spaces in front of "print"
14 guess = input()
15 guess = int(guess)
16
17 if guess < number:
18 print('Your guess is too low.') # Eight spaces in front of "print"
19
20 if guess > number:
21 print('Your guess is too high.')
22
23 if guess == number:
24 break
25
26 if guess == number:
27 guessesTaken = str(guessesTaken + 1)
28 print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
29
30 if guess != number:
31 number = str(number)
32 print('Nope. The number I was thinking of was ' + number + '.')
当变量可以在python中的任何时候明显地声明时,为什么在开始时声明
guessesTaken
?我试过这两种方法,一种是完全不使用那条线,另一种是将
guessesTaken
改为0以外的数字。在这两种情况下,它的工作方式似乎完全相同,因为range
功能似乎可以管理guessesTaken
。书中说:
第4行创建一个名为
guessesTaken
的新变量:4. guessesTaken = 0
您将存储玩家在该变量中的猜测次数。
由于玩家在程序中的这一点上没有做出任何猜测,所以将整数存储在这里。
这对我来说不能证明这条线的存在。
最佳答案
循环前的声明没有任何作用。它仅用于代码的可读性或理解。