Class function doesn't show the value passed in - python

My function doesn't show the input number for number_served:
class Restaurant():
def __init__(self, name, cuisine):
self.name = name
self.cuisine = cuisine
self.number_served = 0
def describe_rest(self):
print("Welcome to " + self.name.title() + "!")
print("We serve the best " + self.cuisine.title() + " food!")
def open_rest(self):
print(self.name.upper() + " is OPEN now!")
def set_number_served(self, number_served):
print("We have served " + str(self.number_served)
+ " customers today.")
def increment_number_served(self, additional_served):
print("We have served " + str(self.number_served)
+ str(self.additional_served) + " customers today.")
restaurant = Restaurant('gamja', 'korean')
print("\n")
restaurant.describe_rest()
print("\n")
restaurant.open_rest()
restaurant.set_number_served(1000)
At the last line, restaurant.set_number_served(1000), I get "We have served 0 customers today." instead of 1000. What am I doing wrong here?

You forgot to set the instance variable in that routine. Simply add a line to do that.
def set_number_served(self, number_served):
self.number_served = number_served
print("We have served " + str(self.number_served)
+ " customers today.")

Related

line 2 error python crash course eric matthes problem 9-2

This is in chapter 9. The three restaurants problem, says there's a syntax error with the colon in line 2. Don't understand why that would be or if the error is somewhere else. May have mistyped something somewhere but not sure where, probably something simple i overlooked. Thanks.
Here's the code:
class Restaurant():
def__init__(self, name, cuisine_type):
self.name = name.title()
self.cuisine_type = cuisine_type
def describe_restaurant(self):
msg = self.name + " serves wonderful " + self.cuisine_type + "."
print("\n" + msg)
def open_restaurant(self):
msg = self.name + " is open. Come on in!"
print("\n" + msg)
mean_queen = Restaurant('the mean queen', 'pizza')
mean_queen.describe_restaurant()
ludvigs = Restaurant("ludvig's bistro", 'seafood')
ludvigs.describe_restaurant()
mango_thai = Restaurant('mango thai', 'thai food')
mango_thai.describe_restaurant()
If you are still having issues, try this. You may have missed the indentation after your class declaration
class Restaurant():
def __init__(self, name, cuisine_type):
self.name = name.title()
self.cuisine_type = cuisine_type
def describe_restaurant(self):
msg = self.name + " serves wonderful " + self.cuisine_type + "."
print("\n" + msg)
def open_restaurant(self):
msg = self.name + " is open. Come on in!"
print("\n" + msg)
mean_queen = Restaurant('the mean queen', 'pizza')
mean_queen.describe_restaurant()
ludvigs = Restaurant("ludvig's bistro", 'seafood')
ludvigs.describe_restaurant()
mango_thai = Restaurant('mango thai', 'thai food')
mango_thai.describe_restaurant()
output
The Mean Queen serves wonderful pizza.
Ludvig'S Bistro serves wonderful seafood.
Mango Thai serves wonderful thai food.
>

Python variable inside of function not able to be called

I am making an rpg type thing with python and I made a few functions but I need to call variables that were stated and altered inside of a separate function. How would I be able to call a variable inside a function.
My Code:
import time
def title():
print("Hello Welcome To Elvoria")
time.sleep(1)
print("Choose Your Gender, Name, And Race")
time.sleep(1)
def gnd():
Gender = input("""Male, Female, Or NonBinary?
""")
if Gender == ("Male"):
genderin = 'Male'
elif Gender == ("Female"):
genderin = 'Male'
elif Gender == ("NonBinary"):
genderin = 'Male'
else:
gnd()
def nm():
namein = input("""What Is Your Character's Name?
""")
print("Welcome To Elvoria "+namein+"")
def rac():
print("""The Race Options Are:
Elf-Good With Archery And Light Armor
Kelner-Good With Two Handed Weapons And Heavy Armor
Human-Good With Bows And Stealth
Mageine-Good With Magic And Speed""")
time.sleep(1)
racin = input("""Now Choose A Race
""")
if racin == ("Elf"):
print ("You Are Now A " + genderin + racin +" Named" + namein + "")
elif racin == ("Kelner"):
print ("You Are Now A " + genderin + racin +" Named" + namein + "")
elif racin == ("Human"):
print ("You Are Now A " + genderin + racin +" Named" + namein + "")
elif racin == ("Magein"):
print ("You Are Now A " + genderin + racin +" Named" + namein + "")
else:
print ("You Are Now A " + genderin + racin +" Named" + namein + "")
title()
time.sleep(1)
gnd()
time.sleep(1)
nm()
time.sleep(1)
rac()
And The Error Code:
print ("You Are Now A " + genderin + racin +" Named" + namein + "")
NameError: name 'genderin' is not defined
Change your functions to return the result, and take the values they need as parameters:
def gnd() -> str:
gender = input("""Male, Female, Or NonBinary?
""")
if gender in ("Male", "Female", "NonBinary"):
return gender
return gnd()
def nm() -> str:
name = input("""What Is Your Character's Name?
""")
print(f"Welcome To Elvoria {name}")
return name
def rac(gender: str, name: str) -> str:
print("""The Race Options Are:
Elf-Good With Archery And Light Armor
Kelner-Good With Two Handed Weapons And Heavy Armor
Human-Good With Bows And Stealth
Mageine-Good With Magic And Speed""")
time.sleep(1)
race = input("""Now Choose A Race
""")
print (f"You Are Now A {gender} {race} Named {name}")
return race
When you call them, make sure to assign the values to variables so you can use them again:
title()
time.sleep(1)
gender = gnd()
time.sleep(1)
name = nm()
time.sleep(1)
race = rac(gender, name)
You have 2 options:
You could create a global variable, and define that using the global statement in your function, so you can use the global value afterwards
You could pass a value to the function, and work with it (the better way, using global variables should be avoided)

