Everything left out of what is shown is correct because I tested it before...
no matter what i put, it still says "That is not a choice" which is my else statement
1 = choice1
2 = choice2
3 = choice3
while True:
choice = raw_input("->")
if choice == 1:
dochoice1
break
elif choice == 2:
dochoice2
break
elif choice == 3:
dochoice3
break
else:
print "That Is Not A Choice"
continue
raw_input returns a string, which you're comparing to integers, either convert choice to int, or compare it to string:
choice = int(raw_input("->"))
or:
if choice == "1":
If the user inputs something that's not a valid int, you can catch the exception:
try:
choice = int(raw_input("->"))
except ValueError:
print "Invalid int"
continue
Related
I am still new to programming and I wanted to do a simple calculator in python. However, I could only reach this point of my code:
import operator as op
print("Greetings user, welcome to the calculator program.\nWe offer a list of functions:")
print("1. Add\n2. Subtract\n3. Multiply\n4. Divide\n5. Modulus\n6. Check greater number")
while True:
userInput = input("Please choose what function you would like to use based on their numbers:")
if userInput.isdigit():
if int(userInput) in range(1,7):
str(userInput)
break
else:
print("Number inputted is either below or above the given choices")
continue
else:
print("Incorrect input. Please try again.")
continue
def add(x,y):
return op.add(x,y)
def sub(x,y):
return op.sub(x,y)
def mul(x,y):
return op.mul(x,y)
def div(x,y):
return op.truediv(x,y)
def mod(x,y):
return op.mod(x,y)
def gt(x,y):
if x == y:
return "Equal"
else:
return op.gt(x,y)
variableA = 0
variableB = 0
while True:
variableA = input("Enter the first value: ")
if variableA.isdigit():
float(variableA)
break
else:
print("Incorrect input. Please try again.")
continue
while True:
variableB = input("Enter the second value: ")
if variableB.isdigit():
float(variableB)
break
else:
print("Incorrect input. Please try again.")
continue
if userInput == 1:
print("You chose to add the two numbers and the result is:")
print(add(variableA,variableB))
print("Thank you")
elif userInput == 2:
print("You chose to subtract with the two numbers and the result is:")
print(sub(variableA,variableB))
print("Thank you")
elif userInput == 3:
print("You chose to multiply the two numbers and the result is:")
print(mul(variableA,variableB))
print("Thank you")
elif userInput == 4:
print("You chose to divide with the two numbers and the result is:")
print(div(variableA,variableB))
print("Thank you")
elif userInput == 5:
print("You chose to find the modulo with the two numbers and the result is:")
print(mod(variableA,variableB))
print("Thank you")
elif userInput == 6:
print("Is the first input greater than the second?")
if sub(variableA,variableB) == True:
print(f"{sub(variableA,variableB)}. {variableA} is greater than {variableB}")
elif sub(variableA,variableB) == False:
print(f"{sub(variableA,variableB)}. {variableB} is greater than {variableA}")
else:
print(f"It is {sub(variableA,variableB)}")
print("Thank you")
Not sure why my if statement is not executing after all the correct inputs from the user. I mostly focused on the error handling part and after everything going well, the if statement is just not executing after that. There could probably be a simple mistake but even I can't understand what's going on here.
You have an issue with type casting. So when you are taking input from the user all the userInput is str not int, so you need to cast it like userInput = int(userInput) before doing further calculator operations.
Also, you need to assign the float casting to a variable like this variableA = float(variableA) and variableB = float(variableB) otherwise your add/sub/divide/multiply etc. will not do expected operations.
For example add will do concatenation i.e '2' + '4' = 24 not 2 + 4 = 6.0
import operator as op
print("Greetings user, welcome to the calculator program.\nWe offer a list of functions:")
print("1. Add\n2. Subtract\n3. Multiply\n4. Divide\n5. Modulus\n6. Check greater number")
while True:
userInput = input("Please choose what function you would like to use based on their numbers:")
if userInput.isdigit():
if int(userInput) in range(1,7):
str(userInput)
break
else:
print("Number inputted is either below or above the given choices")
continue
else:
print("Incorrect input. Please try again.")
continue
def add(x,y):
return op.add(x,y)
def sub(x,y):
return op.sub(x,y)
def mul(x,y):
return op.mul(x,y)
def div(x,y):
return op.truediv(x,y)
def mod(x,y):
return op.mod(x,y)
def gt(x,y):
if x == y:
return "Equal"
else:
return op.gt(x,y)
variableA = 0
variableB = 0
while True:
variableA = input("Enter the first value: ")
if variableA.isdigit():
variableA = float(variableA) # <-- fix this line
break
else:
print("Incorrect input. Please try again.")
continue
while True:
variableB = input("Enter the second value: ")
if variableB.isdigit():
variableB = float(variableB) # <-- fix this line
break
else:
print("Incorrect input. Please try again.")
continue
userInput = int(userInput) # <-- fix this line
if userInput == 1:
print("You chose to add the two numbers and the result is:")
print(add(variableA,variableB))
print("Thank you")
elif userInput == 2:
print("You chose to subtract with the two numbers and the result is:")
print(sub(variableA,variableB))
print("Thank you")
elif userInput == 3:
print("You chose to multiply the two numbers and the result is:")
print(mul(variableA,variableB))
print("Thank you")
elif userInput == 4:
print("You chose to divide with the two numbers and the result is:")
print(div(variableA,variableB))
print("Thank you")
elif userInput == 5:
print("You chose to find the modulo with the two numbers and the result is:")
print(mod(variableA,variableB))
print("Thank you")
elif userInput == 6:
print("Is the first input greater than the second?")
if sub(variableA,variableB) == True:
print(f"{sub(variableA,variableB)}. {variableA} is greater than {variableB}")
elif sub(variableA,variableB) == False:
print(f"{sub(variableA,variableB)}. {variableB} is greater than {variableA}")
else:
print(f"It is {sub(variableA,variableB)}")
print("Thank you")
If the user input is supposed to be an int, convert it early and fail fast.
while True:
userInput = input(...)
try:
userInput = int(userInput)
except ValueError:
print("Not an integer, try again")
continue
if userInput in range(1, 7):
break
print("Number out of range, try again")
and similarly for the operands
while True:
variableA = input("Enter the first value: ")
try:
variableA = float(variableA)
break
except ValueError:
print("not a float")
There's little reason to convert the menu choice to an integer, though. You could simply write
while True:
userInput = input(...)
if userInput in "123456": # ... in ["1", "2", "3", "4", "5", "6"]
break
print("Invalid choice, try again")
I would like to make it so my menu works in a way which if a letter is input or anything other than a correct answer is input my script doesn't just end abruptly and it asks to input a correct option. Could anyone help me do this please? Here is the code i have so far:
#variables for password entry
secret_word = "giraffe"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
#password entry code
while guess != secret_word and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("enter guess: ")
guess_count += 1
else:
out_of_guesses = True
if out_of_guesses:
print("out of guesses!")
else:
print("You are into the secret lair!")
#Menu code
def menu(menu):
print("--------------------------\nMenu\n--------------------------\n1.Secret
Sauce\n2.More secret stuff\n3.Even more secret stuff\n4.Exit")
choice = int(input("--------------------------\nENTER CHOICE: "))
if choice == 1:
print("--------------------------\nSecret Sauce recipe:\n1.ITS A SECRET!")
elif choice == 2:
print("--------------------------\nThis is also secret! Go away!")
elif choice == 3:
print("--------------------------\nYOU DARE TO TRY AGAIN?! STOP, GO AWAY!")
elif choice > 4:
print("This was not an option! TRY AGAIN!")
return (menu)
else:
return(False)
return(choice)
#exit loop for the def
running = True
while running:
menuChoice = menu(menu)
if menuChoice == False:
print("\nGoodbye")
running = False
Instead of
choice = int(input("--------------------------\nENTER CHOICE: "))
You can do the following:
choice = input("--------------------------\nENTER CHOICE: ")
and then after it we need to check if the string is a digit, so you can transfer it to "int" type safely.
if choice.isdigit():
if choice == 1:
print("--------------------------\nSecret Sauce recipe:\n1.ITS A SECRET!")
elif choice == 2:
print("--------------------------\nThis is also secret! Go away!")
elif choice == 3:
print("--------------------------\nYOU DARE TO TRY AGAIN?! STOP, GO AWAY!")
elif choice > 4 or choice != (1,2,3,4):
print("This was not an option! TRY AGAIN!")
return (menu)
else:
return(False)
return(choice)
In your menu() function,
Instead of immediately casting the input into an int, you can use a try statement to make sure the input is an integer, so if the user types in a letter your program will not stop. For example:
validInput = False
while validInput == False:
choice = input("--------------------------\nENTER CHOICE: ")
try:
choice = int(choice)
validInput = True
except:
print("Please enter an integer.")
Replace choice = int(input("--------------------------\nENTER CHOICE: ")) with the above code and it will work.
When I run this code it always goes to the else. Even when I choose 1, 2, or 3. How can I achieve a proper if, elif else statement?
def main():
name = input("What is your name?")
print("Hello", name)
choice = int
choice = 0
choice = input("Please choose a number from the following options: \n 1. Paper \n 2. Rock \n 3. Scissors")
print (choice)
if choice == 1:
print ('You chose number 1')
elif choice == 2:
print ('You chose number 2')
elif choice == 3:
print ('You chose number 3')
else:
print ('Invalid Entry Mush')
return
main()
input returns a string. You will need to cast it to an int so that your elif options that check for ints are triggered:
choice = int(input("Please choose a number from the following options: \n 1. Paper \n 2. Rock \n 3. Scissors"))
By the way the two lines before that one are unnecessary.
Or you can put your if statements between quotes: ex: if choice == "1" print("nr 1") elif choice == "2" so on ..
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
def main_menu():
print ("Three Doors Down Figurative Language Game")
print ("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*")
print ("NOTE: TO SELECT, TYPE NUMBER OF OPTION")
print ("")
print (" 1) Begin Game")
print ("")
print (" 2) Options")
print ("")
print ("")
menu_selection()
def menu_selection():
valid_answer = ["1","2"]
user_choice = str(input("Make a choice.."))
if user_choice in valid_answer:
def check_valid(user_choice):
if user_choice == 1: #Error section V
return("You started the game.")
else:
user_choice != 1
return("Credits to ____, created by ____")
check_valid(user_choice) #Error Section ^
else:
print("Please use an actual entry!")
menu_selection()
def enterText():
print("ENTER ANSWER!")
print (main_menu())
Okay, so the error should be labeled. That specific if/else statment shows up as "None" and I have tried every method to fix it. One method worked for the if/else statement on the outside, but not this one.
You're taking input as a string str(input()). Then, you're checking if user_input == 1; testing to see if it is an integer, even though it is a string. Instead, try converting to an integer using int(input()). Also, the line user_input != 1 is unnecessary, it's just the equivalent of writing True in your code. Furthermore, you define a function in your if statement, which shouldn't be there:
def main_menu():
print ("Three Doors Down Figurative Language Game")
print ("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*")
print ("NOTE: TO SELECT, TYPE NUMBER OF OPTION")
print ("")
print (" 1) Begin Game")
print ("")
print (" 2) Options")
print ("")
print ("")
menu_selection()
def menu_selection():
valid_answer = ["1","2"]
user_choice = int(input("Make a choice.."))
if user_choice in valid_answer:
if user_choice == 1:
return("You started the game.")
else:
return("Credits to ____, created by ____")
check_valid(user_choice)
else:
print("Please use an actual entry!")
menu_selection()
def enterText():
print("ENTER ANSWER!")
print (main_menu())