我在 Phyton 中創建了一個簡單的代碼,它需要兩個數字,直到給出你在一個回圈中(因為代碼檢查是否給出了一個 int 數字)。之后,您必須選擇某個操作。但是我的代碼不能破壞loop. 不知道是什么問題,如果是縮進?如果我不應該在此使用回圈,語法?
dataRight = False
#Check if the data are int numbers
while not dataRight:
print("Convert LightYears and Parsecs, enter the data:")
dataParsec = input("Parsecs Number: ")
try:
dataParsec = int(dataParsec)
except:
dataParsec = "Error1"
dataLight = input("LightYear Númber: ")
try:
dataLight = int(dataLight)
except:
dataLight = "Error2"
if dataParsec != "Error1" and dataLight != "Error2":
dataRight = True
#After the data given is right, choose the operation to make.
question = input("Choose, A)-LightYear to Parsecs, B)-Parsecs to LightYear: ")
question = question.upper()
lightYear = 3.26156
if question == "A":
convertlightYear = dataParsec / lightYear
print("Convert to Parsecs: ", str(convertlightYear))
elif question == "B":
convertParsec = dataParsec * lightYear
print("Convert to LightYear: ", str(convertParsec))
else:
print("Data entered is wrong")
有人能幫我嗎?已經好幾天了,我看不出有什么問題。
uj5u.com熱心網友回復:
代碼:
- 據我了解,您的問題是 non-terminating
while loop。這只是因為縮進。
while not dataRight:
print("Convert LightYears and Parsecs, enter the data:")
dataParsec = input("Parsecs Number: ")
try:
dataParsec = int(dataParsec)
except:
dataParsec = "Error1"
dataLight = input("LightYear Númber: ")
try:
dataLight = int(dataLight)
except:
dataLight = "Error2"
# This must be outside the except that's all
if dataParsec != "Error1" and dataLight != "Error2":
dataRight = True
輸出:
Convert LightYears and Parsecs, enter the data:
Parsecs Number: l
LightYear Númber: 5
Convert LightYears and Parsecs, enter the data:
Parsecs Number: 2
LightYear Númber: 5
Choose, A)-LightYear to Parsecs, B)-Parsecs to LightYear: A
Convert to Parsecs: 0.613203497712751
uj5u.com熱心網友回復:
如果您希望它在用戶輸入數字之前一直保持回圈,請嘗試以下內容
dataParsec = input("Parsecs Number: ")
while dataParsec.isdigit() == False:
print("Convert LightYears and Parsecs, enter the data:")
dataParsec = input("Parsecs Number: ")
uj5u.com熱心網友回復:
這做的作業:
print("Convert LightYears and Parsecs, enter the data:")
dataParsec = input("Parsecs Number: ")
while dataParsec.isdigit() == False:
dataParsec = input("Parsecs Number: ")
dataLightYear = input("LightYears Number: ")
while dataLightYear.isdigit() == False:
dataLightYear = input("LightYears Number: ")
question = input("Choose, A)-LightYear to Parsecs, B)-Parsecs to LightYear: ")
question = question.upper()
lightYear = 3.26156
if question == "A":
convertlightYear = int(dataParsec) / int(dataLightYear)
print("Convert to Parsecs: ", str(convertlightYear))
elif question == "B":
convertParsec = int(dataParsec) * int(dataLightYear)
print("Convert to LightYear: ", str(convertParsec))
else:
print("Data entered is wrong")
感謝 Blckknght、Bibhav 和 Victor_G。你們都幫了大忙!:D
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/424451.html