Python TypeError: CreateAccount() missing 1 required positional argument

I created this terminal app a while ago and it was working, but I haven't touched in a while and I just opened it back up and I can't figure out what this error is and why I'm having it. It's happening during the account creation part of my program. I tried a couple things out but I'm still not sure what's going on.
**TypeError: CreateAccount() missing 1 required positional argument**
main.py
from Account import Account
from Transaction import Transaction
from enum import Enum
from fcp import CreateAccount
#variables and lists needed for program
new_accounts = []
#do no tneed, just put the balance of 0 straight into the factory class attribute
#balance = 0
user_name = []
Transactions = []
account_number = 0
#***Functions for switch statements***
def create_user():
global new_accounts
global account_number
active_create_account = False
new_username = input("\n\nCreate a username:")
email = input("Write your email: ")
account_number +=1
print(account_number)
# append the createaccount call straight into new_accounts.append
new_accounts.append(CreateAccount(user_name,email, int(input('Choose 1 for Checkings or 2 for Savings: ')), 0, 0))
active_create_account = True
for i in new_accounts:
if account_number == i.account_number:
i.new_account_creation()
account_search_balance = True
if account_search_balance == False:
print("\nThat account does not exist. Please re-enter option 5 and try again.")
main()
fcp.py
from Account import Account
from Transaction import Transaction
#BLANK CLASS TEMPLATE
def CreateAccount(self,user_name,email,account_type,balance,account_number):
account_number +=1
if (account_type == 1): return CreateCheckingAccount(user_name,email,1,balance,account_number)
if (account_type == 2): return CreateSavingsAccount(user_name,email,2,balance,account_number)
else:
return CreatAccount(user_name,email, int(input('Choose 1 for Checkings or 2 for Savings: ')),balance,account_number)
def CreateCheckingAccount(self,user_name,email,account_type,balance,account_number):
return Account(user_name, email,'Checking',balance,account_number)
def CreateSavingsAccount(self,user_name,email,account_type,balance,account_number):
return Account(user_name, email,'Savings',balance,account_number)
transaction.py
import datetime
class Transaction():
def __init__(self,account_number,type_of_transaction,old_balance,new_balance,date = datetime.datetime.now()):
self.account_number = account_number
self.type_of_transaction = type_of_transaction
self.old_balance = old_balance
self.new_balance = new_balance
self.date = datetime.datetime.now()
def to_string(self):
print("\nThe account number is: " + str(self.account_number) + "\nThe type of transaction is: " + self.type_of_transaction + "\nThe old balance was: " + str(self.old_balance) + "\nThe new balance is: " + str(self.new_balance) + "\nThe date of the transaction was: " + str(self.date))
def print_date(self):
print(str(self.date))
Account.py
class Account(object):
def __init__(self,user_name,email,account_type,balance,account_number):
self.user_name = user_name
self.email = email
self.account_type = account_type
self.balance = balance
self.account_number = account_number
def print_balance(self):
print("\nAccount bala is "+ str(self.balance))
return
def new_balance(self):
print("\nThe new account balance is: " + str(self.balance))
def to_string(self):
print("\nUsername: " + self.user_name + "\n\nEmail: " + self.email + "\n\nAccount type: " + (self.account_type) +
"\n\nYour account balance is:" + str(self.balance) +"\n\nAccount number: " + (self.account_number))
def new_account_creation(self):
print("\nCongragulations on your new account! Below is the info:\nUsername: " + self.user_name + "\nEmail: " + self.email + "\nAccount type: " + self.account_type +
"\nYour account balance is:" + str(self.balance) +"\nAccount number: " + str(self.account_number)+ " <--- Do NOT forget this number")
def Deposit(self):
deposit = int(input("\nHow much would you like to deposit?: "))
self.balance += deposit
def withdraw(self,withdraw):
self.balance -= withdraw
you should initiate the class object that contains createAccount() method before invoke.
class TestClass:
def __init__(self):
print("in init")
def createAccount(self, ...):
print("in Test Func")
testInstance = TestClass()
testInstance.createAccount(...)
It looks as though your method definition requires self as an argument but CreateAccount is not in a class. Therefore it is not required.
(remove self in the required arguments)
It's pretty clear, even though you left out the rest of the error message and failed to minimize your code: your function profile requires a self argument that the call didn't bother to provide. Since you used the name self, it seems as if you might want to create a class -- but you didn't do that with the function, nor with the call.
If a class is, indeed, what you want, then please return to your tutorial on class to make sure you implement all of the right items.

