我得到了一項作業,其中我應該通過給出函式的編號來制作執行不同型別計算/函式的程式(必須使用帶有 def 的函式)。并被它嚴重卡住了。
1.
choice = int(input("Chosen function: "))
while choice != 0
if choice == 1:
print("Sum of the list: ", summ_list(lista))
if choice == 2:
print("Is the chosen number inside?: ", decide_if_in(lista, s))
.......
else:
print("The program closes.")
如果用戶按 0,程式應終止。但是,盡我最大的努力,如果我使用 while 或 for 回圈,它將陷入無限回圈,因此我無法解決它。
2.
def decide_if_in():
s = int(input("Which number do you think is in the list?: "))
for d in s:
if d == s:
print("It is in the list")
else:
print("It is not in the list..")
在這里,它確實可以在沒有 def 標簽的情況下作業,但我無法使用它。關鍵是我給它一個數字并檢查它在串列中的串列?
uj5u.com熱心網友回復:
在您的示例 1 中,您沒有choice在回圈內更新。這就是它陷入無限回圈的原因。你可以把它寫成,
choice = int(input("Chosen function: "))
while choice != 0:
if choice == 1:
print("Sum of the list: ", summ_list(lista))
choice = int(input("Chosen function: "))
if choice == 2:
print("Is the chosen number inside?: ", decide_if_in(lista, s))
choice = int(input("Chosen function: "))
.......
else:
print("The program closes.")
一點點python的技巧,你可以直接把函式放在串列或字典中。所以,你可以做類似的事情
def func1(arg1):
#do something here
def func2(arg1):
#do something else
func_dic = {1:func1, 2:func2}
choice = int(input("Whatever: "))
while choice != 0:
print("Whatever: ", func_dic[choice](list))
^^^^^^^^^^^^^^^^ -> function of choice here
print("close dialogue")
對于您的第二個代碼,您的定義是錯誤的。你可以簡單地通過
def func_name(lista):
s = int(input("Whatev: "))
if s in lista:
return "It's in"
else:
return "It's not in"
uj5u.com熱心網友回復:
choice = int(input("Chosen function: "))
while 1: # Loops infinitely, using exit() to stop the script
if choice == 1:
print("Sum of the list: ", summ_list(lista))
elif choice == 2: # Better to use elif
print("Is the chosen number inside?: ", decide_if_in(lista))
.....
elif choice == 0:
print("The program closes.")
exit() # Stops the python script
choice = int(input("Chosen function: ")) # Asking for input again
def decide_if_in(lista): # Taking the list as an arg
s = int(input("Which number do you think is in the list?: "))
if s in list:
print("It is in the list")
else:
print("It is not in the list..")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/370231.html
上一篇:檢查多個串列的最后一個元素
