Creating A Class/Def For A If Else Statement Python - python

so I'm making a simple python program to ask maths questions. It is currently fully working but I want to try and condense the code down. The user has an option of 6 menu items to pick from, each one of these is an Addition, Subtraction, Multiplication..... And each one of them has the following code at the end to check if the user wants to carry on or try a different menu item.
contC = input()
if contC == "Y" or contC == "y":
cont = True
elif contC == "N" or contC =="n":
cont = False
This code is being in every menu choice, I want to create one method to be able to use for all of them, a class or a def? I've tried different things but can't seem to get anything to work.

Try using:
def AskMethod(Operation):
while True:
print("Do you want to do " + Operation.name)
Answer = input()
if Answer.lower() in 'yes':
Operation.use() # Or return Operation. However you do it
return False
elif Answer.lower() in 'no':
return True
else:
print("Please choose yes or no.")
for i in Ops:
Continue = Ask(i)
if Continue == False:
break
To use this, you will need to make an op class, and an ops array containing all of the operations you want. You must add self.name and self.use as well. Hope I helped.

Just make a method
def should_continue(user_input):
if user_input in ('y', 'Y'):
return True
if user_input in ('n', 'N'):
return False
raise ValueError("please enter y/n")
and then just
user_text = input()
cont = should_continue(user_input)

Related

