Program Returning nothing - python

I saw this Flowchart and decided to make a program out of it. The problem is, it only returns "Go Outside" if I enter "no" the first time. All others return "None". Im using Python 2.7
def waitawhile():
print "Wait a while"
rain2 = raw_input("Is it still raining?")
if rain2.lower() == "no":
return "Go Outside"
elif rain2.lower() == "yes":
waitawhile()
def Raining():
print "Is it raining?"
rain = raw_input()
if rain.lower() == "no":
return "Go Outside"
elif rain.lower() == "yes":
print "Have Umbrella?"
umbrella = raw_input()
if umbrella.lower == "yes":
return "Go Outside"
elif umbrella.lower() == "no":
waitawhile()
print Raining()

The problem is with your calls to waitawhile (from both Raining and from waitawhile itself). After calling it, you're discarding the return value and returning nothing. To fix it, change the calls from:
waitawhile()
to:
return waitawhile()
Make sure that, for both functions, there is no way to reach the end of the function without executing a return statement.

Your program have three problem, in the following they are fixed:
def waitawhile():
print "Wait a while"
rain2 = raw_input("Is it still raining?")
if rain2.lower() == "no":
return "Go Outside"
elif rain2.lower() == "yes":
return waitawhile()
def Raining():
print "Is it raining?"
rain = raw_input()
if rain.lower() == "no":
return "Go Outside"
elif rain.lower() == "yes":
print "Have Umbrella?"
umbrella = raw_input()
if umbrella.lower() == "yes":
return "Go Outside"
elif umbrella.lower() == "no":
return waitawhile()
print Raining()
Works as below:
>>> ================================ RESTART ================================
>>>
Is it raining?
yes
Have Umbrella?
yes
Go Outside
>>> ================================ RESTART ================================
>>>
Is it raining?
yes
Have Umbrella?
no
Wait a while
Is it still raining?yes
Wait a while
Is it still raining?no
Go Outside
>>>
The problems in your program are logical error, so the interpreter will not show you a syntax error:
You used .lower instead of .lower() in the if condition, and it will be always false.
You ignored returns of waitawhile() method while you must return them to print method.

Related

