Using a list that is inside a variable - python

This problem I'm having is that I cant use that list I have just created and stored inside current_pizza_list.
pizza_1 = ['8.00','Pepperoni']
print('Input 1 for ', pizza_1[1])
current_pizza = input('What pizza would you like:')
current_pizza_list = ('pizza_' + str(current_pizza) + '[1]')
pizza_ammount = input('How many', str(current_pizza_list) ,' pizzas would you like:')

num = 5
pizza_name = 'pizza_' + str(num)
print('Our pizza choices are ' + pizza_name + '!')
#What you created above is a variable. That is not a list. Below is a list:
#pizzas = ['pepperoni', 'extra cheese', 'cheese', 'veggie']
current_pizza = input('What pizza would you like: ')
current_pizza_name = ('pizza_' + str(current_pizza) + '[1]')
pizza_ammount = int(input('How many ' + current_pizza_name + "'s would you like?: "))
print('You would like ' + str(pizza_ammount) + ' ' + current_pizza_name + ' pizzas!')
Here is your output:
Our pizza choices are pizza_5!
What pizza would you like: 5
How many pizza_5[1]'s would you like?: 10
You would like 10 pizza_5[1] pizzas!
Now you've stated that you want a list, but in your example there is not list, so i'm not sure what you mean, but below is an example of a list of pizzas and attaching a number to each pizza after we access it:
pizza_list = [1, 2, 3, 4, 5, 6, 7, 8]
print('Our pizza choices are: ')
for pizza in pizza_list:
print('\t' + str(pizza))
pizza_choice = int(input('Which pizza would you like to select?: '))
if pizza_choice in pizza_list:
current_pizza = 'pizza_' + str(pizza_choice)
else:
print('We do not have that pizza')
pizza_amount = int(input('How many ' + current_pizza + "'s would you like?: "))
print('You would like ' + str(pizza_amount) + ' ' + current_pizza + " pizza's.")
Above we have a list, which I do not see in your code example called pizza list. If the user selects a pizza within the list we can attach that pizza number to the end of the pizza_ string. We then ask the user how many pizza's they want. The pizza_list can server as your list. Here is the output:
Our pizza choices are:
1
2
3
4
5
6
7
8
Which pizza would you like to select?: 5
How many pizza_5's would you like?: 20
You would like 20 pizza_5 pizza's.

I'd suggest
pizza_name = 'pizza_%d' % num
Here the digit will be added to the string.(assuming num is an integer)
The same thing can be done for floats and strings as well with minor modifications:
result = 'format_string goes here: %05.2f' % 2.123
foo = 'bar_%s' % 'baz'
The one with the float probably needs a little explanation: the %05.2f means that the float will be formatted to have 5 places in total, padded with leading zeros and 2 decimal digits after the dot.

Related

Can't fix int and float error in economic simulator

