Looping program based on user string input not gett - python

I need this program to do one of two things from my repeat function, but it should be able to do both and I can't work out why.
It must do 2 things
make it rerun my main() subprogram,
or say "Goodbye." and close the entire program,
whichever one comes first.
I have tried making it just an if-else statement rather than if-elif-else, which didn't change anything, I have also tried rearranging the code, but that only changes the single output I can get from the subprogram. This is the subprogram currently:
def repeatloop():
repeat = input("Do you want to calculate another bill? (y/n): ")
if repeat == 'n' or 'N':
print("Goodbye.")
time.sleep(2)
sys.exit()
elif repeat == 'y' or 'Y':
main()
else:
print("Error. Program will shut down.")
time.sleep(2)
sys.exit()
It should be able to repeat the program (based on the y or Y input), terminate the program and display "Goodbye." based on the n or N input or it should display the "Error. Program will shut down." message before closing if an invalid input is entered.
Many thanks to whoever can help me!

You may use in () for the comparison with a list. It compares the value of the variable with the list.
def repeatloop():
repeat = input("Do you want to calculate another bill? (y/n): ")
if repeat in ('n','N'):
print("Goodbye.")
time.sleep(2)
sys.exit()
elif repeat in ('y','Y'):
main()
else:
print("Error. Program will shut down.")
time.sleep(2)
sys.exit()

if repeat == 'n' or 'N' doesn't work, since you are checking bool('N') which is always true, the same holds true for repeat == 'y' or 'Y', since
bool('Y') is always true.
You start by checking if repeat is in the list ['n','N'], or is not in the list ['y','Y'], then you exit the program, else you call the same function repeatloop
import time, sys
def repeatloop():
repeat = input("Do you want to calculate another bill? (y/Y/n/N): ")
if repeat in ['n', 'N']:
print("Goodbye.")
time.sleep(2)
sys.exit()
elif repeat in ['y', 'Y']:
repeatloop()
else:
print("Error. Program will shut down.")
time.sleep(2)
sys.exit()
repeatloop()

Hello and welcome to Stackoverflow.
Your problem is that your if statements are not exactly correct; and also your whole function is not correctly indented.
if repeat == 'n' or 'N' is different from if repeat == 'n' or repeat == 'N'.
In the second case, you test two different statements on the repeat keyword, where on the first one you're seeing whether:
repeat is equal to n, and also
'N' is not None; which isn't & this case always returns true.
Another way to do it could be if repeat in ["n", "N"] or even better: if repeat.lower() == 'n'
So put it all together, your code should be refined to:
def repeatloop():
repeat = input("Do you want to calculate another bill? (y/n):")
if repeat.lower() == 'n':
print("Goodbye.")
time.sleep(2)
sys.exit()
elif repeat.lower() == 'y':
main()
else:
print("Error. Program will shuts down.")
time.sleep(2)
sys.exit()

Related

I'm trying to quit a python program with q or Q as an option [duplicate]

