My code has no red flags in it. It runs but it doesnt display anything?
def main():
menuInput()
def menu():
print('''
Welcome! Please make a choice from the following menu
1. Select a year and display available data
2. Review averages by year range
3. Select a date range and show highest temperature
4. Select a date range and show lowest temperature
5. Get total rainfall for a selected year range
6. blank
7. blank
8. See this menu again
9. QUIT the program
''')
def menuInput():
while True:
menu()
try:
userChoice=int(input('Please make a selection: '))
if userChoice > 9:
print('Please enter a number less or equal to 9')
elif userChoice <= 0:
print('Please enter a number greater than 0')
elif userChoice == 1:
print('Good')
elif userChoice == 2:
print('Good')
elif userChoice == 3:
print('Good')
elif userChoice == 4:
print('Good')
elif userChoice == 5:
print('Good')
elif userChoice == 6:
print('Good')
elif userChoice == 7:
print('Invalid Choice')
elif userChoice == 8:
print('Good')
elif userChoice == 9:
print('Program Exiting!')
else:
print('Invalid Choice')
continue
except ValueError:
print('Please enter a whole number instead')
continue
main()
I would like to assume it is because menu() either hasnt been called properly or has not been assigned a to a variable like displayMenu=MENU CODE. Im not sure how to properly go about adding or passing that variable without ruining it
If you have copied and pasted the code verbatim, then the issue is that your main() function is indented improperly. Unindent the line main().
When you indent main(), it becomes part of the function menuInput(), and as a result nothing is run in the actual main of Python (if __name__ == "__main__").
Related
I am using a While True loop to validate some input, when the input is not in a specified list , i should get an error, the issue i have in the code below that is when i enter either 0 or 1 as input, the action takes place however, i still get the error for an invalid input..
Please just run the main() function then press 1 or 0 as your input and you will see..
I would like the error message not to be shown , thank you :)
def main():
print('\nDear user, welcome to the Online library of Husam.\nPlease choose from the option menu below: ')
print(""" ======LIBRARY MENU=======
0. To create a book and add it to the book list.
1. To create a user and add it to the user list.
2. To Display the current books in the library.
3. To Display the current users in the library.
4. Search for a book using: title, author, publisher, or publication date.
5. Remove a book using: title.
6. Display total number of books in the library.
7. Remove a user from the system using: firstname.
8. Display the number of the users in the system.
9. Display a user's details using: username.
10. Borrow a book.
11 Return a book.
12. Display number of books a user is borrowing.
13. Display overdue books that need to be returned.
14. Exit the system.
""")
choice=input("How may we serve you today? Please choose a number between 0 and 14: \n")
while True:
if choice not in ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14']:
print('Error: Invalid input! Please type in only a number between 0 and 14: ')
choice = input('\nHow may we serve you today? Please choose a number between 0 and 14: \n')
else:
choice = int(choice)
if choice == 0:
print(0)
elif choice == 1:
print(1)
elif choice == 2:
print('The Library currently has the following books in it: \n')
print(2)
elif choice == 3:
print('The Library currently has the following users in it: \n')
print(3)
elif choice == 4:
print(4)
elif choice == 5:
print(5)
elif choice == 6:
print(6)
elif choice == 7:
print(7)
elif choice == 8:
print(8)
elif choice == 9:
print(9)
elif choice == 10:
print(10)
elif choice == 11:
print(11)
elif choice == 12:
print(12)
elif choice == 13:
print(13)
elif choice == 14:
print(14)
main()
Your while loop will continue to be evaluated until you break out of it. So if you input 1 then:
choice is the string '1'
you convert it to an int so choice becomes 1
the loop repeats and now choice is 1 which is not in your list of strings so the error is thrown.
There are a few things you could do to fix it. You could break out of your loop when you detect a valid input, or you could not convert choice to an int and just compare it as a string.
I've been attempting to code this program for the past half a month or so but I'm stumped and I need to make substantial progress soon to meet my deadline, any help/advice would be appreciated. Apologies for the bad formatting, thanks for any help you can provide.
def main():
choice = printMenu()
print(choice)
def menu():
print("NRAS Eligibility Calculator")
print("[1] Display Household Income Limits")
print("[2] Calculate Total Income")
print("[3] Calculate Eligibility")
print("[4]: Exit")
def choice = int(input("Enter your choice: "))
while choice !=0:
elif choice== 1:
print("$52,324")
elif choice== 2:
def add_num(a,b):
sum=a+b;
return sum;
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
print("Your total income is",add_num(num1,num2))
elif choice== 3:
def add_num(a,b):
sum=a+b;
return sum;
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
if sum <= "52,324"
print("You're eligible for NRAS!")
else
print ("Sadly, you're not eligible.")
elif choice== 4:
quit()
else:
print("Invalid option.")
print("Thank you for using this calculator.")
I have corrected most of the mistakes and the code works fine. I have also added comments to highlight the changes I made.
But there a lot of questionable things that were going on in this code. I suggest you to look into python syntax properly.
def add_num(a,b):
sum = a+b
return sum
def menu():
print("NRAS Eligibility Calculator")
print("[1] Display Household Income Limits")
print("[2] Calculate Total Income")
print("[3] Calculate Eligibility")
print("[4] Exit")
ch = int(input('Enter your choice : ')) # added a variable to read the choice.
return ch # then return this choice when this function is called.
def choice(choice):
while choice != 0:
if choice== 1: # changed the elif to if.
print("$52,324")
break # added a break due to infinite loop
elif choice == 2:
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
print("Your total income is",add_num(num1,num2))
elif choice == 3:
num1=int(input("income from source 1: "))
num2=int(input("income from source 2 :"))
SUM = add_num(num1, num2) # calling the add_num function here.
if SUM <= 52324: # changed this to int type instead of a string.
print("You're eligible for NRAS!")
else:
print ("Sadly, you're not eligible.")
elif choice == 4:
quit()
else:
print("Invalid option.")
print("Thank you for using this calculator.")
def main():
ch = menu()
choice(ch)
if __name__ == "__main__": # this is how you call a main() in python.
main()
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:
...
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 ..
def validate(choice):
try:
if choice == 1 or choice == 2 or choice == 3 or choice == 4 or choice == 5 or choice == 6 or choice == 7 or choice == 8:
if choice==1:
extrasquare()
elif choice==2:
drawastar()
elif choice==3:
drawit()
elif choice==4:
circle()
elif choice==5:
square()
elif choice==6:
turtle.clear()
elif choice==7:
turtle.bye()
elif choice==8:
import sys #exit from program
sys.exit() #might not work in some versions of idlex
loop = 700076
except:
loop=8
print("Error")
while loop == 1:
#print options for user
print("----------------------------")
print("Hello")
print("Here's you options")
print("1- to draw a set of squares(extra picture)")
print("2-to draw 10 stars")
print("3-to draw nine rectangles")
print("4-to draw a random number of random circles")
print("5-to draw a square motion")
print("6-to Erase everything")
print("7-to exit from turtle")
print("8-to exit from python")
print(" ")
choice = int(input("What would you like to do? Please enter a number:"))
validate(choice)
I need to use try-except to validate input data but obviously I do something wrong. I need to stop loop and print error if input was >=9. Could you help me guys? I really do not know what to write else
You will find this sort of problem a lot easier using a dictionary:
def validate(choice):
options = {
1: extrasquare,
2: drawastar,
3: drawit,
4: circle,
5: square,
6: turtle.clear,
7: turtle.bye,
8: exit # Move your exit action to a separate function for simplicity
}
if choice in options:
options[choice]()
else:
print "Error: %i is not a recognized choice" % i
Your existing code won't raise an exception since you only try a lot of ifs and dont hit an exception condition.
You could do the same with a try by changing the last lines two:
try:
options[choice]()
except KeyError:
print "Error : %i is not a recognized choice" % choice
However it doesn't really enhance the code .