python - Python 程序循环
问题描述
有人可以看看我的代码,看看为什么我在第 41 行遇到语法错误吗?''' 这个程序让用户可以选择玩数字猜谜游戏,他们可以选择在 1 之间进行无限猜测和 100 次或只有 5 次猜测。'''
menu = """
1. Play Game unlimited guesses
2. Play Game with 5 guesses
0. Exit
"""
choice = None
设置循环
while (choice != 0):
print (menu)
gameCode = int(input("Would you like to play a game?"))
if (gameCode == 1):
print ("Guess a number between 1 & 100:")
x = random.randint (1, 100)
guess = int(input())
while (guess != x):
if (guess < x):
guess = int(input("Your guess is too low, try again:"))
count = count+1
elif (guess > x):
guess = int(input("Your guess is too high, try again:"))
count = count+1
elif (guess == x):
print ("Congratulations, you guessed the number in", count,
"attempts!")
elif (gameCode == 2):
for i in range (1,6,1):
guess = int(input("Enter a guess between 1 and 100:")
if (guess == x):
print ("You got it!")
else:
print ("Sorry, incorrect!)
if (guess == x):
print ("You won!")
else:
print ("You lost!")
elif (guess == 0):
break
else:
print ("You entered an invalid game code. Goodbye!")
解决方案
纠正一些错误后,它看起来像这样:
import random
menu = """
1. Play Game unlimited guesses
2. Play Game with 5 guesses
0. Exit
"""
choice = None
while (choice != 0):
print (menu)
gameCode = int(input("Would you like to play a game?"))
if (gameCode == 1):
count=0
print ("Guess a number between 1 & 100:")
x = random.randint (1, 100)
guess = int(input())
while (guess != x):
count = count+1
if (guess < x):
guess = int(input("Your guess is too low, try again:"))
elif (guess > x):
guess = int(input("Your guess is too high, try again:"))
print(f"Congratulations, you guessed the number in {count} attempts!")
elif (gameCode == 2):
for i in range (1,6,1):
guess = int(input("Enter a guess between 1 and 100:"))
if (guess == x):
print ("You got it!")
else:
print ("Sorry, incorrect!")
elif (gameCode == 0):
break
else:
print ("You entered an invalid game code. Goodbye!")
推荐阅读
- sql - 插入多行查询失败
- android - 从互联网或Android应用程序的数据库中检索数据哪个更快?
- r - 如何在一系列csv文件中弹出不匹配的列名?
- directx - DirectCompute:如何从 RWTexture2D 中读取数据
? - openssl - wasm openssl 获取 dlopen 中止
- javascript - 为什么函数声明会被提升而函数表达式不会?
- java - SubmoduleUpdateCommand getConfigUpdate() 返回 null
- android - 如何在 Android 中将 VAST IMA 谷歌广告与 Jwplayer 一起使用
- python - 如何在 R 中获取日期
- java - 接口上的 Java CompletableFuture 链式调用