Variable defined but python wont recognize it. - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Variable defined but python wont recognize it. (/thread-16242.html) |
Variable defined but python wont recognize it. - FWendeburg - Feb-19-2019 Hi, i'm making a program that is supposed to randomly generate numbers between the parameters given. I just copied a bit of the code to show the problem: while True: command = input("\nEnter command: ") # Depending of the command that has been entered do the # thing related to the command. if command.lower() == 'help': show_help() if command.lower() == 'integer': while True: type_of_nums = input(type_of_nums_prompt) if type_of_nums == 'back': break if type_of_nums.lower() == 'e': repeated_q = input("Can the numbers be repeated? (y/n) ") if repeated_q.lower() == 'y': try: nums_to_gen = input(nums_to_gen_prompt) nums_to_gen = int(nums_to_gen) min_num = input(min_num_prompt) min_num = int(min_num) max_num = input(max_num_prompt) max_num = int(max_num) if max_num == 0: print("Thats not a valid number!\n") break except ValueError: if nums_to_gen == 'back' or min_num == 'back' or max_num == 'back': break else: print("That is not a number!\n") continue else: e_repeated(nums_to_gen, min_num, max_num) breakAnd this is the error: As you can see in the first code the min_num variable is defined but it wont work when i use it in the if test.Also if you want to check the whole code you can go to: https://github.com/fwendeburg/random-number-generator/tree/development Thanks in advance! RE: Variable defined but python wont recognize it. - buran - Feb-19-2019 because of the try/except clause, if you enter invalid literal that cannot be converted to int it will raise ValueError and will jump to except block. There you try to use nums_to_gen, min_num, max_num. Depending on which line (18, 20 or 22) is the invalid input some or all of these will not be defined. Thus the second error. In your case you enter qfef for num_to_gen, so min_num and max_num are not defined when you execute the except block (i.e. you have never executed lines 19-22)
RE: Variable defined but python wont recognize it. - metulburr - Feb-19-2019 Quote:Traceback (most recent call last): File "main.py", line 39, in <module> nums_to_gen = int(nums_to_gen) ValueError: invalid literal for int() with base 10: 'qfef' If the try block fails before the definition of min_num then of course its not going to be defined. You need to restructure your program or use isdigit. RE: Variable defined but python wont recognize it. - woooee - Feb-19-2019 crosspost at https://www.reddit.com/r/learnpython/comments/asfpei/help_with_variable_defined_but_python_wont/ |