How do you stop a loop when a condition is met? - python

I'm a complete newbie to the coding trying my hands on python. While coding a simple program to calculate the age I ran into an error I cannot seem to fix no matter how hard I try. The code is pasted below. The program runs as far as I enter an year in the future, however when an year which has passed is used, the code loops again asking if the year is correct. Any help is appreciated.
from datetime import date
current_year = (date.today().year)
print('What is your age?')
myAge = input()
print('future_year?')
your_age_in_a_future_year= input()
future_age= int(myAge)+ (int(your_age_in_a_future_year)) - int(current_year)
def process ():
if future_age > 0:
print(future_age)
else:
print('do you really want to go back in time?, enter "yes" or "no"')
answer = input()
if answer =='yes':
print (future_age)
if answer == 'no':
print ('cya')
while answer != 'yes' or 'no':
print ('enter correct response')
process ()
process()

In this case, your function just needs to contain a while loop with an appropriate condition, and then there is no need to break out from it, or do a recursive call or anything.
def process():
if future_age > 0:
print(future_age)
else:
print('do you really want to go back in time?, enter "yes" or "no"')
answer = None
while answer not in ('yes', 'no'):
answer = input()
if answer == 'yes':
print(future_age)
elif answer == 'no':
print('cya')

try
...
if future_age > 0:
print(future_age)
return
else:
print('do you really want to go back in time?, enter "yes" or "no"')
...

Related

How to restart a program from the top of a Python program? [duplicate]

I'm trying to restart a program using an if-test based on the input from the user.
This code doesn't work, but it's approximately what I'm after:
answer = str(raw_input('Run again? (y/n): '))
if answer == 'n':
print 'Goodbye'
break
elif answer == 'y':
#restart_program???
else:
print 'Invalid input.'
What I'm trying to do is:
if you answer y - the program restarts from the top
if you answer n - the program ends (that part works)
if you enter anything else, it should print 'invalid input. please enter y or n...' or something, and ask you again for new input.
I got really close to a solution with a "while true" loop, but the program either just restarts no matter what you press (except n), or it quits no matter what you press (except y). Any ideas?
This line will unconditionally restart the running program from scratch:
os.execl(sys.executable, sys.executable, *sys.argv)
One of its advantage compared to the remaining suggestions so far is that the program itself will be read again.
This can be useful if, for example, you are modifying its code in another window.
Try this:
while True:
# main program
while True:
answer = str(input('Run again? (y/n): '))
if answer in ('y', 'n'):
break
print("invalid input.")
if answer == 'y':
continue
else:
print("Goodbye")
break
The inner while loop loops until the input is either 'y' or 'n'. If the input is 'y', the while loop starts again (continue keyword skips the remaining code and goes straight to the next iteration). If the input is 'n', the program ends.
Using one while loop:
In [1]: start = 1
...:
...: while True:
...: if start != 1:
...: do_run = raw_input('Restart? y/n:')
...: if do_run == 'y':
...: pass
...: elif do_run == 'n':
...: break
...: else:
...: print 'Invalid input'
...: continue
...:
...: print 'Doing stuff!!!'
...:
...: if start == 1:
...: start = 0
...:
Doing stuff!!!
Restart? y/n:y
Doing stuff!!!
Restart? y/n:f
Invalid input
Restart? y/n:n
In [2]:
You can do this simply with a function. For example:
def script():
# program code here...
restart = raw_input("Would you like to restart this program?")
if restart == "yes" or restart == "y":
script()
if restart == "n" or restart == "no":
print "Script terminating. Goodbye."
script()
Of course you can change a lot of things here. What is said, what the script will accept as a valid input, the variable and function names. You can simply nest the entire program in a user-defined function (Of course you must give everything inside an extra indent) and have it restart at anytime using this line of code: myfunctionname(). More on this here.
Here's a fun way to do it with a decorator:
def restartable(func):
def wrapper(*args,**kwargs):
answer = 'y'
while answer == 'y':
func(*args,**kwargs)
while True:
answer = raw_input('Restart? y/n:')
if answer in ('y','n'):
break
else:
print "invalid answer"
return wrapper
#restartable
def main():
print "foo"
main()
Ultimately, I think you need 2 while loops. You need one loop bracketing the portion which prompts for the answer so that you can prompt again if the user gives bad input. You need a second which will check that the current answer is 'y' and keep running the code until the answer isn't 'y'.
It is very easy do this
while True:
#do something
again = input("Run again? ")
if 'yes' in again:
continue
else:
print("Good Bye")
break
Basically, in this the while loop will run the program again and again because while loops run if the condition is True so we have made the condition true and as you know True is always true and never false. So, will not stop then after this the main part comes here first we will take input from the user whether they want to continue the program or not then we will say that if user says yes i want to continue then the continue keyword will bring the loop to the top again and will run the program again too and if the user says something else or you can do it in another way if you want to only quit the program if user says no then just add this
elif 'no' in again:
print("Good Bye")
break
else:
print("Invalid Input")
this will look that if there is the 'no' word in the input and if there is then it will break the loop and the program will quit

