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 ..
Related
I am looking for a way to include an input at the end of this code where the user will be prompted with a choice to restart the code or end the code without having to manually restart it.
def correct_result(choice,num):
if choice.lower() == 'square': #Prints the Square of a number Ex. 2^2 = 4
return num**2
elif choice.lower() == 'sqrt': #Prints the Square root of a number Ex. √4 = 2
return num**.5
elif choice.lower() == 'reverse': #Changes the sign of the number
return(-num)
else:
return 'Invalid Choice' #prints an error message
choice = input() #Creates a answer box to enter the desired choice
num = int(input()) #Creates a second box that lets the user enter their number
print(correct_result(choice,num)) #Prints either the desired choice or the error function
Wrap your choice and num input in a while loop, break when the user chooses "exit":
def correct_result(choice,num):
if choice.lower() == 'square': #Prints the Square of a number Ex. 2^2 = 4
return num**2
elif choice.lower() == 'sqrt': #Prints the Square root of a number Ex. √4 = 2
return num**.5
elif choice.lower() == 'reverse': #Changes the sign of the number
return(-num)
else:
return 'Invalid Choice' #prints an error message
while True:
choice = input("Choice: ") #Creates a answer box to enter the desired choice
if choice == "exit":
exit()
num = int(input("Number: ")) #Creates a second box that lets the user enter their number
print(correct_result(choice,num)) #Prints either the desired choice or the error function
I'm trying to "convert" an old arithmetic tester I wrote, for my children in "Commodore" BASIC about 100 years ago and which worked fine.
I'm having great problems trying to get the "arithmetic selection" stage working, as it fails on the if/elif when choice is input, simply defaults to else.
I can get it working if I convert the class of input to int() and the selection menu to numeric but I can't get it working simply using the str() class & alphabetic menu.
It is probably a lot easier for a guru to see the two lots of code and see the glaringly obvious error I made, so I'll try to do that.
int() version:
a = int()
s = int()
m = int()
d = int()
print( ''' This is an input tester script.
To start the program, please select one of the functions below, by typing the number of that function at the prompt.''')
choice = int(input(''' Please type in your choice of arithmetic. \n\n 1 for addition \n 2 for subtraction \n 3 for multiplication \n 4 for division \n\n '''))
if choice == 1 : print(' 111')
elif choice == 2 : print(' 222')
elif choice == 3 : print(' 333')
elif choice == 4 : print(' 444')
else : print(' Wrong keys')
str() version:
a = str()
s = str()
m = str()
d = str()
choice = str()
choice = input('''Please select your sums, using:\n\n a for addition \n s for subtraction \n m for multiplication \n d for division \n \n ''')
if choice == a : print ('well done')
elif choice == s : print('that\'s 2')#execfile (subtract)
elif choice == m : print('that\'s 3')#execfile (subtract)
elif choice == d : print('that\'s 4')#execfile (divide)
else: print('Invalid selection')
According to this logic, you need to do the following:
a = 'a'
s = 's'
m = 'm'
d = 'd'
choice = input('''Please select your sums, using:\n\n a for addition \n s for subtraction \n m for multiplication \n d for division \n \n ''')
if choice == a:
print('well done')
elif choice == s:
print('that\'s 2')
elif choice == m:
print('that\'s 3')
elif choice == d:
print('that\'s 4')
else:
print('Invalid selection')
But you don't need to create variables, just replace vars to strings, like:
if choice == 'a':
Your second code is not working because you have not quoted a,s,m,d in condition making because of that it is acting like a variable.see here↓
if choice == a : print ('well done')
Here a is acting like a variable and you have put the value of variable a as empty string sting so it doesn't match with the input value and thus return 'Invalid selection' as output.
It should be ↓
if choice == 'a' : print ('well done')
See here how you should write that code.
# a = str() #There is no use to define these as a empty string
# s = str()
# m = str()
# d = str()
# choice = str()
choice = input('''Please select your sums, using:\n\n a for addition \n s for subtraction \n m for multiplication \n d for division \n \n ''')
if choice == 'a' : print ('well done')
elif choice == 's' : print('that\'s 2')#execfile (subtract)
elif choice == 'm' : print('that\'s 3')#execfile (subtract)
elif choice == 'd' : print('that\'s 4')#execfile (divide)
else: print('Invalid selection')
OR if you want to keep a,s,m,d as a variable than↓
a = 'a'
s = 's'
m = 'm'
d = 'd'
#choice = str()
choice = input('''Please select your sums, using:\n\n a for addition \n s for subtraction \n m for multiplication \n d for division \n \n ''')
if choice == a : print ('well done')
elif choice == s : print('that\'s 2')#execfile (subtract)
elif choice == m : print('that\'s 3')#execfile (subtract)
elif choice == d : print('that\'s 4')#execfile (divide)
else: print('Invalid selection')
I have a menu function and choice function that both worked. There are 3 menu choices. 1 and 3 worked properly at one point. 2 never has. I don't know what I did to mess it up, but when I run the module to test through IDLE, it doesn't ever work past the first prompting to enter my menu choice number. It should complete an if statement, then restart.
I don't know what else to try. I wish I knew what I changed to mess it up.
tribbles = 1
modulus = 2
closer= 3
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
menu()
def choice():
choice = int(input('\n Enter the number of your menu choice: ')
if choice == tribbles:
bars = int(input('\n How many bars of gold-pressed latinum do you have? '))
print('\n You can buy ',bars * 5000 / 1000,' Tribbles.')
menu()
choice()
elif choice == modulus:
num = int(input('\n Enter any number:'))
o_e = num % 2
if num == 0:
print(num,' is an even number')
elif num == 1:
print(num,' is an odd number')
menu()
choice()
elif choice == closer:
print('\n Thanks for playing!')
exit()
else:
print('Invalid entry. Please try again...')
menu()
choice()
print(' ')
choice = int(input('\n Enter the number of your menu choice: '))
I expect it to return with the string plus all formula results, then asking again, unless option 3 was selected and exit() is performed. However it returns with "Enter the number of your menu choice: " after the first input, then it returns blank after choosing any other choice on the second prompt.f
First things first!
It's good practice to define all functions at the top of the file, and call those functions at the bottom! Second your indenting is incorrect, i'm going to assume that happened after you pasted it here. Finally, you never actually call the function choice() you instead overwrite it with the result of a prompt.
Below i'm going to correct these issues.
tribbles = 1
modulus = 2
closer= 3
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
choice() #added call to choice here because you always call choice after menu
def choice():
my_choice = int(raw_input('\nEnter the number of your menu choice: ')) #you were missing a ) here! and you were overwriting the function choice again
#changed choice var to my_choice everywhere
if my_choice == tribbles:
bars = int(raw_input('\nHow many bars of gold-pressed latinum do you have? '))
print('\n You can buy ',bars * 5000 / 1000,' Tribbles.')
menu()
elif my_choice == modulus:
num = int(raw_input('\n Enter any number:'))
o_e = num % 2
if num == 0:
print(num,' is an even number')
elif num == 1:
print(num,' is an odd number')
menu()
elif choice == closer:
print('\n Thanks for playing!')
exit()
else:
print('Invalid entry. Please try again...')
menu()
print(' ')
if __name__ == "__main__": #standard way to begin. This makes sure this is being called from this file and not when being imported. And it looks pretty!
menu()
Before you check the value of choice, the variable choice is not declared. You have to catch your input before the line: if choice == tribbles:. Your are only defining a function which even don't return the value of your choice or set a global variable.
Try this:
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
menu()
choice = int(input('\n Enter the number of your menu choice: '))
if choice == tribbles:
...
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
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())