yes/no loop not working properly when i used OR keyword [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 3 months ago.
I was using a yes/no loop to make an infinite loop which would end when user enters no or No but the program was not working properly. I know the what the error is but i don't know why is it occuring like this. Can anyone tell how to fix the error without changing my initial program
when i use this code it works but when i use if a=='yes' or 'Yes' and elif a=='no' or 'No' in the somehow the output shows the print statement of the if statement even when i enter no.
My program without the OR condition
while True:
a = input("Enter yes/no to continue")
if a=='yes':
print("enter the program")
elif a=='no':
print("EXIT")
break
else:
print("Enter either yes/no")
My initial program with OR condition
while True:
a = input("Enter yes/no to continue")
if a=='yes' or 'Yes':
print("enter the program")
elif a=='no' or 'No':
print("EXIT")
break
else:
print("Enter either yes/no")
In an or statement you have to compare a with the value in all expressions:
while True:
a = input("Enter yes/no to continue")
if a == 'yes' or a == 'Yes':
print("enter the program")
elif a == 'no' or a == 'No':
print("EXIT")
break
else:
print("Enter either yes/no")
A more pythonic way is to use .lower() in your case. For example:
a == 'yes' or a == 'Yes' # is equeal to:
a.lower() == 'yes'
You have a few options:
while True:
a = input("Enter yes/no to continue")
if a.lower()=='yes':
print("enter the program")
elif a.lower()=='no':
print("EXIT")
break
else:
print("Enter either yes/no")
or you can do this:
while True:
a = input("Enter yes/no to continue")
if a=='yes' or a=='Yes':
print("enter the program")
elif a=='no' or a=='No':
print("EXIT")
break
else:
print("Enter either yes/no")
When you use or, you should write complete condition again.
Here if you want to check a=="Yes" also, you should declare it completely.
if a == 'yes' or a == 'Yes':
...
You can also use this:
if a.lower() == 'yes'
...

Trying to make a recursive function to get a y/n answer from the user, but when it recurs the check stops working

The expected output is that it will recur until the user gives a yes or no answer, and if they give yes execute code, in this case just print "yep". everything works if the user inputs "Y" right away, but when the input is illegal and the program asks for another input the user input check stops working.
Example:
(Y/N) y
yep
ends
(Y/N) illegal
Something went wrong, make sure you made the right input and try again!
(Y/N) y
ends
What am I doing wrong ?
def user_choice():
answer = input("(Y/N) ")
if answer.lower() == "n": return False
elif answer.lower() == "y": return True
else:
print("Something went wrong, make sure you made the right input and try again!")
user_choice()
if user_choice(): print("yep")
Couple things:
You're missing the a line with the function signature in your code. I'll assume it's supposed to look like this:
def user_choice():
You're not returning anything when the code takes the else path, so nothing gets returned when the initial choice is illegal (actually None gets returned). So update your function like so:
answer = input("(Y/N) ")
if answer.lower() == "n": return False
elif answer.lower() == "y": return True
else:
print("Something went wrong, make sure you made the right input and try again!")
return user_choice() # <-- need to return a meaningful value here
Recursion is a terrible choice for solving this type of problem. A loop is simpler to write, easier to read, and performs better:
def user_choice():
while True:
answer = input("(Y/N) ")
if answer.lower() == "n": return False
elif answer.lower() == "y": return True
print("Something went wrong, make sure you made the right input and try again!")
Don't do this recursively. That's simply the wrong choice. The solution to your immediate problem is that you need return user_choice() not just user_choice(), but an iterative solution is much smarter:
def user_choice():
while True:
answer = input("(Y/N) ")
if answer.lower() == "n":
return False
elif answer.lower() == "y":
return True
else:
print("Something went wrong, make sure you made the right input and try again!")
if user_choice():
print("yep")
You did not return the result of the recursion. You can use something like this.
def user_choice():
answer = input("(Y/N) ")
if answer.lower() == "n": return False
elif answer.lower() == "y": return True
else:
print("Something went wrong, make sure you made the right input and try again!")
user_choice()
if user_choice(): print("yep")

Converting user input to a boolean and raising an error in Python?

I am working with Python version 3.7.4. I am working on a piece of code that requires user input in the form of yes or no, as follows:
isValid = input("Is this a previous version? (y/n)")
I would like to convert this yes or no question into a boolean response. I have seen this one possibility that I am interested in implementing:
isValid = False if input("Is this a previous version? (y/n)").lower() == 'n' else True
I also want to account for if the user were to give an input other than y or n, though. Ideally, I would like to raise an error if they were to give an input. Could someone show me to how to implement a boolean variable isValid like this in a concise way, or would I have to create another method that would check the user input? Thank you in advance. I can add more details if needed.
This is a bit more verbose, but will force the user to enter y or n and keep asking until they do:
isValid = input("Is this a previous version? (y/n)")
try:
while isValid is not True or False:
if isValid.lower() == 'y':
isValid == True
break
elif isValid.lower() == 'n':
isValid == False
break
else:
print("please select y or n")
isValid = input("Is this a previous version? (y/n)")
except:
print("Please select a valid response")
Maybe something along these lines?
isValid = input("Is this a previous version? (y/n)").lower() in ['y', 'n']
# if isValid: ... do whatever else: raise error
You could do something like this but it is quite ugly and I don't recommend it at all:
def raiser(ex): raise ex
my_input = input("Is this a previous version? (y/n)").lower()
isValid = False if my_input == 'n' else True if my_input == 'y' else raiser(Exception)
One of the best way to do something like this is a simple if/elif/else:
my_input = input("Is this a previous version? (y/n)")
if my_input == "y":
isValid = True
elif my_input == "n":
isValid = False
else:
raise Exception
A single line way to get a boolean as well as to raise an Exception.
ans = input('y/n : ').lower(); ans1 = False if ans=='n' else (True if ans=='y' else exec('raise(ValueError)'))
ans1 is the boolean answer.

Go to a specific raw_input()?

So I'm trying to figure out how I can make this simple little program to go back to the raw_input if the user inputs something else then "yes" or "no".
a = raw_input("test: ")
while True:
if a == "yes":
print("yeyeye")
break
elif a == "no":
print("nonono")
break
else:
print("yes or no idiot")
This is what I got so far, I'm new and it's hard to understand. Thanks in advance.
As #DavidG mentioned, just add your raw_input statement in loop:
while True:
a = raw_input("Enter: ")
if a == "yes":
print("You have entered Yes")
break
elif a == "no":
print("You have entered No")
break
else:
print("yes or no idiot")
Simply you can put the first instruction inside the loop; in this way, every time the user inserts a value different to yes or no you can print a message and wait to a new input.
while True:
a = raw_input("test: ")
if a == "yes":
print("yeyeye")
break
elif a == "no":
print("nonono")
break
else:
print("yes or no idiot")
Describe a condition checker for while and read input everytime when your condition is not meet. Inline returns are good for low quantity conditions but when your choice count is too much or condition in condition situations appear, inline returns are becoming trouble.
Thats why you must use condition checkers(like cloop) instead of inline returns.
cloop=True
while cloop:
a = raw_input("test: ")
if a == "yes":
print("yeyeye")
cloop=False
elif a == "no":
print("nonono")
cloop=False
else:
print("yes or no idiot")
cloop=True

Python: Problems when calling outside function

I'm a beginner to Python, and am having problems with a function. I am making a program in which I have many parameters for the user to choose from and I need to allow them to confirm or deny their choices. Here is a simplified code section that represents my issue.
my code:
def confirm(function):
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
break
elif answer == 'no':
return function() # if the user wants to change their name, recall function
else:
continue # to reprompt user if the answer is not "yes" or "no"
def your_name():
while True:
name = raw_input("What is your name? ")
if not name:
continue # to reprompt user if they do not enter anything
else:
confirm(your_name)
print 'Congratulations! You have a name!'
break
your_name()
When running this program, it will print the congratulatory string the same amount of times that answer received an input.
my output:
What is your name? Bastion
Are you sure? no
What is your name? Artex
Are you sure? no
What is your name? Falcor
Are you sure? yes
Congratulations! You have a name!
Congratulations! You have a name!
Congratulations! You have a name!
My intention is for the congratulatory message to be printed just one time. How can I edit my function(s) in order to achieve this?
What I've tried:
I have attempted all of these, using the exact same input values I used in my output block above.
Within the section of confirm(function) that says:
if answer == 'no':
return function()
I've tried changing it to:
if answer == 'no':
function()
In the output, this will ask for the answer raw_input 3 times, posting the congratulatory message after each input. If I write the code in this way:
if answer == 'no':
print function()
It will print the congratulatory response 3 times and print None on a separate line below for each time. I am looking for an elegant, clean format so this will not do.
So your problem is you are creating a kind of recursive function without meaning to, you don't need to pass the function to be called again as you are already inside the function. I would suggest the following:
def confirm():
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
return True
if answer == 'no':
return False
else:
continue # to reprompt user if the answer is not "yes" or "no"
def your_name():
while True:
name = raw_input("What is your name? ")
if not name:
continue # to reprompt user if they do not enter anything
elif confirm():
print 'Congratulations! You have a name!'
break
your_name()
I think the cleanest way is to change your_name to:
def your_name(toplevel=False):
while True:
name = raw_input("What is your name? ")
if not name:
continue # to reprompt user if they do not enter anything
else:
confirm(your_name)
if toplevel: print 'Congratulations! You have a name!'
break
and the very first call from the top level to your_name(True).
There are other ways, but they require global variables (ecch:-) or even dirtier tricks to find out if the function has been called from the top level; telling it explicitly is way cleaner...
Because of the style recursion you're doing (kudos on that) you end up invoking the your_name() function once each time they fill an answer.
I'd try something more like this:
def confirm():
answer = ''
while answer == '':
answer = raw_input('Are you sure? ')
if answer == 'yes':
return True
elif answer == 'no':
return False
else:
answer = ''
def your_name():
name = ''
while name == '':
name = raw_input("What is your name? ")
if confirm():
print 'Congratulations! You have a name!'
else:
your_name()
your_name()
I think you don't have to use all those "recursive" calls, try this:
def your_name():
flag = True
while flag:
name = raw_input("What is your name? ")
if name:
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
flag = False
break
elif answer == 'no':
break
print 'Congratulations! You have a name!'
your_name()
Using an inner loop for asking if the user is sure. With the use of a flag to determine whenever or not the main "What is your name? " question cycle is over.
You can just put the print 'Congratulations! You have a name!' inside your confirmation() function instead of your_name() so it will be something like this:
def confirm(function):
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
print 'Congratulations! You have a name!'
break
elif answer == 'no':
return function() # if the user wants to change their name, recall function
else:
continue # to reprompt user if the answer is not "yes" or "no"
def your_name():
while True:
name = raw_input("What is your name? ")
if not name:
continue
else:
confirm(your_name)
break
your_name()
BTW, I also modify your conditional syntax in the first function so that the program won't go through two if statements.
This solution is relatively succinct. It loops requesting your name while 'name' is an empty string. When requesting confirmation, it resets name to an empty string and thus continues the loop unless the user confirms 'yes'. It then prints the user's name to confirm its assignment.
def your_name():
name = ''
while name == '':
name = raw_input("What is your name? ")
answer = raw_input('Are you sure (yes or no)? ') if name != '' else 'no'
name = '' if answer != 'yes' else name
print 'Congratulations {0}! You have a name!'.format(name)

Categories

Resources