How do you call a variable that was returned at the end of a function?

I created this function and want to call the returned result but, I'm not sure how to get the variable back. If possible I'd also like a different message to pop up if the user types n. Could anyone help?
def give_entertainment():
random_form_of_entertainment = random.choice(form_of_entertainment)
good_user_input = "y"
while good_user_input == "y":
user_input = input(f"We have chosen {random_form_of_entertainment} for your entertainment! Sound good? y/n: ")
if good_user_input != user_input:
random_form_of_entertainment = random.choice(form_of_entertainment)
continue
else:
print("Awesome! Glad we got that figured out. Your trip is all planned! ")
return random_form_of_entertainment
x = give_entertainment()
Should store the return of your function into x.
With:
print(x)
you should see what's stored in your x variable.
Call the method while assigning it to a variable.
some_var = your_method()
Now this some_var variable have the returning value.
I'd personally use a recursive function for this, I made it work with y/n/invalid_input cases. Also with this an invalid input won't update random_form_of_entertainment so the user has to say y or n for it to change. I hope this is what you're looking for!
def give_entertainment():
random_form_of_entertainment = random.choice(forms_of_entertainment)
good_user_input = "y"
bad_user_input = "n"
invalid_input = True
while invalid_input:
user_input = input(f'We have chosen {random_form_of_entertainment} for your entertainment! Sound good? y/n: ')
if user_input == good_user_input:
print("Awesome! Glad we got that figured out. Your trip is all planned for!")
return random_form_of_entertainment
elif user_input == bad_user_input:
print("Sorry to hear that, let me try again...")
return give_entertainment()
else:
print("I don't recognize that input, please try again.")
continue
chosen_result = give_entertainment()
print(f'You chose {chosen_result}!')

How to have if and elif in functions

First off. My code:
UserInput = ("null") #Changes later
def ask_module(param, param2):
elif UserInput == (param):
print(param2)
while True:
UserInput = input()
UserInput = UserInput.lower()
print()
if UserInput == ("test"):
print("test indeed")
ask_module("test2", "test 2")
I am not that good at coding, so this is probably something that I have done really wrong
This post seems a bit duchy, since I almost just have code,
but I have absolutely no idea on how to make this work.
What the code looks like without shortening:
while True:
UserInput = input()
UserInput = UserInput.lower()
print()
if UserInput == ("inventory"):
print("You have %s bobby pin/s" %bobby_pin)
print("You have %s screwdriver/s" %screwdriver)
elif UserInput == ("look at sink"):
print("The sink is old, dirty and rusty. Its pipe has a bobby pin connected")
else:
print("Did not understand that")
EDIT: I see that it might be hard to see what I'm asking.
I'm wondering how I can shorten my original code
If all your elif blocks have the same pattern, you can take advantage of this.
You can create a dictionary for the text you want to print and then do away with the conditionals.When it comes to choosing which one to print, you simply fetch the relevant text using its corresponding key. You use the get(key, default) method. If there is no key in the dictionary, the default value will be returned. For example,
choices = {'kick': 'Oh my god, why did you do that?',
'light him on fire': 'Please stop.',
'chainsaw to the ribs': 'I will print the number %d',
}
user_input = input().lower()
# individually deal with any strings that require formatting
# and pass everything else straight to the print command
if user_input == 'chainsaw to the ribs':
print(choices[user_input] % 5)
else:
print(choices.get(user_input, 'Did not understand that.'))
I found a solution, just stop using elif entirely.
Example:
userInput = "null"
def ask_question(input, output):
if userInput == (input):
print(output)
else: pass
while True:
userInput = input()
ask_question("test","test")
ask_question("test2", "test2")
ask_question("test3", "test3")

Nothing happens for either input

