Click here to Skip to main content
14,921,311 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I assigned a variable (month1) inside of "try" and I want to access it inside of "except" clause. But I get "variable can't be defined".

The variable (month1) gets stored because I can use it after "except" clause (just print it out not within a special constuction). But when I try to use it in "except" (like in my code), it says me "variable can't be defined". Why ? And is there a way to do it ?

What I have tried:

Here is my code:

<pre lang="Python">try:
    month1 = int(input("Enter your month's of birth number: "))
    day1 = int(input("Enter your day of birth: "))
    year1 = int(input("Enter your year of birth: "))
    print("You were born in " + months_by_number[month1] + " " + str(day1) + " " + str(year1))
except ValueError:
    print("You had to enter a NUMBER !")
except KeyError :
    print("There are 12 month, not " + str(month1)) # here I get "variable can't be difined"
Posted
Updated 20-Feb-20 11:15am
v2

1 solution

Variables have a lifetime (scope) of the block they are declared in.
This will throw an exception because x is not defined.

Python
try:
  print(x)
except:
  print("An exception occurred")


This one will work
Python
try:
  x = 5
  print(x)
except:
  print("An exception occurred")



What you need to do is declare your variable outside of the try scope.
Before the try scope so it the variable still exists in your except block.

Python
x = 5
try:
  print(x)
  raise Exception("fail!")
except NameError:
  print("Variable x is not defined")
except:
  print(x)
  print("Something else went wrong")


This will raise the exception but x will still have scope (lifetime) and will print out in the 2nd exception case.
   
Comments
Rodion Mikhailov 21-Feb-20 2:01am
   
Thank you very much, this helped.
I needed to not just assign a variable, but make s´that was integer. So here's what I've done. Is it good ? It works.

month1 = input("Enter your month's of birth number: ")
try:
month1 = int(month1)
day1 = int(input("Enter your day of birth: "))
year1 = int(input("Enter your year of birth: "))
print("You were born in " + months_by_number[month1] + " " + str(day1) + " " + str(year1))
except ValueError:
print("You had to enter a NUMBER !")
except KeyError:
print("There are 12 month, not " + str(month1))
raddevus 21-Feb-20 9:33am
   
Yes, looks good. Now the month1 variable has scope that is larger than just the try block.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900