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)
Related
I successfully defined a parameter and passed it to a function but when I return to main menu that parameter's value is completely reset and I cannot use it anywhere. The value of the parameter stays only within the second function. Like, the parameter cannot communicate with the whole program as far as I understand.
def main_menu(subtotal):
while True:
print("1) Appetizers")
print("2) Option 2")
print("3) Option 3")
print("4) Option 4")
print("5) Option 5")
print(" ")
print("Current overall subtotal: $" + str(round(subtotal,2)))
while True:
try:
choice = int(input("What is your choice? "))
break
except ValueError:
print("Please enter whole numbers only.")
while choice > 5 or choice < 1:
print("Please choose an option from 1 to 5")
try:
choice = int(input("what is your choice? "))
except ValueError:
print("Please enter whole numbers only.")
if choice == 1:
appetizers(subtotal)
"""
elif choice == 2:
option_2(subtotal)
elif choice == 3:
option_3(subtotal)
elif choice == 4:
option_4(subtotal)
elif choice == 5:
end(subtotal)
return subtotal
"""
def appetizers(subtotal):
while True:
print("1) Option 1")
print("2) Option 2")
print("3) Option 3")
print("4) Return to Main Menu")
print(" ")
print("Current overall subtotal: $" + str(round(subtotal,2)))
product_amount = 1
while True:
try:
choice = int(input("What is your choice? "))
break
except ValueError:
print("Please enter whole numbers only.")
while choice > 4 or choice < 1:
print("Please choose an option from 1 to 4")
try:
choice = int(input("what is your choice? "))
except ValueError:
print("Please enter whole numbers only.")
if choice == 4:
return subtotal
else:
while True:
try:
product_amount = int(input("How many would you like? "))
break
except ValueError:
print("Please enter whole numbers only.")
while product_amount > 100000 or product_amount < 1:
print("Please choose an option from 1 to 100,000")
product_amount = int(input("How many would you like? "))
if choice == 1:
subtotal = subtotal + (product_amount * 4.99)
elif choice == 2:
subtotal = subtotal + (product_amount * 2.99)
elif choice == 3:
subtotal = subtotal + (product_amount * 8.99)
For this project's sake, I don't want to use global variables. I only want to use the subtotal variable as a parameter throughout the program and continuously alter its value throughout the program and make calculations with it. I want to do this by passing it through other functions.
Since you've written the operations into functions and you're passing in the current subtotal, you just need to be updating the subtotal by saving the return value from appetizers() in main_menu(), like here:
# ...
if choice == 1:
subtotal = appetizers(subtotal)
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 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'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()
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__").