How to convert user input(string) into argument? - python

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.

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)

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

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

Related

Python Function Errors

I know this is not hard, but I keep getting either an undefined error or different errors, I tried everything I could think of to get the solution. I placed the input variables outside of the code and it worked partially. I'm only 3 weeks or so into my first computer science class. help is appreciated, please & thanks.
# function that prompts the user for a name and returns it
def user():
name = input("Please enter your name: ")
return name
# function that receives the user's name as a parameter, and prompts the user for an age and returns it
def userAge(name):
age = input("How old are you, {}? ".format(name))
return age
# function that receives the user's name and age as parameters and displays the final output
def finalOutput(name, age):
age2x = int(age) * 2
print("Hi, {}. You are {} years old. Twice your age is {}.").format(name, age, str(age2x))
###############################################
# MAIN PART OF THE PROGRAM
# implement the main part of your program below
# comments have been added to assist you
###############################################
# get the user's name
user()
# get the user's age
userAge("name")
# display the final output
finalOutput("name", "age")
You're not storing the values the user supplies, or passing them back to your function calls, here:
user()
userAge("name")
finalOutput("name", "age")
Change the above lines to:
name = user()
age = userAge(name)
finalOutput(name,age)
Correction 1:
Don't pass arguments with double quotes, that means you are passing a string literal to the function not actual value of variable.
for example, if you assign variable name as "Jhon" and you pass it to the function as userAge("name") means you are passing string literal "name" to userAge() not variable value "Jhon".
def printName(name):
print(name)
name = "jhon"
printName("name")
output: name
def printName(name):
print(name)
name = "jhon"
printName(name)
output: jhon
Better assign the return value to some Valerie and pass without double quotes as mentioned by #TBurgis.
Correction 2:
Syntax mistake in print statement. Correct syntax should be
print("Hi, {}. You are {} years old. Twice your age is {}.".format(name, age, str(age2x)))

Python Class/Objects __str__ & other problems [duplicate]

