name error first_name is not defined, after I defined it - python

I'm trying to make a function that returns a fully formmated full name, here is the code,
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = (first_name + ' ' + last_name)
return full_name.title()
_musician = get_formatted_name('jimi', 'hendrix')
print(musician)
get_formatted_name(first_name, last_name)
I keep getting an error in the shell, NameError: name 'first_name' is not defined.

You haven't defined first_name anywhere. You have tried to use it without defining it anywhere first.
To get the code above to work you need to get rid of the last line, de-indent the final 2, rename _musician to musician and it will work, as below:
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = (first_name + ' ' + last_name)
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)

Related

Python Test Case Failed

I was trying to solve a simple python code it run successfully but it fails all the test cases. Can anyone help what mistake I'm doing.
def print_full_name(first_name, last_name):
first_name = 'Ross'
last_name = 'Taylor'
print(f'Hello {first_name} {last_name} ! You are welcome.')
if __name__ == '__main__':
first_name = input()
last_name = input()
print_full_name(first_name, last_name)
The code you supplied does not contain a test so the question is a little confusing.
If you are asking why your inputs do not end up in the print statement.
The following is the answer:
Your method parameters are overridden inside the method by the following lines, this is referred to as hard coding the values.
first_name = 'Ross'
last_name = 'Taylor'
In order to print out what you send via inputs, you need to use the parameters to form the string.
Essentially the two lines above are the problem, as they always populate the sting.
try the following:
def print_full_name(first_name, last_name):
# Create a string using the method parameter values
result = f'Hello {first_name} {last_name} ! You are welcome.'
print(result)
if __name__ == '__main__':
# Assign a value to first_name
first_name = input('first_name: ')
# Assign a value to last_name
last_name = input('last_name: ')
# Call the method passing in the values set above
print_full_name(first_name, last_name)

printing a string in object oriented programming

I'm working on a MOOC on Python Programming and am having a hard time finding a solution to a problem set. I hope you can provide some assistance.
The problem statement is:
This problem uses the same Pet, Owner, and Name classes from the previous problem.
In this one, instead of printing a string that lists a single pet's owner, you will print a string that lists all of a single owner's pets.
Write a function called get_pets_string. get_pets_string should have one parameter, an instance of Owner. get_pets_string should return a list of that owner's pets according to the following format:
David Joyner's pets are: Boggle Joyner, Artemis Joyner
class Name:
def __init__(self, first, last):
self.first = first
self.last = last
class Pet:
def __init__(self, name, owner):
self.name = name
self.owner = owner
class Owner:
def __init__(self, name):
self.name = name
self.pets = []
Add your get_pets_string function here!
Here's my code:
def get_pets_string(Owner):
result = Owner.name.first + " " + Owner.name.last + "'s" + " " + "pets are:" + Pet.name
return result
My code is getting the following error:
AttributeError: type object 'Pet' has no attribute 'name'
Command exited with non-zero status 1
Below are some lines of code that will test your function. You can change the value of the variable(s) to test your function with different inputs.
If your function works correctly, this will originally
print:
David Joyner's pets are: Boggle Joyner, Artemis Joyner
Audrey Hepburn's pets are: Pippin Hepburn
owner_1 = Owner(Name("David", "Joyner"))
owner_2 = Owner(Name("Audrey", "Hepburn"))
pet_1 = Pet(Name("Boggle", "Joyner"), owner_1)
pet_2 = Pet(Name("Artemis", "Joyner"), owner_1)
pet_3 = Pet(Name("Pippin", "Hepburn"), owner_2)
owner_1.pets.append(pet_1)
owner_1.pets.append(pet_2)
owner_2.pets.append(pet_3)
print(get_pets_string(owner_1))
print(get_pets_string(owner_2))
Could you please offer some guidance on what I'm not doing right with my code?
In your code, the name is an instance variable of Pet class. So, to access name of Pet you need an instance of Pet class. But in your code in the Pet.name, the Pet refers to the class and as there is no class variable name in Pet class, the above error is displayed.
To fix this, you can use the member pets of Owner class representing list of Pet object. So in the get_pets_string() you can iterate over pets member of Owner and print names of all the pets.
So after change to get_pets_string(), it will look like -
def get_pets_string(owner):
result = owner.name.first + " " + owner.name.last + "'s pets are: " + ", ".join(p.name.first + " " + p.name.last for p in owner.pets)
return result
Here I have used join() to show the name of all the pets separated by comma

