I want to write a program that is about tools and has three choices--calculator, random number selector, and calendar. However, when I am trying to use try-except for invalid user input, the variable in the if statement is said as undefined. The codes are the following:
if user_input == 0:
try:
small_option = int(
input("Which operation do you want to do? \n 1. Adding \n 2. Subtracting \n 3. Multiplying "
"\n 4. Dividing"))
small_list = [0, 1, 2, 3]
user_option = small_list[small_option]
except IndexError:
print("Invalid option")
Then the next variable in the if statement is undefined, the following lines:
if user_option == 0:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
When I ran it, the program says Traceback (most recent call last): File "C:/Users/31459/PycharmProjects/Useful programs/Tools.py", line 41, in <module> if user_option == 0: NameError: name 'user_option' is not defined
import calendar
import random
def adding(para1, para2):
return para1 + para2
def substract(para1, para2):
return para1 - para2
def multiplying(para1, para2):
return para1 * para2
def dividing(para1, para2):
return para1 / para2
while True:
try:
big_option = input("Which tool will you use? \n 0. Calculator \n 1. Calender \n 2. Random number generator")
big_list = [0, 1, 2]
big_option_int = int(big_option)
user_input = big_list[big_option_int]
if user_input == 0:
try:
small_option = int(
input("Which operation do you want to do? \n 1. Adding \n 2. Subtracting \n 3. Multiplying "
"\n 4. Dividing"))
small_list = [0, 1, 2, 3]
user_option = small_list[small_option]
except IndexError:
print("Invalid option")
if user_option == 0:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if user_option == 1:
print("The sum is", num1, "+", num2, adding(num1, num2))
elif user_option == 2:
print("The subtraction is", num1, "-", num2, substract(num1, num2))
elif user_option == 3:
print("The multiplying is", num1, "*", num2, multiplying(num1, num2))
else:
print("The divide is", num1, "/", num2, dividing(num1, num2))
break
if user_option == 1:
user_year_str = input("Please input the year you want to get.")
user_month_str = input("Please input the month you want to get.")
user_year = int(user_year_str)
user_month = int(user_month_str)
calendar.month(user_year, user_month)
else:
random_input_1 = input("Please input the 1st number:")
random_input_2 = input("Please input the 2nd number:")
random_input_1_int = int(random_input_1)
random_input_2_int = int(random_input_2)
random.randint(random_input_1_int, random_input_2_int)
except IndexError:
print("Invalid option")
the user_option needs to be defined
are you sure you defined the variable before using the conditional statement?
it needs to have a value before using the conditional statement
It's probably because the try block raises an error and it fails to initialize variable user_option
. Hence, it raises an error.
Try adding this as an alternative
user_option = small_option -1
Every object(here: variable) in python has a scope, and in that scope is recognizable. out of its scope it's unrecognizable.
The scope of user_option variable is the try block that in it user_option is defined. if you want to use user_option out of try block you should defined it in bigger scope (means out of try block that it's defined).
You're making option 4 invalid by accessing the list by direct index.
Indices start at 0, so consequently option 4 does not exist, that is an Index Error. 1-3 does not raise an error as the user_option is defined without exception. But your "0" option in small_list
will never be used.
Simply initializing the variable user_option
before the try/catch will fix the UnboundLocalError
. But not the flaw in your logic. You could subract the given option value by one to turn it into a 0-starting index as you have defined the small_list
variable
small_list[small_option-1]
will retrieve 0 when you write 1 and 3 when you write 4, all of which are defined indices of small_list
.
user_option = None # by defining the variable first, we avoid the UnboundLocalError
try:
small_option = int(
input("Which operation do you want to do? \n 1. Adding \n 2. Subtracting \n 3. Multiplying "
"\n 4. Dividing"))
small_list = [0, 1, 2, 3]
user_option = small_list[small_option-1] # 1. Adding = small_list[0], 2. Subtracting = small_list[1], etc..
except IndexError:
print("Invalid option")
if user_option == 0:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.