python- function isn't called in a while loop - python

noprob=["nothing","none","no damage"]
while True:
q1=input("input your answer:")
answer=q1.split(' ')`
if any(a in answer for a in noprob):
function()#wont call this
break
else:
print("else statement")
continue
def function():
print("code now works")
my code won't call the function when it should. this code should recognize user input and output necessary actions.
new whole code: with added elif statement which i think is the problem with the code
`noprob=["nothing","none","no damage"]
something=["something","yes"]`
def function():
print("code now works")`
def something():
print("something, code works")
while True:
q1=input("input your answer:")
answer=q1.split(' ')`
if any(a in answer for a in noprob):
function()#wont call this
break
elif any(a in answer for a in something):
something()
break
else:
print("else statement")
continue

Python executes code form top to bottom. So you won't get to execute function if you don't declare its definition before. move the function before the while loop.
noprob=["nothing","none","no damage"]
def function():
print("code now works")
while True:
q1=input("input your answer:")
answer=q1.split(' ')
if any(a in answer for a in noprob):
function()#wont call this
break
else:
print("else statement")
continue

Your problem is, your list and function both named something. Rename one and change your code accordingly.
something=["something","yes"]
def something(): #this one shadows your list and needs to be renamed
print("something, code works")
For generator thingy, Python 3.5

Related

Using Python for default parameters

I am currently learning python and stuck on a coding exercise. I am trying to achieve the result as shown on the image1. I am stuck on the overall code. I also not sure how to incorporate the "quit", so that the program terminates.
Image1
def tester(result):
while tester:
if len(result)< 10:
return print(givenstring)
else:
return print(result)
def main():
givenstring = "too short"
result=input("Write something (quit ends): ")
if __name__ == "__main__":
main()
For your problem, you need to have a variable that is your Boolean (true/false) value and have your while loop reference that. currently your while loop is referencing your function. inside your main function when you get your user input you can have a check that if the input is "quit" or "end" and set you variable that is controlling your loop to false to get out of it.
you also are not calling your tester function from your main function.
You missed into main() function to call your function, like tester(result). But such basics should not be asked here.
def tester(result):
if len(result)< 10 and result != 'quit':
givenstring = "too short"
return print(givenstring)
else:
return print(result)
def main():
result=None
while True:
if result == 'quit':
print("Program ended")
break
else:
result=input("Write something (quit ends): ")
if result.lower() == 'quit':
result = result.lower()
tester(result.lower())
if __name__ == "__main__":
main()

Switch-case statement in Python

I'm tired of trying to make a menu that let's me choose from a dictionary keys and in every value I have the choice. I found that I can use dictionary and get() method, it's working fine, but I should use if else statement after get() to execute a function that answers the user choice. Can I do it better? Maybe using a lambda inside the key value?
def menu():
print("Welcome to Our Website")
choises={
1:"Login" ,
2:"Register",
}
for i in choises.keys(): # Loop to print all Choises and key of choise !
print(f"{i} - {choises[i]}")
arg=int(input("Pleasse Chose : "))
R=choises.get(arg,-1)
while R==-1:
print("\n Wrong Choise ! Try again ....\n")
menu()
else:
print(f"You Chosed {R}")
if R==1:
login()
if R==2:
register()
def register():
print("Registration Section")
def login():
print("Login Section")
menu()
you can simulate a switch statement using the following function definition:
def switch(v): yield lambda *c: v in c
You can use it in C-style:
x = 3
for case in switch(x):
if case(1):
# do something
break
if case(2,4):
# do some other thing
break
if case(3):
# do something else
break
else:
# deal with other values of x
Or you can use if/elif/else patterns without the breaks:
x = 3
for case in switch(x):
if case(1):
# do something
elif case(2,4):
# do some other thing
elif case(3):
# do something else
else:
# deal with other values of x
It can be particularly expressive for function dispatch
functionKey = 'f2'
for case in switch(functionKey):
if case('f1'): return findPerson()
if case('f2'): return editAccount()
if case('f3'): return saveChanges()

How does continue statement work in function?

i am building scientific calculator. After performing the operation it ask do u want to go back in main menu or Exit
def Again():
x=input ("Go back to main menu(Y/N)")
if (x=='Y') or (x=='y'):
continue
else:
break
when user press y it go back to main menu otherwise exit
You can`t use break and continue in function, read tutorial
instead, you can use check in your main loop, and your function must return True or False
def Again():
x=input ("Go back to main menu(Y/N)")
if (x=='Y') or (x=='y'):
return True
else:
return False
while True: # your main loop
# some other code
# check on exit
if Again():
continue
else:
break
This can work!
class Cal:
def main_menu(self):
print ("I am in main menu")
def again(self):
x = raw_input("Go back to main menu(Y/N)")
if x == 'y':
self.main_menu()
if __name__ == '__main__':
c = Cal()
c.again()
When you will enter y it will go to the main menu.
Also, continue and break will not work here as they both are applied in loops.
You can use raw_input instead of input as input does not accept string values.

I cant find whats causing my program to stop working after i but everything into separate functions

So I originally had everything outside functions. Meaning there was no 'def' or 'return' anywhere. and all the displays came out fine.
But now that I'm trying to use Main function as a switch to call other functions. my output disappeared, and when i entered '1' then '1' would just be repeated back at me. I am confused how where I made my mistake.
Then I am trying to return to my main function after I enter 'a' but I do not know how to do that.
Can anyone help me fix this?
~Im using Thonny Python IDE on a raspberry pi if that helps.
Here is my code:
#
import sys, random
def main():
slct= input()
if slct==1:
set1()
elif slct==2:
set2()
elif slct ==3:
set3()
return
def set1():
n1= random.randint(0,9)
pw1= random.randint(1,3)
print(n1)
if pw1==1:
print('one')
elif pw1:
print('ten')
else:
print('hundred')
return
def set2():
n2= random.randint(0,9)
pw2= random.randint(1,3)
print(n2)
if pw2==1:
print('thousand')
elif pw2:
print('ten thousand')
else:
print('hundred thousand')
return
def set3():
n3= random.randint(0,9)
pw3= random.randint(1,3)
print(n3)
if pw3==1:
print('one million')
elif pw3:
print('ten million')
else:
print('hundred million')
return
you need call main().
add main() at the end of your file.
Also you don't need to add return at the end of every function unless you want to return any value e.g. return "passed"
I don't know what you are doing with this code but as set1(), set2() and set3() are same,following code is also similar to what you have:
import sys, random
def main():
n1= random.randint(0,9)
pw1= random.randint(1,3)
print(n1)
if pw1==1:
print('one')
elif pw1:
print('ten')
else:
print('hundred')
return
main()

Python Basic if statements

Hi Guys for the below code i want to execute only if the first condition satisfy so please help me
print('welcome')
username = input()
if(username == "kevin"):
print("Welcome"+username)
else:
print("bye")
password = input()
if(password == "asdfg"):
print("Acess Granted")
else:
print("You Are not Kevin")
If I got this right, you want to exit/terminate the script at the "else" block of the 1st if statement.
There are two approaches - 1st is that you use sys.exit():
import sys
#if statement here
...
else:
print("bye")
sys.exit()
2nd is that you put your 2nd if under the 1st if's else block:
...
else:
password = input()
if password=="abcdef":
#do something here
else:
print("you're not Kevin")
Also, I see that you're using brackets after the if statements (if (condition):). That is not necessary for Python 3.x as far as I'm concerned.
See: https://repl.it/CEl7/0

Categories

Resources