抱歉,我有點初學者,我無法讓 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()
uj5u.com熱心網友回復:
else跟在它前面的最后一個iforelif陳述句之后。對你來說,這是:
if user == "stop":
這意味著,如果用戶沒有“停止”,您就是在告訴程式列印“錯誤輸入”。
一個簡單的解決方法是簡單地更改if user == "stop":為elif user == "stop":
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/477529.html