Python 'if' statement not triggering correctly [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
For some reason, no matter what user_input is (Yes, No, "", eserw3) the first if statement will always be triggered. Any insight as to why the elif and the else never get activated? (The below code compiles perfectly without any errors)
Thank you in advance.
def retry():
user_input = raw_input("Would you like to face %s again? (Yes/No)" % (Enemy))
if user_input == "Yes" or "yes":
respawn()
getMove()
elif user_input == "No" or "no":
print "Thanks for playing!"
else:
print "Please enter either Yes or No."
def retry():
user_input = raw_input("Would you like to face %s again? (Yes/No)" % (Enemy))
if user_input == "Yes" or user_input == "yes":
respawn()
getMove()
elif user_input == "No" or user_input == "no":
print "Thanks for playing!"
else:
print "Please enter either Yes or No."
def retry():
user_input = raw_input("Would you like to face %s again? (Yes/No)" % (Enemy)).lower()
if user_input == "yes":
respawn()
getMove()
elif user_input == "no":
print "Thanks for playing!"
else:
print "Please enter either Yes or No."
Change your if condition to
user_input in ["Yes", "yes"]
Reason: When you write user_input == "Yes" or "yes", it evaluates as:
(user_input == "Yes") or "yes"
The second part of OR is a True always(non-zero length string). Hence your problem of if block executing always.

Exiting a program from an If/ELSE statement with Python

I am attempting to exit a program without using sys.exit()
The user is asked whether they wish to continue and if they input "Yes" a message saying so is printed and the program continues to run. If they input anything else a message saying they chose to exit is printed and then the program is meant to exit.
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
else:
print "You have chosen to quit this program"
What I am struggling with is what to add to ELSE to return something to my main which will cause the program to exit and how to go about writing that in code.
If you are so much keen about not using sys.exit() you could directly use raise SystemExit. Well this exception is technically raised when you call sys.exit() explicitly. In this way you don't need to import sys at all.
def keep_going():
answer = raw_input("Do you wish to continue?")
if (answer == "yes"):
print ("You have chosen to continue on")
else:
print "You have chosen to quit this program"
raise SystemExit
This answer will give you the alternate possible ways.
Try this:
def main():
while keep_going():
keep_going()
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
return True
else:
print "You have chosen to quit this program"
return False
if __name__ == "__main__":
main()
The program will continue calling keep_going() as long as it returns true, that is when a user answers "yes"
An even shorter solution would be to call keep_going() after the "yes" condition:
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
keep_going()
else:
print "You have chosen to quit this program"
Just, return something, and if that is returned, then let your main function exit, either by falling off the end, by using a return statement, or calling sys.exit()/raise SystemExit.
As an example, I'm here returning a string (a different one based on what the user answered):
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
return "keep going"
else:
print "You have chosen to quit this program"
return "please exit"
Now, in main, I can test which of these strings keep_going() returned:
def main():
while keep_going() != 'please exit':
# your code here
if __name__ == "__main__":
main()
While strings will work for this purpose, other values are more commonly used for such a task. If keep_going() returned True (instead of "keep going") or False (instead of "please exit"), then main could be written like
def main():
while keep_going():
# your code here
This also reads pretty naturally ("while keep going do your code"). Note that in this case I'm not comparing the return value to something since True and False are truthy variables - and Python's branching control structures (like if and while) know how they work, i.e. there is no need to write keep_going() == True, and indeed it is considered un-pythonic to do so.
You can try this
def keep_going():
answer = raw_input("Do you wish to continue?")
if answer == "yes":
print "You have chosen to continue on"
else:
print "You have chosen to quit this program"
quit()

Never ending While

In this code I try to call a function. On the other hand its not working the way I want it to work, for it is staying in the loop even though I am changing the loops condition options_secondscenario[0] from 0 to 1 at the end of the Loop. What I want this to do is to move to third_scenario() function. Thanks in advance.
options_secondscenario = ['Whats going on out there?', 'So what now?']
def third_scenario():
print "This is the third scenario"
choiceselection2 = raw_input("> ")
if choiceselection2 == 1:
print "stay"
else:
print "leave"
def dead():
print "You are dead"
exit()
def second_scenario():
print "Conversation 1"
print "Conversation 2"
print "Conversation 3"
print options_secondscenario
choices = options_secondscenario[0]
while choices == options_secondscenario[0]:
choiceselection = raw_input("> ")
if choiceselection == 'Whats going on out there?':
print "Conversation 4"
elif choiceselection == 'Whats up':
print "Nothing"
elif choiceselection == 'what is that':
print "I dont know"
elif choiceselection == 'is':
dead()
else:
third_scenario()
choices == options_secondscenario[1]
second_scenario()
You are trying to change your choices var AFTER the loop (check your indentation). So the while loop never gets a chance to reach this statement.
Also, you are using the compare operator == instead of the assignment operator = like so:
choices = options_secondscenario[1]
That line should be somewhere INSIDE your while loop. Check your indentation.

Python: Recursion, I keep getting the wrong value, what I can do?

def answer():
if True:
ans = raw_input('Enter y/n:')
if ans != "y" and ans != "n":
print "Try again"
answer()
elif ans == "n":
return False
elif ans == "y":
return True
if answer():
print "It's working!, you entered Y"
else:
print "You entered N"
When I execute this code, I press Enter several times or enter wrong letters, then I enter y, I always get "You entered N" instead of "It's working!, you entered Y" .
I can't figure out what's the problem, please help me.
You are discarding the return value of your function in the if block. You should change it to:
if ans != "y" and ans != "n":
print "Try again"
return answer()
If you don't return the value, your function will return None, which will be evaluated as False on the outer if. Also, there is no need of if True: inside your function.
P.S: Please avoid using recursion for this task. You can easily do this with a while loop, which iterates till the user doesn't pass correct input, and breaks as soon as succeeds. Also, give user a certain number of attempts to pass correct inputs, to avoid infinite loop.
You don't really need recursion in this case, just use an infinite loop and don't return if the answer is not "y" or "n":
def answer():
while True:
ans = raw_input('Enter y/n:')
if not ans or ans not in "yn":
print "Try again"
else:
return ans == "y" # This is more succinct
if answer():
print "It's working!, you entered Y"
else:
print "You entered N"

Elif and if not working or me not understanding [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 7 years ago.
Well my code is working, but when I type No if I want to retry to enter the password it doesn't work; it just goes to the enter password line (line 20). I have tried multiple ways to fix this but I simply cannot.
import time
import os
print ("Hello world.")
time.sleep(1)
print ("Waiting 5 seconds.")
time.sleep(5)
print ("You have waited 10 seconds.")
print ("Executing Chrome.")
time.sleep(1)
print ("Execution failed!")
password = input("Enter the execution password: ")
if password == 'password1234':
os.system ('C:\\Users\\Harry\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe')
else:
print ("Wrong password!")
time.sleep(1)
passretry = input("Do you want to try again? ")
if passretry == 'yes' or 'Yes':
passretry1 = input("Enter password: ")
if passretry1 == 'password1234':
os.system ('C:\\Users\\Harry\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe')
elif passretry == 'no' or 'No':
print ("Closing...")
time.sleep(1)
else:
print ("Wrong password.")
time.sleep(.5)
print ("Retry limit exceeded, closing.")
time.sleep(1)
if passretry == 'yes' or 'Yes':
the above if statement is evaluated as: -
if (passretry == 'yes') or 'Yes':
Now, since 'Yes' is evaluated to True, so, your if statement is always True, and hence you always have to enter new password.
You need to change the condition to: -
if passretry in ('yes', 'Yes'):
likewise, the following elif should be changed to: -
elif passretry in ('no', 'No'):
This condition:
if passretry == 'yes' or 'Yes':
means "If passretry == 'yes' is true, or 'Yes' is true". 'Yes' is always true, because a non-empty string counts as true. That's why you're always taking the first code path.
You need to spell things out a little more:
if passretry == 'yes' or passretry == 'Yes':
(Or to make your code a bit more general:
if passretry.lower() == 'yes':
which would allow for people shouting YES.)
You need another complete statement:
passretry == 'yes' or passretry == 'Yes':
The string 'Yes' always evaluates to True.

Categories