Using While True to validate input - python

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.

Related

How do I unit test this function with inputs?

How do I unit test this function with inputs? search_by_choice is a variable that takes in user's input, but how do I unit test this?
def search(books_data):
"""
Searches and print search result as numbered list.
A function that takes in menu_selection (an integer) as user input from menu(), run search_function() and collects
the result from search_function(). Print user the result and return to main menu page, ie. menu().
:precondition: the integer must be in the range [1:8]
:postcondition: print number of results and numbered list of results as dictionaries
:return: menu()
"""
print(SEARCH_OPTIONS())
search_by_choice = int(input("Please enter your choice (in number): ").strip())
if search_by_choice == 1:
print("You chose search by: Author")
return 1
elif search_by_choice == 2:
print("You chose search by: Title")
return 2
elif search_by_choice == 3:
print("You chose search by: Publisher")
return 3
elif search_by_choice == 4:
print("You chose search by: Shelf")
return 4
elif search_by_choice == 5:
print("You chose search by: Category")
return 5
elif search_by_choice == 6:
print("You chose search by: Subject")
return 6
elif search_by_choice == 7:
print("You chose to Return to previous page (Main Menu)")
menu(load_data())
# return 7
elif search_by_choice == 8:
print("You chose to Quit")
quit_books(books_data)
else:
print("Error! Please enter a valid integer")
menu(load_data())
you can use:
def numbers_to_strings(argument):
switcher = {
0: "zero",
1: "You chose search by: Author",
2: "You chose search by: Title",
3:
.
.
}
# get() method of dictionary data type returns
# value of passed argument if it is present
# in dictionary otherwise second argument will
# be assigned as default value of passed argument
return switcher.get(argument, "nothing")
# Driver program
if __name__ == "__main__":
argument=0
print numbers_to_strings(argument)

How can I fix my code to properly display my menu?

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__").

How do I fix my Python function so that it returns with input prompts?

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:
...

Simple elif statement

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 ..

validate Fn usining try-except in python

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 .

Categories

Resources