Why is it when I call an attribute of my class, it is printing an older variable instead of the latest one?

I am working with Python class and methods at the moment, and I have the following code:
class Employee:
def __init__(self, first,last):
self.first = first
self.last = last
self.email = first + '.' + last + "#gmail.com"
def fullname(self):
return f'{self.first} + {self.last}'
emp_1 = Employee('John','Smith')
empl_1.first = 'Patrick'
print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname())
And the output is:
Patrick
John.Smith#gmail.com
Patrick Smith
What I am struggling to understand is that when I print the first name by itself, and the full name of the employee, it is using the latest first name, which is defined to be 'Patrick'. However, for the email function, it is still using 'John'. Can someone kindly explain why this is the case?
You only define self.email once - when initialising the object. It will not magically update whenever you change other variables.

Python Error : TypeError: patientInfo() missing 1 required positional argument: 'Disease'

I'm brand new to Python, and I'm trying to learn how to work with classes. Does anyone know how come this is not working?
code is here:
this is my patient class
class Patient:
# Constructor
def __init__(self, name, Age, Gender, Disease):
self.name = name
self.Age = Age
self.Gender = Gender
self.Disease = Disease
# Function to create and append new patient
def patientInfo(self, Name, Age, Gender, Disease):
# use ' int(input()) ' method to take input from user
ob = Patient(Name, Age, Gender, Disease)
ls.append(ob)
and want to access patientInfo in main class but while accessing getting errors regarding the positional argument.
code of the main class is here:
elif user_choice == 2:
print()
f = open("myfile.txt", "a")
f.write(input('\n'))
# "{}\n".format(name)
name = f.write(input("Name: "+ "\n"))
f.write("\n")
Age = f.write((input("Age: "+ "\n")))
Gender = f.write(input("Gender: "+ "\n"))
Disease = f.write(input("Disease: "+ "\n"))
f.close()
Patient.patientInfo(name, Age, Gender, Disease)
can you please suggest to me where I am going wrong?
For your code to work, you have 2 options:
If you want to call patientInfo without creating an object of class Patient then change the function as below:
#staticmethod
def patientInfo(Name, Age, Gender, Disease):
# use ' int(input()) ' method to take input from user
ob = Patient(Name, Age, Gender, Disease)
ls.append(ob)
If you dont want to change the function declaration as above:
Create an object (say obj) of class Patient and call it as obj.patientInfo(...)

Passing a variable as a list of arguments

My code is below. I'm just getting the basic functionality working before making more of the database, but I've run into a problem - Is there any way to pass a variable into four different arguments? My create_person function uses four arguments, but I need to initiate this after I create a Person object.
import os
import sqlite3
from personClass import *
#Connection to database - ToDoDB.db
conn = sqlite3.connect('ToDoDB.db')
cursor = conn.cursor()
def create_table_ToDo():
cursor.execute("""CREATE TABLE ToDo (
Forename text,
Surname text,
FirstChore text,
SecondChore text
)""")
print("ToDo table successfuly created!")
conn.commit()
def create_person(Forename, Surname, FirstChore, SecondChore):
query= "INSERT INTO ToDo (Forename, Surname, FirstChore, SecondChore)values (?,?,?,?);" #Inserts values below into this - question mark to sanitize first -
cursor.execute(query,(Forename, Surname, FirstChore, SecondChore)) #- then executes this command
conn.commit() #Commit and close after each function to save
print("New person and tasks added to the list of users")
#create_table_ToDo()
johnTest = Person("John", "Test", "Ironing clothes", "Washing dishes")
print(johnTest)
create_person(johnTest)
I've included my person class here just in case it helps.
class Person(ToDo):
def __init__(self, firstName, lastName, choreOne, choreTwo):
super().__init__(choreOne, choreTwo)
self.firstName = firstName
self.lastName = lastName
def getName(self):
print("My name is " + self.firstName + " " + self.lastName)
def getTasks(self):
print("My name's " + self.firstName + " and my tasks are " + self.choreOne + ", " + self.choreTwo)
def __repr__(self):
response = "{},{},{},{}".format(
self.firstName,
self.lastName,
self.choreOne,
self.choreTwo)
return response
You can use python's built-in getattr method to access the attribute values of an object. The following line should work:
create_person(getattr(johnTest, 'firstName'), getattr(johnTest, 'lastName'), getattr(johnTest, 'choreOne'), getattr(johnTest, 'choreTwo'))

Categories

Resources