How to print the for loop as the last thing in a function?

So here is my function and some info on it:
This function is called by another function, so returning the result1 would print what I want.
So, in this function, I want to be able to print result1 then the for loop after; although, since I am unable to place the for loop inside the return, it would always print the for loop first, then the returned result1 would be printed next.
Note: Dish_str() is another function, I will include it at the bottom
def Restaurant_str(self: Restaurant) -> str:
result1 = ("Name: " + self.name + "\n" +
"Cuisine: " + self.cuisine + "\n" +
"Phone: " + self.phone + "\n" +
"Menu: ")
for i in self.menu:
print(Dish_str(i))
return result1 + "\n\n"
This is the result:
Fried Chicken ($10.00): 1300.0cal
Name: KFC
Cuisine: American
Phone: 1112223333
Menu:
I want to make it so that the dish would come after the menu.
One way that I attempted to make it work was putting the Dish_str() into the return so it would look like this:
return result1 + Dish_str(self.menu) + "\n\n"
To which, I'd receive an error that says an attribute error saying that the list does not contain attribute name, even though in the for loop, it was able to work. Then I tried doing simply just Dish_str(self) which gives me a type error that can't concatenate a list.
Another way I tried to make it work was also split the for loop into another function and have the Restaurant_str() call it, but alas, no avail because I realized it was the same exact thing as calling Dish_str() just with another extra function.
Here is the other functions that are calling it and being called on:
def Dish_str(self: Dishes) -> str:
'''Returns a string that represents the dish name, price, and calories'''
result = self.name + " ($" + str("%.2f" % self.price) + "): " +
str(self.calories) + "cal"
return result
def Collection_str(C: list) -> str:
''' Return a string representing the collection
'''
s = ""
for r in C:
s = s + Restaurant_str(r)
return s
I simply print the collection through:
print(Collection_str(C))
Please let me know if you need me to clarify anything as I wrote this late at night and didn't have time to check in the morning. Thank you for your patience and help in advance.
Just add the string dish to the end of result1, result1 = result1 + Dish_str(i)
def Restaurant_str(self: Restaurant) -> str:
result1 = ("Name: " + self.name + "\n" +
"Cuisine: " + self.cuisine + "\n" +
"Phone: " + self.phone + "\n" +
"Menu: ")
for i in self.menu:
result1 = result1 + Dish_str(i)
return result1 + "\n\n"
Would this help?

Call function for paired arguments

Here is simple script to generate greeting messages:
def greeting(event, person):
print("Happy " + event + ", dear " + person + ".")
event = "Birthday"
person = "Emily"
greeting(event, person) # Happy Birtday, dear Emily.
event = "New Year"
person = "Mark"
greeting(event, person) # Happy New Year, dear Mark.
Is there way to get the same result, but call the greeting function only once?
You can put this in a loop to handle a list of names and events. I'd recommend keeping the inner function the same, and firing a sequence of data at it from outside. Depending on your application, mileage may vary.
def greeting(event, person):
print("Happy " + event + ", dear " + person + ".")
event_list = [("Birthday", "Emily"),
("New Year", "Mark")]
for event, person in event_list:
greeting(event, person)
If you can modify greeting:
def greeting(info_pairs):
for event, person in info_pairs:
print("Happy " + event + ", dear " + person + ".")
greeting([("Birthday", "Emily"), ("New Year", "Mark")])
If you just want to the function to loop over the inputs, this should work:
def greeting(messages):
for event, person in messages:
print("Happy " + event + ", dear " + person + ".")
greeting([('Birthday', 'Emily'), ('New Year', 'Mark')])
Either of the options mentioned by other users will work. It depends on whether you want to put the loop in the function or outside of it:
def greeting(event, person):
print("Happy " + event + ", dear " + person + ".")
for event, person in [("Birthday", "Emily"),
("New Year", "Mark")]:
greeting(event, person)

Categories

Resources