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

(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)

Related

Why is my while loop with if statements not working?

answer = "8"
print("What is 5 + 3 = ? ")
answer = input()
while (answer != "8"):
if (answer == "8"):
print("Correct answer!")
else:
print("Incorrect answer!")
Whenever I write the correct answer in the input, the print statement doesn't appear, whereas if I write the incorrect answer, it sends me an infinite amount of my else statement. How can I fix this?
The while loop is executing once for every time that answer != "8". So if you enter 8, it never executes because 8 always equals 8, and if you enter something else, then it executes an infinite number of times because something that does not equal 8 never equals 8. The solution here is to get rid of the while line.
You should move the input method inside the loop - you want the user to be able to input a new number in case the answer is wrong
Working code:
print("What is 5 + 3 = ? ")
while True:
answer = input()
if (answer == "8"):
print("Correct answer!")
break
else:
print("Incorrect answer!")
thats because the wile don't execute if the answer is "8".
You should Know as weel that every while loop should have a break statement .
if you want this code to just print if the result is correct or no you can just delete the while statement

If statement does not run even after user input

optionone = 0 #DEFINING BOTH VARIABLES
optiontwo = 0
class first_day_morning: #WORKING
optionone = input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ")
def first_choice(optionone): #NOT WORKING DOING ELSE COMMAND FOR 1 INPUT
if optionone == 1:
time.sleep(1)
print('')
print("You have chosen to get out of the house for once")
elif optionone == 2:
time.sleep(1)
print('')
print("DO LATER")
else:
time.sleep(1)
print('')
print("please choose a valid option")
first_choice(int(input()))
I am trying to make it so that the user input decides the outcome of the if statement, if user inputs 1, then something happens, if user inputs 2 then something else happens, if user inputs anything else, than the if statement runs again as only 1 or 2 are valid inputs. However, the problem is that no matter what the user inputs, the if statement does not run, and no error is shown either. I tried a try/except in case an error just isn't showing for some reason (try except ValueError:) and nothing seemed to work I have also tried to specify the input as str, int, float, no specification, raw_input etc. and nothing really works, can someone help?
ps. I am using Visual Studio Code
As you can see, the if statement does not run as no error is shown even after user input.
When the program runs, the class body will be evaluated, meaning the input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ") will prompt for input. That value will then be kept in first_day_morning.optionone, however first_choice's optionone is different. It is equal to the parameter supplied on the final line, int(input()), which will silently prompt for another input, and then convert it to an integer. From what I think you're trying to achieve, I'd recommend you remove the class and change the final line to:
first_choice(int(input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ")))
def first_choice():
print('')
print("You have chosen to get out of the house for once")
def second_choice():
print('')
print("DO LATER")
def third_choice():
print('')
print("please choose a valid option")
while True:
print("""Select a choice""")
c = int(input('enter your choice:'))
if c == 1:
first_choice()
elif c == 2:
second_choice()
elif c == 3:
third_choice()
elif c == 4:
break
i dont really understand what u r trying to acomplish here, but the code works for me, some tips from a beginer:
-you define optiontwo and never use it
-you you are filling optionone with input inside a class, dont know why, cause is never used
not sure what do u want, but try this:
import time
def first_choice(optionone): #NOT WORKING DOING ELSE COMMAND FOR 1 INPUT
if optionone == 1:
time.sleep(1)
print('')
print("You have chosen to get out of the house for once")
elif optionone == 2:
time.sleep(1)
print('')
print("DO LATER")
else:
time.sleep(1)
print('')
print("please choose a valid option")
first_choice(int(input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ")))
although, test it in console, not sure about vscode but running inside sublime does not ask for input

Python 3.X - only take number from user input [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
I am stuck on a problem that I am trying to solve. I am only suppose to take int (1-4) from user's input and not take any string/float/etc. I have figured out what to do if a user chooses any integer other than 1-4. However, I am stuck on the part where a user chooses anything other than an integer (i.e string, float, etc).
this is what I have done so far:
def menu():
my code
menu()
# keeps on looping till user have selected a proper selection (1-4)
selection = int(input("> "))
if selection == 1:
my code
elif selection == 2:
my code
elif selection == 3:
my code
elif selection == 4:
my code
else:
print("I'm sorry, that's not a valid selection. Please enter a
selection from 1-4. ")
menu()
Any help would be appriciated. I've been trying to find a solution for hours but got stuck on the last part.
Seeing as you don't appear to be doing any integer operations on the value coming from input - I would personally just leave it as a string.
selection = input("> ")
if selection == "1":
pass
elif selection == "2":
pass
#...
else:
print("I'm sorry...")
By doing this you don't have to deal with that edge case at all.
If you must (for some reason) cast this to an int (like, you're using the value later) then you could consider using exception handling.
try:
selection = int(input("> "))
except ValueError:
selection = "INVALID VALUE"
and the continue you on, as your current else statement will catch this and correctly handle it.
try this If you make sure that your code allows the user to input only numbers in python:
def numInput():
try:
number = int(input("Tell me a number"))
except:
print "You must enter a number"
numInput()
return number
You can use an infinite loop to keep asking the user for an integer within the desired range until the user enters one:
while True:
try:
selection = int(input("> "))
if 1 <= selection <= 4:
break
raise RuntimeError()
except ValueError, RuntimeError:
print("Please enter a valid integer between 1 and 4.")

I need to figure out how to make my program repeat. (Python coding class)

I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.

Python yes/no def

I'm using the example below:
APT command line interface-like yes/no input?
I want to make it its own definition as outlined then call it upon demand, like this:
def log_manager():
question = "Do you wish to continue?"
choice = query_yes_no_quit(question, default="yes")
if choice == 'y':
print ("you entered y")
else:
print ("not working")
Regardless of what I input, "not working" is always printed. Any guidance would be really appreciated!
The function returns True/False. So use if choice:
Btw, you could have easily found out the solution on your own by adding print choice ;)
Use:
if choice:
print("you entered y")
else:
print("not working")
the function returns True / False, not "y" / "n".

Categories