python - 我不明白这段代码有什么问题
问题描述
我收到 elif 选项 ==2: 的语法错误。我想知道我需要做什么来修复它。我遵循了教授给我们的伪代码,但它仍然无法运行。我想知道我是否不应该使用 elif 或者可能关于缩进的某些内容已关闭。
import random
print("Welcome to the guess my number program")
while True:
print("1. You guess the number")
print("2. You type a number and see if the computer can guess it")
print("3. Exit")
option = int(input("Please enter your number here: "))
if option ==1:
#generates a random number
mynumber = random.randint(1,11)
#number of guesses
count = 1
while True:
try:
guess = int(input("Guess a number between 1 and 10:"))
while guess < 1 or guess > 10:
guess = int(input("Guess a number between 1 and 10:")) # THIS LINE HERE
except:
print("Numbers Only")
continue
#prints if the number you chose is too low and adds 1 to the counter
if guess < mynumber:
print("The number you chose is too low")
count= count+1
#prints if the number you chose is too high and adds 1 to the counter
elif guess > mynumber:
print("The number you choose is too high")
count = count+1
#If the number you chose is correct it will tell you that you guessed the number and how many attempts it took
elif guess == mynumber:
print("You guessed it in " , count , "attempts")
break
elif option == 2:
number = int(input("Please Enter a Number: "))
count = 1
while True:
randomval = random.randint(1,11)
if (number < randomval):
print("Too high")
elif (number > randomval):
print("Too low")
count = count+1
elif (number==randomval):
print("The computer guessed it in" + count + "attempts. The number was" + randomval)
break
else:
break
解决方案
问题很简单。if option == 1
和之间没有连续性elif option == 2
,因为在 while 循环之间。你所要做的就是删除el
部分,elif option == 2
然后只写if option == 2
.
我自己没有测试过整个程序。但乍一看,这应该可以解决问题。
否则请发表评论。
推荐阅读
- json - 添加重量属性时,Snipcart 中的产品抓取“购物车确认”错误
- reactjs - res.status(404)后如何将json数据从后端(express.js)发送到前端(react)?
- php - Laravel 集合中最新外键的唯一标识符
- r - 如何将一个数据帧的列中的值与R中另一个数据帧的标题匹配
- android - Media pipe Android App上的横向方向。一旦将应用程序设置为横向模式,相机方向就会出错
- java - 如何使用 AssertJ 检查对象的多个字段是否为空?
- node.js - SyntaxError: missing ) after argument list 似乎找不到可能的解决方案
- reactjs - 无法读取未定义的属性(读取“地图”) - useQuery
- mysql - 在 Power Bi 中加载比他们更多的行是
- google-sheets - ArrayFormula 什么都不做