I'm making an economic simulator type thing in python and when trying to calculate total cost when buying something i keep getting either an int error or a float error please help.
can only concatenate str (not "float") to str
import time
money = 1
moneyfo = "{:.2f}".format(money)
woodinv = 0
woodsalea = 1
woodprice = (woodsalea / 2)
woodpricefo = "{:.2f}".format(woodprice)
amntw = 0
float(amntw)
buywcost = 0
print ("Prducts are wood food and stone")
print ("Prices are wood(" + woodpricefo + ")")
bos = input("""Buy Or Sell
""")
if bos == ("Buy"):
btyp = input("""Wood, Food, Or Stone?
""")
if btyp == ("Wood"):
amntw = input("0-100")
buywcost = float(amntw) * woodprice
buywcostfo = "{:.2f}".format(buywcost)
print ("That will be" + float(buywcostfo) + "you have" + money + "would you like to buy")
It's just like the error says--you can only concatenate strings to other strings--i.e. when combining strings using the + operator, you must actually combine strings.
Here is my edited version of the code. I think you avoid the error in question, though I would also recommend making it more readable by adding comments and using more descriptive variable names.
import time
money = 1
moneyfo = "{:.2f}".format(money)
woodinv = 0
woodsalea = 1
woodprice = (woodsalea / 2)
woodpricefo = "{:.2f}".format(woodprice)
amntw = 0
float(amntw)
buywcost = 0
print ("Prducts are wood food and stone")
print ("Prices are wood(" + woodpricefo + ")")
bos = input("""Buy Or Sell""")
if bos == ("Buy"):
btyp = input("""Wood, Food, Or Stone?""")
elif btyp == ("Wood"):
amntw = input("0-100")
buywcost = float(amntw) * woodprice
buywcostfo = "{:.2f}".format(buywcost)
print ("That will be" + str(float(buywcostfo)) + "you have" + str(money) + "would you like to buy")
Your errors are here:
print ("That will be" + float(buywcostfo) + "you have" + money + "would you like to buy")
You need to convert numbers to strings before adding them to other strings:
print ("That will be" + str(float(buywcostfo)) + "you have" + str(money) + "would you like to buy")
Also, this isn't doing what you probably intend:
float(amntw)
You have to save the result of the conversion to a float - it doesn't change the number in-place:
amntw = float(amntw)
However, as you do this:
amntw = 0
float(amntw)
Assuming your intent was to make amntw the float equivalent of 0 you can simply set it directly as a float value:
amntw = 0.0
In your print statement you are casting the type to a float and so you are trying to concatenate a string and a float in 2 different places, python does not allow this.
Change this line:
print ("That will be" + float(buywcostfo) + "you have" + money + "would you like to buy")
Option 1:
print ("That will be" + buywcostfo + "you have" + str(money) + "would you like to buy")
Option 2, Python also has a feature called f strings which allow you to put variables directly inside the string:
print(f"That will be {buywcostfo} you have {money} would you like to buy")
only you have to change the last line as follows
print ("That will be " + str(float(buywcostfo)) + " you have " + str(money) + " would you like to buy")
you can choose print formattings as given here
Not sure why you're initializing variables before they're being used. That's not necessary in python.
amntw = 0 # You don't need any of this
float(amntw) # float() isn't doing anything here without assignment
buywcost = 0 # It's just making your code messy
And don't do str(float(buywcostfo)) as others are suggesting. That would be redundant. Since buywcostfo is already a string, you would be casting a string to a float and back to a string again.
buywcost = float(amntw) * woodprice # buywcost is now a float
buywcostfo = "{:.2f}".format(buywcost) # buywcostfo is a string
print("That will be" + float(buywcostfo) ...) # now it's a float again - can't add to string
You should read up on f-strings. They can make your life easier and really clean up your code a lot.
# This way unless the variables buywcostfo and moneyfo are needed elsewhere,
# they can be removed completely.
print(f"That will be {buywcost:.2f} you have {money:.2f} would you like to buy")

Adding values from a list based on user input