This question already has answers here:
__str__ returned non-string (type tuple)
(3 answers)
Closed 4 years ago.
I'm still very new to Python, and am struggling with what should be a simple assignment. I have to write code for an 'Employee' class, save the module, import the module into another .py file and then store and display 3 objects of that class. I keep getting a
"TypeError: __str__ returned non-string (type tuple)"
no matter how I rework the code, and it's driving me nuts. Anything I've done wrong, please, explain to me how/why it's wrong, learning this is incredibly important to me!
The following is the code for the Employee class:
class Employee:
def __init__(self,name,id,dept,title):
self.__name = name
self.__id = id
self.__dept = dept
self.__title = title
def set_name(self,name):
self.__name = name
def set_id(self,id):
self.__id = id
def set_dept(self,dept):
self.__dept = dept
def set_title(self,title):
self.__title = title
def get_name(self):
return self.__name
def get_id(self):
return self.__id
def get_dept(self):
return self.__dept
def get_title(self):
return self.__title
def __str__(self):
return 'Name: ',self.__name,'\n','ID Number: ',str(self.__id),'\n','Department: ',self.__dept,'\n','Job Title: ',self.__title
I'm not sure I need the set and/or get name methods, because the three objects I have to store and display are pre-determined (no user input or anything). The preceding code is saved in a file named emp.py. The following code is where I think the problem is, but being a novice I don't know for sure.
import emp
def main():
name = 'Susan Meyers'
id = '47899'
dept = 'Accounting'
title = 'Vice President'
employee1 = emp.Employee(name,id,dept,title)
name = 'Mark Jones'
id = '39119'
dept = 'IT'
title = 'Programmer'
employee2 = emp.Employee(name,id,dept,title)
name = 'Joy Rogers'
id = '81774'
dept = 'Manufacturing'
title = 'Engineer'
employee3 = emp.Employee(name,id,dept,title)
print('Employee 1:')
print(employee1)
print('Employee 2:')
print(employee2)
print('Employee 3: ')
print(employee3)
main()
I've tried this by creating an object (i.e. susan = emp.Employee['Susan',id number,'dept','title'] with the appropriate information where id, dept, title are, but still get the tuple error. What am I doing wrong? I considered storing the information in a list or dictionary, but figured I should stick to the bare-bones basics. I feel so stupid, I've been at this all day! For any and all help, thanks in advance.
EDIT: Fixed the indention errors (weren't present in my code in pycharm, but copying and pasting them here w/o proper proofreading...)
FURTHER EDIT:
When run, I need it to say:
Employee 1:
Name: Susan Meyers
ID Number: 47899
Department: Accounting
Title: Vice President
Employee 2:
Name: Mark Jones
ID Number: 39119
Department: IT
Title: Programmer
Employee 3:
Name: Joy Rogers
ID Number: 81774
Department: Manufacturing
Title: Engineer
**And that's the end of the program, like I said, should be really basic stuff, if this were a list or something, I could knock it out np... But each employee has to be stored as an object of the Employee class. We just covered an incredibly long chapter on Classes and Objects (while I was sick with the flu) so my recall/methods may not be the best.
The error's with the __str__ method itself
def __str__(self):
return 'Name: ',self.__name,'\n','ID Number: ',str(self.__id),'\n','Department: ',self.__dept,'\n','Job Title: ',self.__title
"TypeError: __str__ returned non-string (type tuple)"
This error notifies you that
'Name: ',self.__name,'\n','ID Number: ',str(self.__id),'\n','Department: ',self.__dept,'\n','Job Title: ',self.__title
is a tuple. (This is implicitly constructed from the comma-delimited notation.) However, Python is expecting a str as the return type. Change your return statement so that it returns a string. You can use
return ''.join(['Name: ',self.__name,'\n','ID Number: ',str(self.__id),'\n','Department: ',self.__dept,'\n','Job Title: ',self.__title])
or
return 'Name: {}\nID Number: {}\nDepartment: {}\nJob Title: {}'.format(self.__name, self.__id, self.__dept, self.__title)
or anything as long as it returns a string.
Edit: Clarification on Provided Solutions
The first solution uses the .join() method, which follows this format
<str_to_connect>.join(<iterable_of_str>)
The square brackets used ['Name: ',self.__name, ... self.__title] will pack all your various string arguments into a list. Passing this list into .join() connects it all together into a single str.
The second solution uses the .format() method which follows this format
<str_to_format>.format(<args>...)
You can pass complex formatting into the .format() function, but they generally make use of a {} placeholder, which are then filled with input from the arguments passed.
The essential thing is that both these will return str types.
Further reading: str.join(), PyFormat.
Note: C. Kim's solution in the comments, using %, is also equally valid.

Python3 TypeError: takes 1 positional argument but 2 were given

I'm new to programming, here is my code..
But I get error, attached... Please help me..
students = []
def add_student(name, student_id):
student = {"name": name, "student_id": student_id}
students.append(student)
name = input("Enter student name: ")
student_id = input("Enter student ID: ")
def save_file(student):
try:
f = open("students.txt", "a")
f.write(student + "\n")
f.close()
except Exception:
print("Could not save file")
add_student(name, student_id)
save_file(name, student_id)
Your save_file method takes a variable called student but you pass in name and student_id. So, your method expects one argument but got two. Ergo your error.
You can modify the method to take both the name and ID by adding another argument, similar to what you did with add_student. I would also advise that you look at the stack trace and try to understand what's going on before you ask questions. You'll learn more that way and you may come to understand your problem without seeking help.
The function save_file() is allowed to get only one argument student, but you are passing two arguments name, student_id to the function. That's the error!
Change def save_file(student) as def save_file(student, student_id): to fix the error.
Hope this helps! Cheers!

Python Object Oriented Programming

I have to write a program to demonstrate a customer using their credit card to check out, I have spent a few hours trying to figure out how to do it and have provided my code below.
I have to make a class, then use it in a main function.
This is what I have so far:
class Customer:
def __init__(self, customer_name, credit_card_num, credit_security_code, debit_card_num, debit_pin):
self.customer_name = name
self.credit_card_num = credit_num
self.credit_security_code = credit_code
self.debit_card_num = debit_num
self.debit_pin = debit_pin
def inputCardInfo(self):
self.customer_name = str(input("Enter your name: "))
self.credit_card_num = str(input("Enter credit card Number: "))
self.credit_security_code = str(input("Enter 3-digit security code: "))
self.debit_card_num = str(input("Enter debit card number: "))
self.debit_pin = str(input("Enter 4-digit PIN: "))
then the main function:
from customer import Customer
def main():
print("Welcome to Wake-Mart. Please register.")
customer_name = input("enter name: ")
customer1 = Customer(customer_name)
print("Registration completed")
main()
I don't know the correct way to call the class methods. I feel if I can figure out how to make one of these work I can figure out the rest.
If you want to understand behaviors and properties more deeply I would recommend making a separate behavior for each value. (get_credit_num, get_debit_num, etc.)
Then, in your main, just call each function individually to get each value.
And to clarify, "class functions", or behaviors, are just things an object can do. You call them the same way you would any function, with the only difference being you put the name of the instance you are calling this behavior for before the function to replace "self". So if you were calling "InputCardInfo" for the object customer1, you would do it like so:
customer1.InputCardInfo(other parameters)
Your code as-is will not work because you are not passing all required parameters when initializing your class.
customer1 = Customer(customer_name)
All of the additional parameters besides self included in your def __init__(self, var1, var2, var3): needs to be passed to the class instance when initializing. There are also variable naming issues with your code but I hope my example below clarifies things for you.
A quick note first to help you better understand: self.customer_name = name does not make sense in your code because there is no parameter named name included in the __init__() method. You must associate an instance variable (self.whatever) to a known variable name passed in through the __init__(self, external_var) method so that self.whatever = external_var. Then, and only then, can you use class methods to call self.whatever and expect to receive the data you passed from external_var. Also, additional parameters you include after self in __init__(self, ..., ...) MUST be passed as variables when creating a class instance.
class Customer:
def __init__(self, customer_name, credit_card_num, credit_security_code, debit_card_num, debit_pin):
self.customer_name = customer_name
self.credit_card_num = credit_card_num
self.credit_security_code = credit_security_code
self.debit_card_num = debit_card_num
self.debit_pin = debit_pin
name = 'Mike'
cc_num = '0000 0000 0000 0000'
code = '111'
debit_num = '1111 1111 1111 1111'
pin = '1234'
new_customer = Customer(name, cc_num, code, debit_num, pin)

Searching a list to see if there is a match python

Basically this is within a class which appends objects of another class to list self. There are 200 objects in list self. So basically if I call self[1] I will get ['John',['Alex', 'Rob']. Basically 'john' refers to self.firstname and the other names refer to there group members. For example the below will print the firstnames and groupmembers of each object for all 200 objects
for line in self:
print line.firstname
for line in self:
print line.groupmembers
Now I have to create something that goes through all the names and checks the names. So basically if John has Alex and Rob as members then there has to be another object with a first name Alex and another object with a firstname Rob. So say there is no object with firstname Alex I want to print 'mismatch'. This is what I have so far but its not doing what its intended to do.
def name(self):
firstnames = []
for item in self:
firstnames.append(item.firstname)
for item1 in self:
for i in item1.groupmembers:
if i not in hello:
print 'mismatch'
Okay so first off, line and self are bad variable names.
self should only be used within a class to be used as a way to call or use its own variables.
Secondly, you say each value in this self list contains values like ['John',['Alex', 'Rob'], but then you go on to use it like a class object... and frankly that don't do make none sense.
So to remedy this, I'm going to assume its done with class objects. I would also rename self to something like school, and instead of calling an element of self; line, which yields no information to the reader.. call it a student!
I'm going to assume your class would start looking like this:
class Student:
# having an empty default value makes it easy to see what types variables should be!
firstname = ""
groupmembers = []
def __init__(self,firstname,groupmembers ):
self.firstname = firstname
self.groupmembers = groupmembers
Then if you have a list of people you can loop through them like so..
>>>school = [Student("foo", ["bar", "that guy"]),
Student("bar", ["foo", "that guy"])]
>>>for student in school:
print student.firstname
print student.groupmembers
foo
["bar", "that guy"]
bar
["foo", "that guy"]
Then to check it a students group members are in school you can add a function to the Student class
class Student:
# having an empty default value makes it easy to see what types variables should be!
firstname = ""
groupmembers = []
def __init__(self,firstname,groupmembers ):
self.firstname = firstname
self.groupmembers = groupmembers
def group_present(self, school):
# This is how you would get all the names of kids in school without list comprehension
attendance = []
for student in school:
attendance.append(student.firstname)
# this is with list comprehension
attendance = [ student.firstname for student in school]
#compare group members with attendance
#note that I write student_name, not student
## helps point out that it is a string not a class
for student_name in self.groupmembers:
if not student_name in attendance:
print "Group member '{}' is missing :o!! GASP!".format(student_name)
In idle:
>>> school[0].group_present(school)
Group member 'that guy' is missing :o!! GASP!
Hope that helps!
I am not sure if i understand exactly but maybe you can use contains
self[1].__contains__('Alex')
this should return true in case of existence or false otherwise.

Categories

Resources