Home > database >  Why do I get an error when passing input value into function parameter but not when statically assig
Why do I get an error when passing input value into function parameter but not when statically assig

Time:03-16

When I manually type "alex" into the "printPeople" parameter, the code prints out fine.

class people:  
    name = ''
    age = ''

alex = people()
alex.name = 'Alex'
alex.age = '25'

clarance = people()
clarance.name = 'Clarance'
clarance.age = '24'

def printPeople(person):
    print('-' * 20)
    print('Name:', person.name)
    print('Age:', person.age)
    print('-' * 20)

printPeople(alex)

However, if I try using an input function to manually choose a name:

class people:  
name = ''
age = ''

alex = people()
alex.name = 'Alex'
alex.age = '25'

clarance = people()
clarance.name = 'Clarance'
clarance.age = '24'

def printPeople(person):
    print('-' * 20)
    print('Name:', person.name)
    print('Age:', person.age)
    print('-' * 20)

userInput = input('Enter name: ')
printPeople(userInput)

I get an error:

AttributeError: 'str' object has no attribute 'name'

CodePudding user response:

alex is a variable

printPeople(alex)

not a str value like input returns

# Wrong
printPeople("alex")

If you want the input to select data in your program, use a dict which you can index with the user input.

people_data = {"alex": alex}

...

printPeople(people_data[userInput])

CodePudding user response:

Your printPeople function is expecting a people value, or at least some value with name and age attributes. When you call printPeople(input()) you're passing a string into printPeople. That string does not have the required attributes.

CodePudding user response:

You are passing a String Object and it has not an atrribute name. You must know that in python everything is object.

In this two lines you are trying to access attributes name and age of the instance, hence you have an error. print('Name:', person.name) print('Age:', person.age)

  • Related