我正在學習 Python 函式和回圈;但是,我在嘗試計算分配給回圈中整數的兩個變數時遇到錯誤,我在下面發布了我的代碼以及 draw.io 圖,以便更好地解釋我想要完成的任務:
在包含的影像中,綠色代表一個作業回圈或功能,紅色代表一個損壞的回圈或功能,白色代表尚未編碼
在包含的代碼中,回圈適用于輸入選項 m 和 l,但回圈不適用于選項 q。q 選項也不適用于 w、e 和 r 選項的添加。
PS 我還沒有在 w、e、r 或 y 選項中撰寫任何代碼(如您所見),但是我已將整數分配給 q、w、e 和 r 變數。
q = 1
w = 2
e = 3
r = 4
def exitprogram():
print ("exiting...")
def q_function():
Q_loop = True
while Q_loop:
print("Q function selected, select addition - press k to go back or x to exit")
print("")
Q_addition = int(input("Add Q with "))
#exit program
if Q_addition =="x":
exitprogram()
break
#additions
elif Q_addition == "w":
q_w = q w
print(q_w)
if Q_addition == "k":
start()
#invalid input
else:
print("invalid input - try again")
continue
def w_function():
print("W function operational")
W_addition = int(input("Add W with - to exit select x "))
def e_function():
print("E function operational")
E_addition = int(input("Add E with - to exit select x "))
def r_function():
print("R function operational")
R_addition = int(input("Add R with - to exit select x "))
def t_function():
T_loop = True
while T_loop:
T_selection = input("T function operational - press k to go back or x to exit ")
if T_selection == "k":
more()
elif T_selection == "x":
exitprogram()
break
else:
print("invalid input - try again")
continue
def y_function():
print("Y function operational")
def more():
moreloop = True
while moreloop:
l = input ("select t or y - to go back select k to exit select x ")
if l =="t":
t_function()
break
if l =="y":
y_function()
break
if l =="x":
exitprogram()
break
elif l =="k":
start()
else:
print("invalid input - try again")
continue
def start():
loop1 = True
while loop1:
a = input("select q, w, e or y - for more options select m or to exit select x ")
if a == "x":
exitprogram()
break
elif a == "q":
q_function()
break
elif a == "w":
w_function()
break
elif a == "e":
e_function()
break
elif a == "r":
r_function()
break
elif a =="m":
more()
break
else:
print("invalid input - try again")
continue
start()
錯誤回溯包括在下面
Traceback (most recent call last):
File "x:/xxx/xxx/xxxx/xxxx.xx", line 115, in <module>
start()
File "x:/xxx/xxx/xxxx/xxxx.xx", line 95, in start
q_function()
File "x:/xxx/xxx/xxxx/xxxx.xx"", line 16, in q_function
Q_addition = int(input("Add Q with "))
ValueError: invalid literal for int() with base 10: 'w'
uj5u.com熱心網友回復:
您Q_addition = int(input("Add Q with "))正試圖將輸入(x、k、e 等)轉換為 int。這會引發錯誤。此外,您的邏輯檢查字串不是 int
#exit program
if Q_addition =="x":
Q_loop = False #set the loop variable to false to exit the loop and return to main function
#changed to elif as Q_addition can only be one option
elif Q_addition =="x":
...
elif Q_addition == "w":
#if you'd like addition with the other variables need to add them
elif Q_addition == "e":
q_e = q e
print(q_e)
elif Q_addition == "r":
q_r = q r
print(q_r)
...
#changed to elif, see above
elif Q_addition == "k":
洗掉int()演員所以Q_addition = input("Add Q with ")
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/432744.html
下一篇:PHP,比較2個while回圈
