python - 似乎无法使我的 else 语句在 Python-turtle 中正常工作

抱歉,我有点初学者,我无法让 else 语句在这个程序中正常工作,我用 python 在海龟中绘制东西。我尝试缩进 else 语句else: print("Wrong input!"),但它只是说“输入错误!”每次我做某事;该程序运行良好,但不断重复。如果我保持这样的 else 语句并且我输入其他任何内容,那么“输入错误!”应该弹出的没有出现。有谁知道该怎么做?

例如:如果我像我在这里给出的那样运行代码,结果是这样的:

你想做什么?:f(<--我输入这个)

你想前进多少像素?:100(<--我输入这个)

现在如果我放别的东西

你想做什么?:asbfaifb (<-- 我输入这个)

你想做什么?:

它没有显示“输入错误!”应该说的消息

另一方面,如果我再次缩进 else 语句,这就是结果

你想做什么?:f

你想前进多少像素?:100

输入错误!

你想做什么?:r

你想右转多少度?:90

输入错误!

你想做什么?:100

输入错误!

你想做什么?:b

输入错误!

你想做什么?:

但代码仍然运行良好,只是不断重复“输入错误!”一遍又一遍

#importing turle
import turtle

#Creating our turtle and naming it
turtle = turtle.Turtle()


#Ask the user what to do and tell the instructions
#Make a function for the instructions
def instructions():
  print("What do you want me to do? Please choose the letter corresponding to the action: ")
  print("Forward = f")
  print("Turn right = r")
  print("Turn left = l")
  print("Turn backwards = b")
  print("If you want to stop: stop\n")

#print out the instuctions
instructions()

#Function for drawing by getting the user's input
def drawing():
  while True:
    user = input("What you want to do?: ")
  
  #If they want to go forward
    if user == "f":
      l = int(input("How many pixels you want to go forward?: "))
      turtle.forward(l)
  
  #If they want to turn right
    elif user == "r":
      x = int(input("How many degrees you want to turn right?: "))
      turtle.right(x)
  
  #If they want to turn left
    elif user == "l":
      y = int(input("How many degrees you want to turn left?: "))
      turtle.left(y)
  
  #If they want to turn backwards
    elif user == "b":
      z = 180
      turtle.right(z)
      
  #If they want to stop the program
    if user == "stop":
      print("\nOk, I will stop the program now\n\nTo make a new drawing, re-run the program")
      break
  #If they type anything else
   else:
     print("Wrong input!")



drawing()

回答1

else 跟在它之前的最后一个 ifelif 语句之后。对你来说,这是:

if user == "stop":

这意味着,如果用户没有“停止”,您就是在告诉程序打印“错误输入”。

一个简单的解决方法是简单地将 if user == "stop": 更改为 elif user == "stop":

相似文章

随机推荐

最新文章