I have a feeling I've made a silly mistake somewhere but at nearly 2am I just can't see it...
Here's the code in question. It is part of a function:
running = True
while (running):
playerName = input("Please enter your first name \n").title()
print ("You have entered '%s' as your name. Is this correct?"%playerName)
playerNameChoice = input("Enter 'Y' for Yes or 'N' for No.\n").upper()
if(playerNameChoice == "Y"):
break
#The following randomly selects Card 1 for the computer
randomComputerCard = random.choice(availableCards)
if randomComputerCard in (Queen,King,Jack,Ace):
randomComputerCard = 10
else:
randomComputerCard = randomComputerCard
randomComputerCard2 = random.choice(availableCards)
if randomComputerCard2 in (Queen,King,Jack,Ace):
randomComputerCard2 = 10
else:
randomComputerCard2 = randomComputerCard2
print ("%i"%randomComputerCard)
print ("%i"%randomComputerCard2)
print ("TEST OVER")
elif(playerNameChoice == "N"):
continue
During testing when I enter Y when prompted to enter either Y or N nothing happens, it just continues the loop when it should actually break. However when I enter N it does exactly what it's meant to and continues the loop. Sorry if this is a waste of a question, but I actually have no idea what I've done incorrectly.
Thanks in advance as always! :)
EDIT: The variable availableCards has already been defined.
You need to remove the 'break' at line 7. That's causing your code to exit prematurely.

How do I restart a program based on user input?

I'm trying to restart a program using an if-test based on the input from the user.
This code doesn't work, but it's approximately what I'm after:
answer = str(raw_input('Run again? (y/n): '))
if answer == 'n':
print 'Goodbye'
break
elif answer == 'y':
#restart_program???
else:
print 'Invalid input.'
What I'm trying to do is:
if you answer y - the program restarts from the top
if you answer n - the program ends (that part works)
if you enter anything else, it should print 'invalid input. please enter y or n...' or something, and ask you again for new input.
I got really close to a solution with a "while true" loop, but the program either just restarts no matter what you press (except n), or it quits no matter what you press (except y). Any ideas?
This line will unconditionally restart the running program from scratch:
os.execl(sys.executable, sys.executable, *sys.argv)
One of its advantage compared to the remaining suggestions so far is that the program itself will be read again.
This can be useful if, for example, you are modifying its code in another window.
Try this:
while True:
# main program
while True:
answer = str(input('Run again? (y/n): '))
if answer in ('y', 'n'):
break
print("invalid input.")
if answer == 'y':
continue
else:
print("Goodbye")
break
The inner while loop loops until the input is either 'y' or 'n'. If the input is 'y', the while loop starts again (continue keyword skips the remaining code and goes straight to the next iteration). If the input is 'n', the program ends.
Using one while loop:
In [1]: start = 1
...:
...: while True:
...: if start != 1:
...: do_run = raw_input('Restart? y/n:')
...: if do_run == 'y':
...: pass
...: elif do_run == 'n':
...: break
...: else:
...: print 'Invalid input'
...: continue
...:
...: print 'Doing stuff!!!'
...:
...: if start == 1:
...: start = 0
...:
Doing stuff!!!
Restart? y/n:y
Doing stuff!!!
Restart? y/n:f
Invalid input
Restart? y/n:n
In [2]:
You can do this simply with a function. For example:
def script():
# program code here...
restart = raw_input("Would you like to restart this program?")
if restart == "yes" or restart == "y":
script()
if restart == "n" or restart == "no":
print "Script terminating. Goodbye."
script()
Of course you can change a lot of things here. What is said, what the script will accept as a valid input, the variable and function names. You can simply nest the entire program in a user-defined function (Of course you must give everything inside an extra indent) and have it restart at anytime using this line of code: myfunctionname(). More on this here.
Here's a fun way to do it with a decorator:
def restartable(func):
def wrapper(*args,**kwargs):
answer = 'y'
while answer == 'y':
func(*args,**kwargs)
while True:
answer = raw_input('Restart? y/n:')
if answer in ('y','n'):
break
else:
print "invalid answer"
return wrapper
#restartable
def main():
print "foo"
main()
Ultimately, I think you need 2 while loops. You need one loop bracketing the portion which prompts for the answer so that you can prompt again if the user gives bad input. You need a second which will check that the current answer is 'y' and keep running the code until the answer isn't 'y'.
It is very easy do this
while True:
#do something
again = input("Run again? ")
if 'yes' in again:
continue
else:
print("Good Bye")
break
Basically, in this the while loop will run the program again and again because while loops run if the condition is True so we have made the condition true and as you know True is always true and never false. So, will not stop then after this the main part comes here first we will take input from the user whether they want to continue the program or not then we will say that if user says yes i want to continue then the continue keyword will bring the loop to the top again and will run the program again too and if the user says something else or you can do it in another way if you want to only quit the program if user says no then just add this
elif 'no' in again:
print("Good Bye")
break
else:
print("Invalid Input")
this will look that if there is the 'no' word in the input and if there is then it will break the loop and the program will quit

Categories

Resources