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.
>
Related
I have a variable in my code that looks like this, only problem is it looks very ugly in my terminal. Here's a picture.
I would like it to display: {Name of the winner} has won: {prize}, instead of showing their Discord ID and making my terminal look horrible to look at.
Here is my code, which makes this monstrosity of a terminal.
winners = random.sample([user for user in users if not user.bot], k=winerscount)
winnerstosend = "\n".join([winner.mention for winner in winners])
win = await msg.edit(embed = discord.Embed(title = "WINNER" , description = f"Congratulations {winnerstosend}, you have won **{msg4.content}**!" , color = discord.Color.blue()))
print(Fore.GREEN + winnerstosend , Fore.WHITE + "has won: " , Fore.GREEN + msg4.content)
print(Style.RESET_ALL)
Now I would love it if you could help me out, and convert my mistake into a beautiful confirmation message.
hmm, try winner.display_name instead of winner.mention
Is user your object?
If so, you can define a str dunder-method and print the string in the way you want.
Please see example below.
user#Inspiron:~/code/advanced_python$ cat str_dunder_example.py
class A:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f'User {self.name} aged {self.age} has won'
if __name__ == '__main__':
a = A('FakeBlob', 20)
print(a)
user#Inspiron:~/code/advanced_python$ python str_dunder_example.py
User FakeBlob aged 20 has won
user#Inspiron:~/code/advanced_python$
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.
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.")
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?
Could you possibly check my syntax and tell me why the debugger skips my try statement and skips to the except.
book class:
class book(object):
def _init_(self, title, author, numPages):
if title is None:
raise ValueError("invalid 'title' argument. please try again")
if author is None:
raise ValueError("invalid 'author' argument. please try again")
if numPages <= 0:
raise ValueError("invalid 'numPages' argument. please try again")
self.title = title
self.author = author
self.numPages = numPages
main class:
from book import book
def printBook (b):
if b is None:
raise ValueError('invalid book argument')
print (b.author + ": " + b.title + "\n" +" Number of page: " + b.numPages )
if __name__ == '__main__':
try:
b1 = book("The Eye of the World", "Robert Jordan", 685)
b2 = book("The Heir of Novron", "Michael J. Sullivan", 932)
printBook(b1)
printBook(b2)
except:
print("ERROR: INVALID BOOK")
There are at least 2 mistakes:
Constructor is called __init__ as jonsharpe already mentioned
you need str() for concatenation of ints and string. So you need to modify your print function:
print (b.author + ": " + b.title + "\n" +" Number of page: " + str(b.numPages) )