Python Function Errors - python

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

Related

Calling a function from outside class with user input without using global

I am trying to avoid using global, instead I created a class. I am having trouble calling the class, instead, I am getting the following error
TypeError: phone.__init__() missing 1 required positional argument: 'NUMBER_INPUT'
Any ideas? Thanks in advance!
class phone:
def __init__(self,NUMBER_INPUT):
self.NUMBER_INPUT = NUMBER_INPUT
def phone_number(self):
"""validate user input of phone number"""
while True:
self.NUMBER_INPUT = input("Please enter your phone number: ")
if re.fullmatch(r"\d{3}-\d{3}-\d{4}" ,self.NUMBER_INPUT):
print("You phone number is: " + self.NUMBER_INPUT)
break
print("Please enter a valid phone number ex. 123-456-5678")
phone().phone_number()
So, I think you neither did read documentation nor watched/read any tutorial about Python classes. So I will explain it here for you.
Class is a "object project". It may have predefined methods, predefined values. It also may have a way to construct these dynamically.
Class object at first need to be instantiated and then initiated. That means that firstly you need to create an instance of a class, then to initiate default values.
Python has 2 methods for this.
__new__() creates a new instance of a class and returns it. It's already realised for every Python class, but there may be special cases for you to override it.
__init__(*args, **kwargs) initiates values of a class. You must define non-static values here or globally in class.
So, creating a class object is achieved in python by calling class like this
A_instance = A(*args, **kwargs)
That in words means create me instance of A with these args and kwargs
So in your code, you are using (actualy overriding) __init__(*args, **kwargs) with args = (NUMBER_INPUT,) and kwargs = None.
Thus you must provide NUMBER_INPUT every time you create an object of phone, like so:
phone1 = phone("123-456-7890")
phone2 = phone("098-765-4321")
You must provide a value for NUMBER_INPUT when calling phone() like phone("123").phone_number().
But it would be better if you will use dummy value for NUMBER_INPUT in constructor like:
class phone:
def __init__(self):
self.NUMBER_INPUT = ""
def phone_number(self):
"""validate user input of phone number"""
while True:
self.NUMBER_INPUT = input("Please enter your phone number: ")
if re.fullmatch(r"\d{3}-\d{3}-\d{4}" ,self.NUMBER_INPUT):
print("You phone number is: " + self.NUMBER_INPUT)
break
print("Please enter a valid phone number ex. 123-456-5678")
phone().phone_number()

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.
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

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)

Regular Expression Python School Class Names for Mock Project

I have a project in python where I want to assign names for my classes in School downtown in the Michigan High School. The classes that I have are '1B, 2B and 3B', and when the user inputs their name and classroom name, their class will be validated to ensure it is correct in the specific format '1,2 OR 3', 'B' - so they cannot write '4B' or '2A' because those classes do not exist.
So far, I have developed this block of code:
while True: # This starts the whole of the while loop.
class_name = str(input("Please enter your class name >>"))
if re.match("1A" "2A" "3A", class_name):
print("Incorrect. Please write your class name again.")
else:
print("Your class name has been accepted")
How can I validate the class_name variable so it can match the classroom names '1A, 2A or 3A?' Thanks,
Taylor Hayward.
Your logic is backwards (and your syntax is wrong, too). You don't want to test for a set of illegal class names (that set is far too large) - you want to test against the set of legal names and repeat if the test fails.
while True: # This starts the whole of the while loop.
class_name = input("Please enter your class name >>") # str() is unnecessary
if class_name not in {"1B", "2B", "3B"}:
print("Incorrect. Please write your class name again.")
else:
print("Your class name has been accepted")
break # Exit the while loop
A regex would also be possible:
if not re.match("[123]B$", class_name):
Note the $ anchor to ensure that the match ends after B, otherwise input like 2BC would be accepted by the regex (re.match() only anchors the match to the start of the string, not the end).

Categories

Resources