I just started learning Python 2 days ago and I created a simple "store" that you can order and the program would tell you the total. But the problem is that I don't know how to make a person's answer to show the total value of the product. As in if person A orders an iPhone, it'll show the price of the iPhone.
I kind of did it but I used the if statements, but I know that this method isn't efficient, as well as if Person B chooses more than 1 product, I don't know how to make a sum of the prices automatically instead of using the if statements, here is my code, thank you!
print("Welcome to the Apple Store!")
name = input("What is your name?\n")
print("Hello " + name + ", welcome to the Apple store!\n\n")
products = "iPhone 14 $10,000, Macbook Air $14,000, iPhone 13 $8,000\n"
value = input
iPhone_14 = 10000
Macbook_Air = 14000
iPhone_13 = 8000
a = iPhone_14 + Macbook_Air
order = input("Here is our list of products, what would you want?\n" + products)
if order == "iPhone 14":
print("Alright " + name + ", your " + order + " will be prepared.\n\n" + "The total amount will be " + str(iPhone_14))
if order == "Macbook Air":
print("Alright " + name + ", your " + order + " will be prepared.\n\n" + "The total amount will be " + str(Macbook_Air))
if order == "iPhone 13":
print("Alright " + name + ", your " + order + " will be prepared.\n\n" + "The total amount will be " + str(iPhone_13))
if order == "iPhone 14, Macbook Air":
print("Alright " + name + ", your " + order + " will be prepared.\n\n" + "The total amount will be " + str(a))
This could be a simple solution, I left you some comments inside the code:
# you can use a dictionary to store the value of each product
products = {"iPhone_14": 10000, "Macbook_Air": 14000, "iPhone_13": 8000}
# this list will contain the keys of the products you want to add to cart
cart = []
print("Here our list of products {}, what do you want to buy?\nEnter 'stop' when you're done\n".format(list(products.keys())))
stop = False
while not stop:
order = input("Insert a product:")
if order == "stop":
# if the user want to stop entering products, can type "stop" instead of a product
stop = True
elif order in products:
cart.append(order)
else:
# if the product entered is not among the products dictionary keys
print("Product {} is not available".format(order))
print("\nThis is your cart:")
total = 0
for elem in cart:
print("Product {} ({}$)".format(elem, products[elem]))
total += products[elem]
print("Your total is {}$".format(total))
Example:
Here our list of products ['iPhone_14', 'Macbook_Air', 'iPhone_13'], what do you want to buy?
Enter 'stop' when you're done
Insert a product:Macbook_Air
Insert a product:iPhone_14
Insert a product:stop
This is your cart:
Product Macbook_Air (14000$)
Product iPhone_14 (10000$)
Your total is 24000$
So I'm trying to make a calculator but when i do plus (also with other things but for example) it does work but after the outcome comes it asks for number 2 again, I just want the code to start again.
this is the plus piece of the code:
q = input(str("Wil je de bewerkingsteken legende zien? (j/n): "))
if q == "J" or q == "j" :
print ("\nplus = + ")
print ("min = -")
print ("maal = X")
print ("delen door = :")
print ("quadrateren = Q")
print ("tot de kracht van = P")
print ("Worteltrekken = W")
print ("Procent = %")
num1 = float(input("\n Nummer 1: "))
bew = input("\n Bewerkingsteken: ")
num1_word = (str(num1))
if bew == "+" :
plus_num2 = input(float("\nNummer 2: "))
plus_num2_con = (str(plus_num2))
plus_out = (num1 + plus_num2)
plus_out1 = (str(plus_out))
print ("\n" + num1_con +" + " + num2_con + " = " + plus_out1)
First, you write the input wrong for plus_num2. Try this;
plus_num2 = float(input("\nNummer 2: "))
Second, you define the number's name different from last print function. Try This;
print ("\n" + num1_word +" + " + plus_num2_con + " = " + plus_out1)
Third, if you want to start the code again you can add while True on first line.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I'm trying to build a BMI calculator for a project. It must prompt the user to enter the height and weight of 6 members (the elements in the array), calculate the input and print the BMI of each member. I've got that part taken care of, but I'm stumbling on the part where we use that to populate a second array and count the number of individuals that are underweight, overweight, or normal weight. Here is what I have so far:
Names = ["Jim", "Josh", "Ralph", "Amber", "Chris", "Lynn"]
Hs = []
Ws = []
UW = 18.5
OW = 25
for Name in Names:
Hs.append(int(input("What is your height in inches, " + Name + ": ")))
Ws.append(int(input("What is your weight in pounds, " + Name + ": ")))
def BMI(Ws, Hs):
for W, H in zip(Ws, Hs):
bmi_total = (W * 703) / (H ** 2)
for Name in Names:
print("The BMI for " + Name + " is: ", bmi_total)
BMI(Ws, Hs)
BMIScore = [bmi_total]
countUW = 0
countHW = 0
countOW = 0
for i in BMIScore:
if i <= UW:
countUW = countUW + 1
print("There are ", countUW, "underweight individuals.")
if i > UW and i < OW:
countHW = countHW + 1
print("There are ", countHW, "individuals with a healthy weight.")
if i >= OW:
countOW = countOW + 1
print("There are ", countOW, "overweight inividuals.")
And here is the output I get:
What is your height in inches, Jim: 5
What is your weight in pounds, Jim: 5
What is your height in inches, Josh: 5
What is your weight in pounds, Josh: 5
What is your height in inches, Ralph: 5
What is your weight in pounds, Ralph: 5
What is your height in inches, Amber: 5
What is your weight in pounds, Amber: 5
What is your height in inches, Chris: 5
What is your weight in pounds, Chris: 5
What is your height in inches, Lynn: 5
What is your weight in pounds, Lynn: 5
The BMI for Jim is: 140.6
The BMI for Josh is: 140.6
The BMI for Ralph is: 140.6
The BMI for Amber is: 140.6
The BMI for Chris is: 140.6
The BMI for Lynn is: 140.6
Traceback (most recent call last):
File "C:\Users\Crase\AppData\Local\Programs\Python\Python39\Final Project.py", line 30, in <module>
if i <= UW:
TypeError: '<=' not supported between instances of 'tuple' and 'float'
Additionally, is there a way to add whether a particular individual from the array is overweight or underweight in the line "print("The BMI for " + Name + " is: ", bmi_total)" ?
Any assistance would be appreciated. And please pardon me if my presentation is a bit sloppy. It's my first time posting.
If you can't use an object-oriented approach, you can use lists of tuples to represent a person:
names = ["Jim", "Josh", "Ralph", "Amber", "Chris", "Lynn"]
people = []
for name in names:
height = int(input("What is your height in inches, " + name + ": "))
weight = int(input("What is your weight in pounds, " + name + ": "))
# Calculate the BMI while iterating over the list of names
bmi = (weight * 703) / (height ** 2)
people.append((name, height, weight, bmi))
Then, you can use a dictionary to store the overs, healthies and unders:
UW_LIM = 18.5
OW_LIM = 25
stats = {"OW": 0, "HW": 0, "UW": 0}
for name, _, _, bmi in people:
print("The BMI for", name, "is", bmi)
key = "UW" if (bmi < UW_LIM) else "HW" if (UW_LIM < bmi < OW_LIM) else "OW"
stats[key] += 1
Finally, just print 'em out:
print("There are", stats["UW"], "underweight individuals.")
print("There are", stats["HW"], "individuals with a healthy weight.")
print("There are", stats["OW"], "overweight inividuals.")
For fun, here's an OOP approach:
class Person:
def __init__(self, name: str, height: float, weight: float):
self.name = name
self.height = height
self.weight = weight
#property
def bmi(self):
return (self.weight * 703) / (self.height ** 2)
#property
def classification(self):
return 0 if (bmi < UW_LIM) else 1 if (UW_LIM < bmi < OW_LIM) else 2
names = ["Jim", "Josh", "Ralph", "Amber", "Chris", "Lynn"]
# UW HW OW
stats = [ 0, 0, 0]
for name in names:
height = int(input("What is your height in inches, " + name + ": "))
weight = int(input("What is your weight in pounds, " + name + ": "))
person = Person(name, height, weight)
print("The BMI for", person.name, "is", person.bmi)
stats[person.classification] += 1
print("There are", stats[0], "underweight individuals.")
print("There are", stats[1], "individuals with a healthy weight.")
print("There are", stats[2], "overweight inividuals.")
Answering the first question you might want to try changing i into float(i). I'm not sure this will work with all of the loops, but you need to define the type of variable "i" is. And to answer the second question, can you could provide more information about what "overweight" and "underweight" is, but you could add a statement like this:
if bmi_total <= 150:
#etc.
Your bmi_total is defined within your BMI function but then used outside of it. The error I got when trying your code specifically pointed to that. To solve that you could make bmi_total a global so it is accessible outside of the function like this:
Names = ["Jim", "Josh", "Ralph", "Amber", "Chris", "Lynn"]
Hs = []
Ws = []
UW = 18.5
OW = 25
for Name in Names:
Hs.append(int(input("What is your height in inches, " + Name + ": ")))
Ws.append(int(input("What is your weight in pounds, " + Name + ": ")))
def BMI(Ws, Hs):
for W, H in zip(Ws, Hs):
# changed bmi_total to be a global variable here
global bmi_total
bmi_total = (W * 703) / (H ** 2)
for Name in Names:
print("The BMI for " + Name + " is: ", bmi_total)
BMI(Ws, Hs)
BMIScore = [bmi_total]
countUW = 0
countHW = 0
countOW = 0
for i in BMIScore:
if i <= UW:
countUW = countUW + 1
print("There are ", countUW, "underweight individuals.")
if i > UW and i < OW:
countHW = countHW + 1
print("There are ", countHW, "individuals with a healthy weight.")
if i >= OW:
countOW = countOW + 1
print("There are ", countOW, "overweight inividuals.")
However, it would be better form to have the BMI function calculate the BMI and return that. Most programmers are either directly or indirectly fans of the KISS (Keep It Stupid Simple) principle. Basically, seperate each chunk of functionality into a logical function (like BMI()) and have it do one thing and one thing only (in this case, calculate the BMI).
As others have stated, you will also probably want to group your names, weights, heights, and BMI for each person into a container to keep things more organized. That could be a list of lists, a dictionary, a class, or any number of other ways of keeping associated information together. Great start though!
print(input("Enter invoice number :- "))
t=0
for x in range (1,5,1):
p=int(input(print("Enter",x,"st ",end='')))
print(p)
t+=p
print("product",x," price = ",p)
print("Total Bill = ",t)
In the line p=int(input(print("Enter",x,"st ",end=''))), the print function does not return anything so what is is happening is you are printing "Enter 1 st" then printing None as print return None.
To fix:
p=int(input("Enter " + str(x) + " st "))
Change:
p=int(input(print("Enter",x,"st ",end='')))
to:
prompt = "Enter {}st ".format(x)
p = int(input(prompt))
input prints its argument, so you don't need to call print when passing an argument as a prompt. If you do, then print will print it, and will then return None, which input will then print.
This should fix it
print(input("Enter invoice number :- "))
t=0
for x in range(1, 5):
string = "Enter " + str(x) + "st "
p = int(input(string))
print(p)
t+=p
print("product", x, " price = ", p)
print("Total Bill = ",t)
So i've been trying to create a calculator with more complex structure. The problem that am facing is that i'm trying to create a function that calls another function, i know it seems unneccesary but it will be needed in the future. I have a problem calling the function.
class Calculator:
class Variables:
# Start by defining the variables that you are going to use. I created a subclass because I think is better and
# easier for the code-reader to understand the code. For the early stages all variables are going to mainly
# assigned to 0.
n = 0 # n is the number that is going to be used as the main number before making the math calculation
n_for_add = 0 # n_for_add is the number that is going to added to "n" in addition
n_from_add = 0 # n_from_add is the result from the addition
self = 0
def addition(self):
try:
n = int(input("enter number: ")) # user enters the n value
n_for_add = int(input("What do you want to add on " + str(n) + " ? ")) # user enters the n_for_add value
except ValueError: # if the value is not an integer it will raise an error
print("you must enter an integer!") # and print you this. This will automatically kill the program
self.n = n
self.n_for_add = n_for_add
n_from_add = n + n_for_add # this is actually the main calculation adding n and n_for_add
self.n_from_add = n_from_add
print(str(n) + " plus " + str(n_for_add) + " equals to " + str(n_from_add)) # this will print a nice output
def subtraction():
try:
nu = int(input("enter number: "))
nu_for_sub = int(input("What do you want to take off " + str(nu) + " ? "))
except ValueError:
print("you must enter an integer!")
nu_from_sub = nu - nu_for_sub
print(str(nu) + " minus " + str(nu_for_sub) + " equals to " + str(nu_from_sub))
# this is the same as addition but it subtracts instead of adding
def division():
try:
num = int(input("enter number: "))
num_for_div = int(input("What do you want to divide " + str(num) + " off? "))
except ValueError:
print("you must enter an integer!")
num_from_div = num / num_for_div
print(str(num) + " divided by " + str(num_for_div) + " equals to " + str(num_from_div))
# same as others but with division this time
def multiplication():
try:
numb = int(input("enter number: "))
numb_for_multi = int(input("What do you want to multiply " + str(numb) + " on? "))
except ValueError:
print("you must enter an integer!")
numb_from_multi = numb * numb_for_multi
print(str(numb) + " multiplied by " + str(numb_for_multi) + " equals to " + str(numb_from_multi))
# its the same as others but with multiplication function
def choice(self):
x = self.addition()
self.x = x
return x
choice(self)
Hope it will help you.
Code modified:
class Variables:
def addition(self):
try:
n = int(input("enter number: ")) # user enters the n value
n_for_add = int(input("What do you want to add on " + str(n) + " ? ")) # user enters the n_for_add value
return n + n_for_add
except ValueError:
# if the value is not an integer it will raise an error
pass
def choice(self):
x = self.addition()
self.x = x
return x
objectVariables = Variables()
print objectVariables.choice()
I hope this it may serve as its starting point:
def div(x, y):
return x / y
def add(x, y):
return x + y
def subs(x, y):
return x - y
def do(operation, x, y):
return operation(x, y)
print do(add, 4, 2)
print do(subs, 4, 2)
print do(div, 4, 2)