Home > front end >  Im wondering why my parameters aren't defined
Im wondering why my parameters aren't defined

Time:01-13

I am sort of newer to python and I can't understand why my parameters aren't defined. I'm not understanding why parameters aren't global when I call the global function to the parameters, it says its already global. Here's the code

def Forum(Age, Sex, BirthYear):
    Age,Sex,BirthYear = input('Enter the following:').split()
    print('What is your Age?',Age)
    print('What is your Sex?',Sex)
    print('What is your Birth year',BirthYear)

Forum(Age,Sex,BirthYear)

print('You are '  Age  ' Years old. You are '  Sex  ', and you were born in '  BirthYear)

CodePudding user response:

Wrong order. You seem to want this (with one input).

def Forum(Age, Sex, BirthYear):
    print('What is your Age?',Age)
    print('What is your Sex?',Sex)
    print('What is your Birth year',BirthYear)

Age,Sex,BirthYear = input('Enter the following:').split()
Forum(Age,Sex,BirthYear)

Or (with 3 separate inputs)

def Forum(Age, Sex, BirthYear):
    print('You are '  Age  ' Years old. You are '  Sex  ', and you were born in '  BirthYear)

print('Enter the following:')

Age = input('What is your Age? ')
Sex = input('What is your Sex? ')
BirthYear = input('What is your Birth year? ')
Forum(Age,Sex,BirthYear)

This defines the variables for the function call itself; you are instead overriding your parameters within the function body, and making function-local variables, rather than global ones. You cannot define global vars within a function before they get used (by calling the function). Ex.

def SetAge(_age):
  print(_age)  # 2
  global age
  print(age)  # 0
  age = _age

age = 0
SetAge(int(input('What is your age? ')))  # inputs 2
print(age)  # prints 2

CodePudding user response:

I can't understand why my parameters aren't defined.

This is because you did not define Age,Sex,BirthYear when you pass them into your function. Yes, you defined your function Forum, but on the next line you called it with 3 unknown parametres as your input.

While this is the reason for the undefined problem you are getting, as John Coleman mentioned in his comment, you should not be passing the parametres if you are getting them from elsewhere like input(). If you look closely, even if Age,Sex,BirthYear have their values, their values will be overwritten inside your function.

  • Related