我刚刚编写了一个猜测随机数的快速脚本。 虽然脚本'恭喜你赢了等'的最后一行没有运行。 此外,在某些解释器中,它发出错误“无法运行脚本”。
Error in cat(name) : object 'name' not found
Error in own_brew(template, data[-1L]) :
答案 0 :(得分:1)
我对您的脚本进行了一些修改。请注意,其功能受执行流程的约束,并且没有必要使用特殊控制语句(例如continue
,break
)或明确的干预来使其在逻辑上保持一致:
import random
secret_number = random.randint(1, 100)
guess = None
attempts = 0
while secret_number != guess:
guess = int(input("Take a guess: "))
attempts += 1
if secret_number == guess:
print("\nYou guessed it! The number was ", secret_number)
elif guess < secret_number:
print("Higher...")
elif guess > secret_number:
print("Lower...")
我改变了:
isCorrect
变量。我删除它是因为它没有使用; guess
变量的方式。在while语句之前是None
; 我建议直观地了解脚本的工作原理。
我尝试运行它并收到以下输出:
None@vacuum:~$ python3.6 ./test.py
Take a guess: 70
Higher...
Take a guess: 80
Higher...
Take a guess: 90
Higher...
Take a guess: 95
Lower...
Take a guess: 94
Lower...
Take a guess: 93
Lower...
Take a guess: 92
Lower...
Take a guess: 91
You guessed it! The number was 91
答案 1 :(得分:0)
你应该从while循环中打印出这一行,因为当secret_number == guess时你的循环会中断。
while ...:
if:
...
elif:
...
print "You guessed it! The number was {0}".format(secret_number)