[SOLVED] Why do I get an error when passing input value into function parameter but not when statically assigning it?

Issue

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’

Solution

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])

Answered By – chepner

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *