NameError: name 'x' is not defined(Python 3.7)

Question:

I am new to python ,
I am learning "if and else" condition in python 3.7.

So the issue is , when I type my this code

def age_group(user_age):
    x = int(input("Enter your age :"))
    return x

if x < 150 :
    print(age_group(x))
else :
    print("Either he is GOD or he is dead")

But after executing I get an NameError:-

Traceback (most recent call last):
File ".Enter Age.py", line 6, in <module>
if x < 150 :
NameError: name 'x' is not defined
Asked By: Kiran kudpane

||

Answers:

Yes, x only exists in the scope of age_group. Variables used in functions in Python typically exist only in that scope unless you use the global keyword or do some other trickery. Either way, you should return that value to the caller and assign it to a variable. Working example (I also removed one unused argument):

def age_group():
  return int(input("Enter your age :"))

x = age_group()
if x < 150:
  print(x)
else:
  print('Either he is GOD or he is dead')
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.