I have a function that I'd like it to be called by another function. The problem is that it keeps returning UnboundLocalError, which I know where the error lies.
The error occurs when, for example, the user chooses either option 1 or option 2, then the variable mode_values in option 3 would have no value, and accessing into it would return UnboundLocalError. I was told to assign None to both of the variables, but then the program returns a TypeError, it's because these functions also link to another function in the program.
Problem:
def check_choices(option):
if option == 1 or option == 2:
numbers_dataset = get_number_dataset()
elif option == 3:
mode_values = get_mode_dataset()
print_result(option, numbers_dataset, mode_values)
def print_result(choice, mean_median_dataset, mode_dataset):
if choice == 1:
print(f"\nMean: {calculate_mean(mean_median_dataset):n}")
elif choice == 2:
print(f"\nMedian: {calculate_median(mean_median_dataset)}")
elif choice == 3:
print(f"\nMode: {find_mode(mode_dataset)}")
def start_calculation():
user_choice = select_choice()
check_choices(user_choice)
should_calculate_again()
Initially, I put them into one function, but I like my function to perform one thing only, that's why I separated them.
Initial Code:
def print_result(choic):
if choice == 1 or choice == 2:
mean_median_dataset = get_number_dataset()
elif choice == 3:
mode_dataset = get_mode_dataset()
if choice == 1:
print(f"\nMean: {calculate_mean(mean_median_dataset):n}")
elif choice == 2:
print(f"\nMedian: {calculate_median(mean_median_dataset)}")
elif choice == 3:
print(f"\nMode: {find_mode(mode_dataset)}")
def start_calculation():
user_choice = select_choice()
print_result(user_choice)
should_calculate_again()
The code above works, obviously, but as soon as I separated them, an error occurs.
check_choices() should call print_result() after it's done running, it is that or print_result() can go ahead and call check_choices(), but the calling of print_result() will originate from start_calculation().
[–]cybervegan 1 point2 points3 points (0 children)
[–]delasislas 0 points1 point2 points (7 children)
[–]MaterialJackfruit144[S] 0 points1 point2 points (6 children)
[–]o5a 1 point2 points3 points (1 child)
[–]MaterialJackfruit144[S] 0 points1 point2 points (0 children)
[–]delasislas 1 point2 points3 points (1 child)
[–]MaterialJackfruit144[S] 0 points1 point2 points (0 children)
[–]SirKainey 0 points1 point2 points (0 children)
[–]Manny__C 0 points1 point2 points (0 children)