Harshit
Harshit

Reputation: 13

How to convert user input(string) into argument?

The problem is getting that when I give the user input value to as an argument, it takes as a string and gives an error.

class Employee():
    def details(self,name=[]):
        print(
          "Name of Employee is:",name[0],
          "\nSalary of Employee is:",name[1],
          "\nPost of Employee is:",name[2],
          "\nLocation of Employee is:",name[3]
        )    

harry = ["Harry",10000,"Engineer","Gurgoan"]
manish = ["Manish",20000,"Manager","Noida"]
e = Employee()
f = input("Enter name to get details:")
e.details(f)

if I use e.details(harry) and don't use input function it works fine. but I want to get detail of harry by using the input function.

Upvotes: 0

Views: 132

Answers (3)

AmirTheFree
AmirTheFree

Reputation: 66

Just use eval at the last line to completely fix the problem

I tested & it worked just now

e.details(eval(f)) # eval the string 

eval makes string as variable name

Edit: But use it at your own risk user can run anything with this method

Upvotes: -1

OKEE
OKEE

Reputation: 460

When you create an object from the Employee class and then call from it details function, e object - does not know about your lists that you define before object creation

I am not sure what your code is doing, but I think you meant something like this:

class Employee:
    def __init__(self):
        self.workers_data = {
            "harry": ["Harry", 10000, "Engineer", "Gurgoan"],
            "manish": ["Manish", 20000, "Manager", "Noida"],
        }

    def details(self, name):
        print(
            "Name of Employee is: {}\nSalary of Employee is: {}\nPost of Employee is: {}\nLocation of Employee is: {}".format(
                *self.workers_data[name]
            ),
        )


e = Employee()
f = input("Enter name to get details:")
e.details(f)

Upvotes: 4

Lakerr
Lakerr

Reputation: 97

This is because your string can be less than 4 symbol’s, and when you call name[3] it returns error. Also if you want to get words from input, you can split it by space’s: input().split()

If you need to get info about name, try to use dictionary:

harry = ["Harry",10000,"Engineer","Gurgoan"]
manish = ["Manish",20000,"Manager","Noida"]
Names = {"Harry": harry, "Manish": manish}
e = Employee()
f = input("Enter name to get details:")
e.details(Names[f])

Upvotes: 2

Related Questions