'simple code, help, noob here. In assignment i cant just copy the function. How can I get around that?
This is a recipe that changes depending on how many people they are.
Then the assignment says that the code should then print out the recipe for 4 people and then 7 with a script "important that it is not just a new function".
This is how the file looks like
import math
print("Detta är ett recept på sockerkaka som ändras beroende på hur många serveringar
som ska göras. ")
m = int(input("Skriv antal serveringar:"))
print(m * 0.5, "tsk vaniljsocker")
print(m * 0.75, "dl strösocker")
print(m * 0.5, "tsk bakpulver")
print(m * 18.75, "g smör")
print(m * 0.25, "dl vatten")
print(math.floor(m * 0.75), "st ägg")
print(m * 0.75, "dl vetemjöl")
print(10 + m, "minuter för att blanda smeten")
print(30 + 3*m, "minuter för att grädda kakorna")
print("Total tid för tillagning:",10 + m + 30 + 3*m, "min")
Solution 1:[1]
A function
You can use a function, like this:
def recipe(people: int) -> str:
m = people
recipe_ = f"""{m * 0.5} tsk vaniljsocker\n
{m * 0.75} dl strosocker\n""" # Complete the recipe like this
return recipe_
Than you can call the function like this:
>>> recipe(people)
If you want to know more about functions in python, look at this:
If you really want to make the number of people to be an input, you can do like this:
people = int(input("your text"))
recipe(people)
Repeating the function
If you want to have the recipe more than one time, you can call the function twice or trice.
x = int(input("How many recipes do you want to have?"))
for _ in range(x):
people = int(input("your text"))
print(recipe(people))
If you want to know more about for loops in python, look at this:
F-strings
In Python3 there are several ways to format a string, for example the .format() string method.
>>> years = int(input("How old are you"))
>>> "I'm {} years old".format(years)
Another way to do this is the f-string method:
>>> f"I'm {years} years old"
If you want a longer explaination, look at this:
round() or floor()
Then, you can round the st ägg amount without importing math module, using the built-in method round():
>>> round(10.3)
10
>>> round(10.3, 1)
10.3
You can read more about round there:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
