1

我认为如果我只是逐字给出问题,这是最简单的:

“编写一个 Python 程序,不断询问用户输入 10 以外的数字。如果输入 10,请训斥用户不要猜数字 10。”

我遇到了一个错误——基本上,我不知道在进入 while 循环之前如何定义guess 变量。

target, guess = 10

while target != guess:
    guess = int(input('Enter a number other than 10: '))

print("Hey, you weren't supposed to enter 10!")
4

4 回答 4

2

您可以像这样将一个元组分配给一个元组

target, guess = 10, 10

您实际上并不希望它们相同,因为这样 while 循环会立即退出。

你可以说

target, guess = 10, None

但通常将其写在 2 行上会更清楚

target = 10
guess = None

另一种方法是避免首先分配一个虚拟值来猜测

target = 10
while True:
    guess = int(input('Enter a number other than 10: '))
    if guess == target:
        break

print('Hey, you werent supposed to enter 10!')
于 2013-10-01T03:01:57.347 回答
0

创建该错误是因为您试图将两个变量分配给一件事(整数10)。如果您希望两个变量都相等10,则需要执行以下操作:

target = guess = 10

但是,在此程序中,您将不需要该功能。相反,你会想要这样的东西:

# Set target equal to 10
target = 10
# Make guess equal None, since there are no guesses yet
guess = None

# Loop until guess equals target
while target != guess:
    # Get new guess
    guess = int(input('Enter a number other than 10: '))

# Print message
print('Hey, you werent supposed to enter 10!')
于 2013-10-01T02:55:29.937 回答
0

你可以这样做...

condition = True

while condition == True:
  number = int(input("Enter a number"))
  if number == 10:
     print("You can't enter ten") #or whatever you want to say
  else:
    condition = False #if you want to drop out of the loop

希望这可以帮助 :)

于 2017-05-10T15:38:55.617 回答
0

只需创建一个值不是 10 的变量“num”(我取了 11)然后创建一个局部变量为 num 并输入你喜欢的值,你会得到结果

num=11
while num!=10:
      num=int(input("Enter a number other than 10"))
print "I thought i said no to 10"
于 2015-09-07T13:54:16.090 回答