Call function for paired arguments - python

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)

Related

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)

Class function doesn't show the value passed in

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

I am receiving an error when executing python <function personAge at 0x101fe6050> instead of the value

I am trying to complete this program for a computer science class, but I am stuck on this error
Hello Tristan Wiener. You are function personAge at 0x101fe6050 years old.
Why am I getting instead of te age?
`#This program calculates a users age while collecting the user's
#birth year, the user's first and last name, the current year
#and whether the user has had their birthday yet.
firstName = raw_input("Please enter your first name")#Get the first name
lastName = raw_input("Please enter your last name")#Get the last name
birthYear = int(input("What is your birth year?"))#Get the birth year
currentYear = int(input("What is the current year?"))#Get the current year
birthdayYet = raw_input("Have you had your birthday yet? [1 for yes/2 for no]")
#Ask if the user has had their birthday
age = 0
def fullName (firstName, lastName):
outStr = firstName +" "+lastName
return outStr
def personAge(birthYear, currentYear, birthdayYet):
if birthdayYet == 1:
print(currentYear - birthYear)
if birthdayYet == 2:
age = currentYear - birthYear - 1
return str(age)
def printMsg(personName,personAge):
return ("Hello" + " " + str(personName) + "." + " " + "You are" + " " + str(personAge) + " " + "years old.")
personName = fullName(firstName, lastName)
userAge = personAge(birthYear, currentYear, birthdayYet)
finalMsg = printMsg(personName, personAge)
print finalMsg`
Replace …
finalMsg = printMsg(personName, personAge)
… with …
finalMsg = printMsg(personName, userAge)
Remember personAge is a function not a number.
finalMsg = printMsg(personName, personAge)
Should be
finalMsg = printMsg(personName, userAge)
personAge is the function you are using to get the persons age. userAge is the persons actual age.

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?

Running a dictionary with a while loop

I am trying to insert a while loop into this program so when it asks for member it starts a dictionary (assuming I would use a dictionary) that lets me input n number of band members and the instrument they use in some form like (name,instrument),(name2,instrument2)..and so on. I know it will be run as a while loop, but I'm not not sure how to enter it in this instance. Would using a dictionary be the best action and if so how would I add it in a case like this?
class Song:
def __init__(self, song, chart, member):
self.song = song
self.chart = chart
self.member = member
def __str__(self):
return (self.song
+ " Top Chart:"
+ str(self.chart)
+ " Band Members: "
+ str(self.member)
+ '\n')
def write():
with open("string.txt", "a+", encoding="utf-8") as f:
while(1):
prompt = ":\t"
in_song = input("Input song or type q " + prompt)
if (in_song == 'q'):
break
in_chart_spot = input("Input chart spot" + prompt)
in_band_mem = input("Input band members" + prompt)
song_data = Song(in_song, in_chart_spot, in_band_mem)
#albumdata = Album()
f.write(str(song_data))
if __name__ == '__main__':
write()

Categories

Resources