I am trying to take a list of items, each with different amounts and calculate how many of all of the items are needed, based on user input.
For example, a grocery list for a dinner based on how many guest are coming. (5 carrots, 3 onions, 4 peppers, 2 hot dogs, and 1 pound of hamburger) per guest. So the user will input how many guests will be attending and and the item counts will be multiplied based on the input and print that value.
I am new to python, although I know this is a simple problem and I have covered this before, I have spent the past two days trying to get ready for a test and think that I am over-thinking it, because I cant even come close -- so frustrating knowing that once I see it, or something similar it will click. Any help is appreciated. I know that syntax is wrong and everything is messed up, I just typed this up real quick to illustrate a general idea of what I am trying to do. Thanks again.
groc_list= int(input('Enter number of students: ')
carrots= (groc_list* 5)
onions= (groc_list* 3)
peppers= (groc_list* 4)
hot_dogs= (groc_list* 2)
hamburger= (groc_list* 1)
print('You will need', carrots, 'onions', peppers, 'hot dogs', pounds of hamburger')
This works:
groc_list = int(input("Enter number of students: "))
carrots = groc_list * 5
onions = groc_list * 3
peppers = groc_list * 4
hot_dogs = groc_list * 2
hamburger = groc_list * 1
print(
f"You will need {carrots} carrots, {onions} onions, {peppers} peppers, {hot_dogs} hot dogs, {hamburger} pounds of hamburger."
)
Probably this will suit you more:
students = int(input("Enter number of students: "))
grocery_multiplier = {
'carrots': 5,
'onions': 3,
'peppers': 4,
'hot dogs': 2,
'hamburger': 1,
}
texts = []
for field, multiplier in grocery_multiplier.items():
texts.append(f"{multiplier * students} {field}")
print('You will need ' + ', '.join(texts))
When you need to add, remove items to be calculated.
Result:
Enter number of students: 5
You will need 25 carrots, 15 onions, 20 peppers, 10 hot dogs, 5 hamburger
Check if this works. Feel free to ask any question:)
groc_list= int(input('Enter number of students: '))
carrots = (groc_list * 5)
onions= (groc_list* 3)
peppers= (groc_list* 4)
hot_dogs= (groc_list* 2)
hamburger= (groc_list* 1)
print("You will need" , str(carrots)+" " + "carrots ", str(onions)+" "+"onions ", str(peppers)+" "+ "peppers ",str(hot_dogs)+" "+"hot_dogs ", str(hamburger)+" "+ "pounds of hamburger")```
syntax error on line 1, paranthesis was not closed properly.
groc_list= int(input('Enter number of students: '))
carrots= groc_list* 5
onions= groc_list* 3
peppers= groc_list* 4
hot_dogs= groc_list* 2
hamburger= groc_list* 1
print(f'carrots-{carrots}, onions-{onions},peppers-{peppers},hotdogs-{hot_dogs}, hamburgers-{hamburger} ')
In my opinion, you should use a dictionary to track all the variabiles, and use a func. You also miss a round brackets on the first line. Also, at the end, on print, use f. Here is the code that I think is correct
num = int(input('Number of students: '))
mol_dict = {'carrots':5,'onions':3.........)
res_dict = {}
for i in mol_dict:
res_dict[i] = mol_dict[i] * num
print(f'You will need {res_dict['carrots']}.........')
This is more readable, more correct and scalable.
Your code was basically nearly complete. Made a few minor tweaks:
groc_list = int(input('Enter number of students: '))
carrots = groc_list
onions = groc_list* 3
peppers = groc_list* 4
hot_dogs = groc_list* 2
hamburger = groc_list
print('You will need', carrots, 'carrots,', onions, 'onions,', peppers, 'peppers,', hot_dogs, 'hot dogs and', hamburger, 'hamburgers.')

How to start with the number 1 in a for loop?

I want the first output to be "Enter the burst time of process 1" instead of "process 0". How to i do this?
num = int(input('Enter the number of processes: '))
for i in range(num):
b = input('Enter the burst time of process ' + str(i) + ': ')
a = input('Enter the arrival time of process ' + str(i) + ': ')
Python's range function returns integers starting between 0 and the given number if there is no starting parameter.
For instance:
for i in range(3):
print (i)
returns:
0
1
2
if you want to alter your code to print the range starting from 1 and inclusive of the given input, you may consider slightly changing the function to this:
num = int(input('Enter the number of processes: '))
for i in range(1,num+1):
b = input('Enter the burst time of process ' + str(i) + ': ')
a = input('Enter the arrival time of process ' + str(i) + ': ')
If you don't want your range to be inclusive of the given integer you can just do it like this:
num = int(input('Enter the number of processes: '))
for i in range(1,num):
b = input('Enter the burst time of process ' + str(i) + ': ')
a = input('Enter the arrival time of process ' + str(i) + ': ')
For loops work like so:
for [variable] in range(start, end, increment)
per your example, you would like to start at 1, and end at 5 for example
for [variable] in range(1, 5)
the values will display
1
2
3
4
End value always is 1 less because it counts 0, so you want to add +1 to the end if you want the exact number.

How do I ask all of the questions in the list without repeating the lines of code?

question = ["1 – Which seven-a-side ball game is played in a swimming pool?",
"2 - When was the Olympics last held in London?",
"3 - What is the world record time of the men's 100m sprint?",
"4 - The latest Bond song was sung by whom?",
"5 - Who won the Euro 2016 Final?",
"6 - Who is the mascot of Pokemon?",
"7 - How many stars are on the U.S flag?",
"8 - If 1 = 5, 2 = 10, 3 = 15 and 4 = 20, what does 5 =?",
"9 - In a right angled triangle one side is 3 and another side is 4, what is the length of the hypotenuse?",
"10 - What is the 7th decimal place of pi?"]
multi1 = ["A: Marco Polo","A: 1944","A:9.58seconds","A: Charlie Puth","A: Portugal","A: Mew","A: 49","A: 25","A: 2","A: 4"]
multi2 = ["B: Polo","B: 2004","B: 9.68seconds","B: Sam Smith","B: Wales","B: Mewtwo","B: 52","B: 4","B: 5","B: 1"]
multi3 = ["C: Water Polo","C: 2008","C: 9.54seconds","C: Adele","C: France","C: Pikachu","C: 51","C: 5","C: 3.5","C: 9"]
multi4 = ["D: Polo Marco","D: 2012","D: 9.60seconds","D: Daniel Craig","D: Germany","D: Togepi","D: 50","D: 1","D: 6","D: 6"]
correctAnswer = ['C','D','A','B','A','C','D','D','B','D']
valueWon = ['£0','£100','£2500','£500','£1000','£2500','£5000','£10000','£100000','£1000000']
x = input(question[0] + ' ' +multi1[0]+ ' ' +multi2[0]+ ' ' +multi3[0]+ ' ' +multi4[0])
if x == ("A","B","C"):
print("I'm sorry that was incorrect,",correctAnswer[0],"was the correct answer, you won,",valueWon[0])
else:
y = input("Congratulations, you won" +" " +valueWon[1]+" " +"would you like to continue, yes or no?")
if y == ("No","no"):
exit
I'm making a 'who wants to be a millionaire' game and I want to ask all of the questions in the list without repeating all of the code that I have used above as it will be too lengthy and I know that there is an easier way. Thanks
One way would be to turn your questions into individual Class objects.
class Question():
def __init__(self, id, question, answers, correct_answer):
self.id = id
self.question = question
self.answers = answers
self.correct_answer = correct_answer
question_one = Question(
1,
"Which seven-a-side ball game is played in a swimming pool?",
{"1":"Marco Polo", "2":"Water Polo", "3":"Polo", "4":"Polo Marco"},
"Water Polo"
)
question_list = [question_one]
for _ in question_list:
print("Question number {0}: {1}".format(_.id, _.question))
answer = input("{0}\n".format(_.answers))
if _.answers[answer] == _.correct_answer:
print("You're correct!")
The resulting output would be:
>>>Which seven-a-side ball game is played in a swimming pool?
>>>{'2': 'Water Polo', '1': 'Marco Polo', '3': 'Polo', '4': 'Polo Marco'}
>>>2
>>>You're correct!
And so on and so forth. Please note that if you're in Python 2.7, you'll need to remove the quotations from the numbers in the answers dict.
I am assuming that this is what you want. I see a lot of improvisations that can be made to the code. But still, I am presenting my answers here, for starters.
question = ["1 – Which seven-a-side ball game is played in a swimming pool?","2 - When was the Olympics last held in London?",
"3 - What is the world record time of the men's 100m sprint?",
"4 - The latest Bond song was sung by whom?",
"5 - Who won the Euro 2016 Final?",
"6 - Who is the mascot of Pokemon?",
"7 - How many stars are on the U.S flag?",
"8 - If 1 = 5, 2 = 10, 3 = 15 and 4 = 20, what does 5 =?",
"9 - In a right angled triangle one side is 3 and another side is 4,what is the length of the hypotenuse?",
"10 - What is the 7th decimal place of pi?"]
multi1 = ["A: Marco Polo","A: 1944","A:9.58seconds","A: Charlie Puth","A:Portugal","A: Mew","A: 49","A: 25","A: 2","A: 4"]
multi2 = ["B: Polo","B: 2004","B: 9.68seconds","B: Sam Smith","B: Wales","B: Mewtwo","B: 52","B: 4","B: 5","B: 1"]
multi3 = ["C: Water Polo","C: 2008","C: 9.54seconds","C: Adele","C: France","C: Pikachu","C: 51","C: 5","C: 3.5","C: 9"]
multi4 = ["D: Polo Marco","D: 2012","D: 9.60seconds","D: Daniel Craig","D: Germany","D: Togepi","D: 50","D: 1","D: 6","D: 6"]
correctAnswer = ['C','D','A','B','A','C','D','D','B','D']
valueWon = ['£0','£100','£2500','£500','£1000','£2500','£5000','£10000','£100000','£1000000']
for i,j in enumerate(question):
x = input(j + '\n ' +multi1[i]+ '\n ' +multi2[i]+ '\n ' +multi3[i]+ '\n ' +multi4[i]+'\n')
if x == ("A","B","C"):
print("I'm sorry that was incorrect,",correctAnswer[i],"was the correct answer, you won,",valueWon[i])
else:
y = input("Congratulations, you won" +" " +valueWon[i]+" " +"would you like to continue, yes or no?")
if y == ("No","no"):
break
I hope this helps.
Thanks!
To answer your question simply: you could iterate over each question in the list of questions with a foreach loop.
for q in question:
#do something with q, the for loop will do this for every q in your list 'question'
The problem with this is you don't have access to the corresponding multiple choice answers, the correct answer, or the value won easily. That is, if the loop is iterating and you're on the 2nd question, how does the for loop know to present the 2nd multiple choice answers, the 2nd correct answer, etc?
You could do:
for q in question:
#set idx equal to the index number of the current question,
#so if you're on question 3, it'll be index 2, and you can use
#idx to grab the corresponding multiple choice answers/correct answer/etc
idx = question.index(q)
#have the user input an answer
x = input(q + ' ' + multi1[idx] + ... + multi4[idx])
if (x != correctAnswer[idx]):
print("I'm sorry that was incorrect,",correctAnswer[idx],"was the correct answer")
else:
y = input("Congratulations, you won" +" " +valueWon[idx]+" " +"would you like to continue, yes or no?")
if y == ("No","no"):
break
but enumerate already does this for you:
for i, q in enumerate(question):
#have the user input an answer
x = input(q + ' ' + multi1[i] + ... + multi4[i])
if (x != correctAnswer[i]):
print("I'm sorry that was incorrect,",correctAnswer[i],"was the correct answer")
else:
y = input("Congratulations, you won" +" " +valueWon[i]+" " +"would you like to continue, yes or no?")
if y == ("No","no"):
break
You could (and probably should) create a class for this that way all of your data is coupled together instead of spread out over several objects. Then you would just have to iterate over the list of objects and use those in the same way.

Multiplication error in Python 2

I can't get my head around a multiplication problem I'm having in Python 2.7. I'm sure the answer is very simple! As you can tell from the simplicity of my code I am a beginner (see below).
from __future__ import division
goAgain = 'yes'
while goAgain == 'yes':
meal = raw_input('How much did your meal cost? ')
tip = raw_input('Do you want to tip a set PRICE or a PERCENTAGE of your total bill? ').upper()
print
if tip == 'PRICE':
tip = raw_input('How much do you want to tip? ')
bill = int(meal) + int(tip)
print 'As your meal cost ' + str(meal) + ' and your tip is ' + str(tip) + ', your total bill is ' + str(bill) + '.'
elif tip == 'PERCENTAGE':
tip = raw_input('What percentage would you like to tip? ')
tip = int(tip) / 100
print 'Your tip is ' + str(tip)
bill = (int(meal) * int(tip)) + int(meal) # This is where my problem is
print 'The bill is ' + str(bill)
print 'As your meal cost ' + str(meal) + ' and you tipped ' + str(tip) + ' percent, your total bill is ' + str(bill) + '.'
else:
tip = raw_input("Sorry, I didn't catch that! Do you want to tip a set PRICE or a PERCENTAGE of your total bill? ").upper()
The issue I'm having is that the program always tells me that my total bill is the same price as the meal variable, despite (what I can see) that I'm adding the meal and the tip values together.
You divide tip by hundred, getting a number less than 1 (which is quite reasonable). Then when you are multiplying it, you cast it to an integer. (int(meal) * int(tip)) + int(meal)
If you cast a number between 0 and 1 to an int, you get zero.
Instead, if you want to cast the result to an integer, you could do this:
bill = int(int(meal)*tip) + int(meal)
or you might want to try casting to float throughout instead of int. It might give more appropriate results.
The problem (as #khelwood already pointed out) is that dividing two integers with / in Python 2 always gives an integer, so your effective tip rate is zero.
The root of the problem is that you're using Python 2. Division in Python 2 is unintuitive, but continues to work this way for reasons of backward compatibility. You can resolve it once and for all by switching to Python 3, or by adding the following at the top of your script(s):
from __future__ import division
You'll then always get a float when you use / to divide two numbers. (There's also //, which will also give you an integer result.)
Since you have used:
tip = int(tip) / 100
tip is now a float:
>>> tip = int(tip) / 100
>>> type(tip)
<type 'float'>
So when you do:
(int(meal) * int(tip)) + int(meal)
you convert your float (that is <1) to an int, so it will become 0:
>>> int(0.7)
0
So (int(meal) * int(tip)) + int(meal) is (int(meal) * 0) + int(meal) = int(meal).
In order to achieve what you want, you don't have to cast tip:
bill = (int(meal) * tip) + int(meal)
However, you could cast the result if you want:
bill = int((int(meal) * tip) + int(meal))

Categories