I was given an assignment in which I was supposed to make program which does different kind of calculations/ functions by giving the number of the function (must use function with def). And got seriously stuck with it.
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.")
If the user presses 0 the program should terminate. However to all my best effort if I make a while or for loop it will get stuck in an infinite loop thus I am unable to solve it.
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..")
Here it does work without the def tag but I cant make it work with it. The point would be I give it a number and it checks the list that is it inside the list?
CodePudding user response:
In your example 1, you are not updating choice
inside your loop. That is why it is stuck in infinite loop. You can write it as,
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.")
A tiny bit of tip- in python, you can directly put functions in list or dictionary. So, you can do something like
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")
For your second code, your definition is wrong. You can simply do it by
def func_name(lista):
s = int(input("Whatev: "))
if s in lista:
return "It's in"
else:
return "It's not in"
CodePudding user response:
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..")