我是Python和编程的新手,我正在尝试制作"猜数字"游戏。我使它工作但我希望添加选项以使用制动语句关闭游戏。我已经尝试了2天,但我想我卡住了。
这是有效的代码(没有关闭游戏的选项):
import random
attempts = 0
secretNumber = random.randint(1,100)
while True:
print("Guess a number between 1 and 100")
guess=input()
guess = int(guess)
attempts = attempts + 1
if guess >100 or guess<=0:
attempts = attempts - 1
print("Not allowed.Only numbers between 1 and 100 allowed! \n")
elif guess < secretNumber and guess >0:
print("Nope!Try a higher number! \n")
elif guess > secretNumber and guess <100:
print("Nope!Try a lower number \n")
if guess == secretNumber:
break
if guess == secretNumber:
attempts = str(attempts)
print("Congratulations you found it after " + attempts + " attempts")
代码(带有关闭游戏的选项)不起作用:
import random
attempts = 0
secretNumber = random.randint(1,100)
while True:
print("Guess a number between 1 and 100. You can exit game anytime by typing quit ")
stop=input()
stop=str(stop)
if stop == "quit":
break
print("You quitted the game")
else:
continue
guess=input()
guess = int(guess)
attempts = attempts + 1
if guess >100 or guess<=0:
attempts = attempts - 1
print("Not allowed.Only numbers between 1 and 100 allowed! \n")
elif guess < secretNumber and guess >0:
print("Nope!Try a higher number! \n")
elif guess > secretNumber and guess <100:
print("Nope!Try a lower number \n")
if guess == secretNumber:
break
if guess == secretNumber:
attempts = str(attempts)
print("Congratulations you found it after " + attempts + " attempts")
对不起这篇长篇文章,对于我做错了什么的任何帮助,甚至是使用 break 语句并且不使用def函数实现此目的的不同方法将不胜感激。 非常感谢。
答案 0 :(得分:0)
在Nick A和timgeb的评论中提到的,你可以适应一些事情。 正如我在以下脚本中建议的那样,您可能需要查看try and except。请在脚本中找到评论。
import random
attempts = 0
secretNumber = random.randint(1,100)
# you can prompt the user within input()
stop=input("Guess a number between 1 and 100. You can exit game anytime by typing quit ")
while True:
if stop == "quit": # as the the output of input() is a string, you can compare it with a string without str()
print("You quitted the game")
break
try: # work with try and except to avoid problems whenever the user writes something else than 'quit' or an integer
guess = int(stop)
attempts += 1
if guess >100 or guess<=0:
attempts = attempts - 1
print("Not allowed.Only numbers between 1 and 100 allowed! \n")
elif guess < secretNumber and guess >0:
print("Nope!Try a higher number! \n")
elif guess > secretNumber and guess <=100: # note that it's <=. Otherwise nothing happens when the users chose 100
print("Nope!Try a lower number \n")
except: # if it's not possible to turn 'stop' into an integer we'd like to perform the following
stop = input("No valid input, please guess again ") # Don't stop the script, let the user guess again
continue # don't stop, but leave the current iteration (don't execute the rest) and start again at the beginning of the loop
if guess == secretNumber:
attempts = str(attempts)
print("Congratulations you found it after " + attempts + " attempts")
break
stop = input("Guess again ") # prompt for a new number every round of the loop