Im a middle school student, and im starting to learn coding in python. I have been watching video tutorials, but i cant seem to figure out how to make the game quit if you type q. here what i have..
print('How old do you thing Fred the Chicken is?')
number = 17
Quit = q
run = 17
while run:
guess = int(input('Enter What You Think His Age Is....'))
print('How old do you thing Fred the Chicken is?')
number = 17
Quit = 'q'
run = 17
while run:
guess = int(input('Enter What You Think His Age Is....'))
if guess == number:
print('Yes :D That is his age...')
run = False
elif guess < number:
print('No, Guess a little higher...')
elif guess > number:
print('No, Guess a little lower....')
print('Game Over')
print('Press Q to Quit')
if run == False:
choice = input('Press Q to Quit')
if choice == 'q'
import sys
exit(0)
Getting Q as input
Quit = int(input('Press Q to Quit')
You're asking for Q as the input, but only accepting an int. So take off the int part:
Quit = input('Press Q to Quit')
Now Quit will be whatever the user typed in, so let's check for "Q" instead of True:
if Quit == "Q":
Instead of sys.exit(0), you can probably just end your while look with break or just return if you're in a function.
Also, I don't recommend the name "Quit" for a variable that just stores user input, since it will end up confusing.
And remember that indentation is important in Python, so it needs to be:
if run == False:
choice = input('Press Q to Quit')
if choice == "Q":
# break or return or..
import sys
sys.exit(0)
That may just be a copy/paste error though.
Indentation and Syntax
I fixed the indentation and removed some extraneous code (since you duplicate the outer loop and some of the print statements) and got this:
print('How old do you thing Fred the Chicken is?')
number = 17
run = True
while run:
guess = int(input('Enter What You Think His Age Is....t'))
if guess == number:
print('Yes :D That is his age...')
run = False
elif guess < number:
print('No, Guess a little higher...')
elif guess > number:
print('No, Guess a little lower....')
if run == False:
print('Game Over')
choice = input('Press Q to Quit')
if choice == 'q'
break
This gave me a syntax error:
blong#ubuntu:~$ python3 chicken.py
File "chicken.py", line 23
if choice == 'q'
^
SyntaxError: invalid syntax
So Python is saying there's something wrong after the if statement. If you look at the other if statements, you'll notice that this one is missing the : at the end, so change it to:
if choice == 'q':
So with that change the program runs, and seems to do what you want.
Some suggestions
Your instructions say "Press Q to Quit", but you actually only accept "q" to quit. You may want to accept both. Python has an operator called or, which takes two truth values (True or False) and returns True if either of them is True (it actually does more than this with values besides True and False, see the documentation if you're interested).
Examples:
>> True or True
True
>>> True or False
True
>>> False or True
True
>>> False or False
False
So we can ask for Q or q with if choice == "Q" or choice == "q":.
Another option is to convert the string to lower case and only check for q, using if choice.lower() == "q":. If choice was Q, it would first convert it to q (with the .lower()), then do the comparison.
Your number is always 17. Python has a function called random.randint() that will give you a random number, which might make the game more fun. For example, this would make the chicken's age between 5 and 20 (inclusive):
number = random.randint(5, 20)
There are many ways to exit certain things. For loops, it is using break, and for functions you can use return. However, for programs, if you wish to exit your program before interpretation finishes (end of the script) there are two different types of exit() functions. There is sys.exit() which is part of the sys module, and there is exit() and quit() which is a built-in. However, sys.exit() is intended for programs not in IDLE (python interactive), while the built-in exit() and quit() functions are intended for use in IDLE.
You can use the break statement to break out of a while loop:
while True:
guess = int(input("...")
# ...rest of your game's logic...
# Allow breaking out of the loop
choice = input("Enter Q to quit, or press return to continue")
if choice.lower() == "q":
break
That means the interpreter exits the while loop, continues looking for more commands to run, but reaches the end of the file! Python will then exit automatically - there's no need to call sys.exit
(as an aside, you should rarely use sys.exit, it's really just used to set non-zero exit-status, not for controlling how your program works, like escaping from a while loop)
Finally, the main problem with the code you posted is indentation - you need to put the appropriate number of spaces at the start of each line - where you have something like:
if run == False:
choice = input('Press Q to Quit')
It must be like this:
if run == False:
choice = input('Press Q to Quit')
Same with anything like while, for, if and so on.

I want to setup a would you like to retry

I have created a guess the number game, at the end of it I want it to ask the user if they would like to retry. I got it to take invalid responses and if Yes then it will carry on, but when I say no it still carries on.
import random
from time import sleep
#Introduction & Instructions
print ("Welcome to guess the number")
print ("A random number from 0 - 1000 will be generated")
print ("And you have to guess it ")
print ("To help find it you can type in a number")
print ("And it will say higher or lower")
guesses = 0
number = random.randint(0, 1)#Deciding the number
while True:
guess = int (input("Your guess: "))#Taking the users guess
#Finding if it is higher, lower or correct
if guess < number:
print ("higher")
guesses += 1
elif guess > (number):
print ("lower")
guesses += 1
elif guess == (number):
print ("Correct")
print (" ")
print ("It took you {0} tries".format(guesses))
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer in ('y', 'n'):
break
print ('Invalid input.')
if answer == 'y':
continue
if answer == 'n':
exit()
First of all, when you check :
if answer in ('y','n'):
This means that you are checking if answer exists in the tuple ('y','n').
The desired input is in this tuple, so you may not want to print Invalid input. inside this statement.
Also, the break statement in python stops the execution of current loop and takes the control out of it. When you breaked the loop inside this statement, the control never went to the printing statement or other if statements.
Then you are checking if answer is 'y' or 'n'. If it would have been either of these, it would have matched the first statement as explained above.
The code below will work :
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer == 'y':
break
elif answer == 'n':
exit()
else:
print ('Invalid input.')
continue
Also, you might want to keep the number = random.randint(0, 1)#Deciding the number statement inside the while loop to generate a new random number everytime the user plays the game.
This is because of the second while loop in your code. Currently when you put y or n it will break and run again (you don't see the invalid message due to the break occurring before reaching that code), it should be correct if you change it to the following:
while True:
answer = input('Run again? (y/n): ')
# if not answer in ('y', 'n'):
if answer not in ('y', 'n'): # edit from Elis Byberi
print('Invalid input.')
continue
elif answer == 'y':
break
elif answer == 'n':
exit()
Disclaimer: I have not tested this but it should be correct. Let me know if you run into a problem with it.

Yes or No answer from user with Validation and restart option?

(py) At the moment, the code below does not validate/output error messages when the user inputs something other than the two choices "y" and "n" because it's in a while loop.
again2=input("Would you like to calculate another GTIN-8 code? Type 'y' for Yes and 'n' for No. ").lower() #**
while again2 == "y":
print("\nOK! Thanks for using this GTIN-8 calculator!\n\n")
restart2()
break #Break ends the while loop
restart2()
I'm struggling to think of ways that will allow me to respond with an output when they input neither of the choices given. For example:
if again2 != "y" or "n"
print("Not a valid choice, try again")
#Here would be a statement that sends the program back to the line labelled with a **
So, when the user's input is not equal to "y" or "n" the program would return to the initial statement and ask the user to input again. Any ideas that still supports an efficient code with as little lines as possible? Thanks!
def get_choice(prompt="Enter y/n?",choices=["Y","y","n","N"],error="Invalid choice"):
while True:
result = input(prompt)
if result in choices: return result
print(error)
is probably a nice generic way to approach this problem
result = get_choice("Enter A,B, or C:",choices=list("ABCabc"),error="Thats not A or B or C")
you could of coarse make it not case sensitive... or add other types of criteria (e.g. must be an integer between 26 and 88)
A recursive solution:
def get_input():
ans = input('Y/N? ') #Use raw_input in python2
if ans.lower() in ('y', 'n'):
return ans
else:
print('Please try again.')
return get_input()
If they're really stubborn this will fail when it reaches maximum recursion depth (~900 wrong answers)

How to not make a loop close when giving an empty input

In my current Python project I utilize a loop via a while loop and have an input function inside of it. Thus far I've defined three different things that happen based on the use input using IF, and I've managed to use an ELSE to print a message when said input doesn't do anything.
However, when the input remains empty and is entered the loop breaks and I get an IndexError based on the if action[0] == "go": line. Here's the code I'm using:
while True:
action = input("? ").lower().split()
#user puts in one of the words below plus a direction
if action[0] == "go":
#stuff happens
if action[0] == "get" :
#stuff happens
if action[0] == "exit":
break
else:
print("Please try again.")
This code works, but as above if I just press enter or input nothing but spaces the loop breaks and I get an IndexError. How can I fix this?
If you input nothing, split is giving you an empty list, so it throws an index error when you try to index it. The solution is just to check if the input is empty, and if so, skip the other conditions and continue iterating. if action == []: break accomplishes this task.
while True:
action = input("? ").lower().split()
#user puts in one of the words below plus a direction
if action == []:
continue
if action[0] == "go":
#stuff happens
if action[0] == "get" :
#stuff happens
if action[0] == "exit":
break
else:
print("Please try again.")
Try to use this condition at the beginning of your loop:
if not action:
print("Please try again.")
continue

Python: How do I get my function to repeat until asked to cancel?

I just started learning Python. Basically I just want to repeat the loop once if answer is yes, or break out of the loop if answer is no. The return True/False doesn't go back to the while loop?
def userinfo():
while true:
first_name=input("Enter your name here:")
last_name=input("Enter your last name:")
phonenum=input("Enter your phone number here")
inputagain=rawinput("Wanna go again")
if inputagain == 'no':
return False
userinfo()
Instead of while true: use a variable instead.
Such as
while inputagain != 'no':
Instead of looping forever and terminating explicitly, you could have an actual condition in the loop. First assume that the user wants to go again by starting again as 'yes'
again = 'yes'
while again != 'no':
# ... request info ...
again = input("Wanna go again?: ")
though this while condition is a bit weak, if the user enters N, n, no or ever no with space around it, it will fail. Instead you could check if the first letter is an n after lowercasing the string
while not again.lower().startswith('n'):
You could stick to your original style and make sure the user always enters a yes-like or no-like answer with some extra logic at the end of your loop
while True:
# ... request info ...
while True:
again = input("Wanna go again?: ").lower()
if again.startswith('n'):
return # exit the whole function
elif again.startswith('y'):
break # exit just this inner loop

Categories