I am trying to loop an input for a selected amount of time "enter how may ingredients you want:" say if the user inputs 5 then a loop "ingredients" will run 5 times for them to enter their ingredients. Sorry if it seems like a basic question, but I'm quite new to this. Thanks for any answers :).
a=input("hello, welcome to the recipe calculator \nenter your recipe name, number of people you will serve and the list of ingredients \n1.retrive recipe \n2.make recipe \noption:")
if a=="2":
print("now enter the name of your recipe")
f=open('c:\\username_and_password.txt', 'w')
stuff = input("create name:")
nextstuff = (int(input("enter number of people:")))
nextstufff = (int(input("enter how many ingredients you want:")))
for (nextstufff) in range(0, 10): #I have put 0, 10 because the user probably wont put more than 10 ingredients. But there's probably a much better way?
print ("ingredient") + (nextstufff) #what am I doing wrong in this for loop
nextstuffff = (int(input("so how much of\n" + nextstufff + "would you like:")))
f.write(str(stuff + "\n") + str(nextstuff) + str(nextstufff))
f.close()
It would be difficult to cleanly answer your question(s) -- so I'll focus specifically on the looping over ingredients question. This should get you pointed in the right direction.
def read_items(prompt):
items = []
while True:
answer = raw_input('%s (blank to end): ' % prompt)
if not answer:
return items
items.append(answer)
ingredients = read_items('enter ingredients')
counts = []
for item in ingredients:
cnt = raw_input('how much of %s:' % item)
counts.append(int(cnt))
print zip(ingredients, counts)
it's not print ("ingredient") + (nextstufff), change it to print ("ingredient:", nextstufff).
Or you can use string formatting:
print ("ingredient: %d"%nextstufff)
Related
this is my homework:
Write a program that asks for the names and ages of 10 students.
Prints the names and ages of the students alphabetically in a table
format -- while also identifying the oldest student as the "Team
Leader".
And this is what I've done so far. Comments are what I think I'm supposed to do but not sure:
#from tabulate import tabulate
studentNames = []
for i in range(10):
item = input("Please enter a name: ")
if len(item) > 0 and item.isalpha():
studentNames.append(item)
#Something like this?
#print(tabulate(studentNames([[]], headers=['Team Leader', 'Students']))
My teacher didn't teach me tabulate but my research says I need to use it, but I think it's wrong and I don't know how to do it alphabetically. I'm sorry for the bad code, I'm embarrassed to even post it.
Any help would be appreciated. Thank you.
I don`t think it help when I solve the exercise for you. I would recommend you figure out how to add the input like the var table.
table = [("A", 20), ("Z", 21), ("C", 29), ("B", 24)]
sorted_table = sorted(table, key=lambda row: row[0])
leader = max(table, key=lambda row: row[1])
To print it you can simply iterate over the rows and print something like this:
print("{0} | {1}".format(row[0], row[1]))
My complete solution is this I would recommend you only use it if you are stuck again.
table = []
for i in range(10):
name = input("Please enter a name: ")
age = input("Enter the age: ")
if len(name) > 0 and name.isalpha():
table.append((name, age))
sorted_table = sorted(table, key=lambda row: row[0])
leader = max(table, key=lambda row: row[1])
print("{0:<12} | {1:<4}".format("Names", "Age"))
print("-" * 19)
for row in sorted_table:
print("{0:<12} | {1:<4}".format(row[0], row[1]))
print("Team Leader is: {0}".format(leader[0]))
Right... This is 90% of the Code... Considering it's your homework, you'll only need to find a quick way to add "Oldest Student" to the end of the Oldest Student which I'm sure you'll do pretty quick. I tried making it easy to read so you can learn. Good Luck!
# Python-3 (Change it slightly to make it usable for Python-2)
# Create an empty List to store input data...
studentDataList = []
# Little Extra to Spice up the Program...
numberOfStudents = int(input("Please Enter the Number of Students you Wish to Enter Data for: "))
studentCount = 1
# Create a Function for requesting data...
def getStudentData():
# Use variables outside this function
global studentCount
# Get Data and Verify
studentNameData = input("Enter Student (" + str(studentCount) + ") Name: ")
if len(studentNameData) != 0 and studentNameData.isalpha() == True:
studentAgeData = int(input("Enter Student (" + str(studentCount) + ") Age: "))
if studentAgeData != 0:
studentDataList.append(studentNameData + " " + str(studentAgeData))
studentCount += 1
else:
print("Invalid Entry")
getStudentData()
else:
print("Invalid Entry")
getStudentData()
# Run For Loop...
for num in range(numberOfStudents):
getStudentData()
# Sort List...
studentDataList.sort()
# Finally Print Table...
for item in studentDataList:
print(item)
So I'm having this problem in which my code is inconsistently failing at random times, this has been answered before:(Python 3.7.3 Inconsistent code for song guessing code, stops working at random times now I have had to add a leaderboard to this song guessing game I am doing. I randomly choose a number of which is used to find the artist and song. If right, it will remove the song and artist to prevent dupes and carry on. Here is the code:
loop = 10
attempts = 0
ArtCount = len(artist)
for x in range (ArtCount):
print(ArtCount)
randNum = int(random.randint(0, ArtCount - 1))
randArt = artist[randNum]
ArtInd = artist.index(randArt)# catches element position
songSel = songs[randNum]
print (randNum)
print ("The artist is " + randArt)
time.sleep(0.5)
songie = songSel
print( "The songs first letter be " + songSel[0])
time.sleep(0.5)
print("")
question = input("What song do you believe it to be? ")
if question == (songSel):
songs.remove(songSel)
artist.remove(randArt)
print ("Correct")
print ("Next Question")
if attempts ==0:
points = points + 5
print("+5 Points")
print("")
if question != (songSel):
loop = loop + 1
attempts = attempts + 1
print("")
print("Wrong,", attempts, "questions wrong, careful!")
print("")
time.sleep(0.5)
if attempts == 5:
break
print("GAME OVER")
Pardon my mess, I'm just starting off in making large code, will clean up when finished. I've had the additional problem of having the count controlled loop as 10 (the amount of questions) then having to go pas the loop when you get a question wrong, I've tried having it loop by the amount of songs in the list and I've also tried making a variable that +1 when you get it wrong so you have space to answer but that doesn't work either. After implementing the leaderboard it now doesn't remove any songs (I was messing with the indentation to make the leaderboard print every time.) The error I randomly get is;
randArt = artist[randNum]
IndexError: list index out of range
I'm never sure why this is the code that is the problem, I'm not even sure if it's necessary.
Please, don't use
randNum = int(random.randint(0, ArtCount - 1))
You may easily get a random artist by using:
randArt = random.choice(artist)
The problem is your code had modify the artist array length when you remove item on true answer. You need to get the right artist count after you change.
for x in range (ArtCount):
print(ArtCount)
count = len(artist) # get the new length here
randNum = int(random.randint(0, count - 1)) # use the new length here instead of your old ArtCount
I have a homework task to basically create a supermarket checkout program. It has to ask the user how many items they are, they then put in the name and cost of the item. This bit I've worked out fine, however I'm having trouble adding the total together.
The final line of code doesn't add the prices together, it just lists them.
Code so far
print "Welcome to the checkout! How many items will you be purchasing?"
number = int (input ())
grocerylist = []
costs = []
for i in range(number):
groceryitem = raw_input ("Please enter the name of product %s:" % (i+1))
grocerylist.append(groceryitem)
itemcost = raw_input ("How much does %s cost?" % groceryitem)
costs.append(itemcost)
print ("The total cost of your items is " + str(costs))
This is for a homework task for an SKE I'm doing however I'm stumped for some reason!
The expected output is that at the end of the program, it will display a total costs of items added into the program with a £ sign.
You have to loop through list to sum the total:
...
total = 0
for i in costs:
total += int(i)
print ("The total cost of your items is " + str(total)) # remove brackets if it is python 2
Alternative (For python 3):
print("Welcome to the checkout! How many items will you be purchasing?")
number = int (input ())
grocerylist = []
costs = 0 # <<
for i in range(number):
groceryitem = input ("Please enter the name of product %s:" % (i+1))
grocerylist.append(groceryitem)
itemcost = input ("How much does %s cost?" % groceryitem)
costs += int(itemcost) # <<
print ("The total cost of your items is " + str(costs))
Output:
Welcome to the checkout! How many items will you be purchasing?
2
Please enter the name of product 1:Item1
How much does Item1 cost?5
Please enter the name of product 2:Item2
How much does Item2 cost?5
The total cost of your items is 10
You need to declare your costs as int and sum them:
print("Welcome to the checkout! How many items will you be purchasing?")
number = int(input ())
grocerylist = []
costs = []
for i in range(number):
groceryitem = input("Please enter the name of product %s:" % (i+1))
grocerylist.append(groceryitem)
itemcost = input("How much does %s cost?" % groceryitem)
costs.append(int(itemcost))
print ("The total cost of your items is " + str(sum(costs)))
There also seems to be a problem with raw_input. I changed it to input.
d={}
for x in range(5):
globals()['int%s' % x] = int(input("Enter the marks of the students: "))
a = int0 + int1 + int2 + int3 + int4
print ("The average marks are ", a/5)
I don't understand the use of dictionary, globals() and ['int%s' % x] in this code. I'm very new to Python, and programming in general, so it would be very much appreciated if someone could answer this in a very simple language.
Thank you so much.
Don't worry, that's the twisted and worst code to learn any language I saw... I mean, if you are learning the first principles don't look at it for too long right now. When you get more practice, review this. That's just an advice. Anyway, I will explain to you line by line:
d={}
'''
here declares a variable with name d, and saves an empty dictionary to it...
I don't know why, because it is never used
'''
for x in range(5):
globals()['int%s' % x] = int(input("Enter the marks of the students: "))
'''
this is a loop that will be repeated 5 times, globals() is a dictionary
of all the variables in the scope that are alive with in the program...
so, globals()['int%s' % x] is creating a new key-value,
for example {'int0': 4}. It is a way to dynamically create variables, so,
the x will have the values [0,1,2,3,4], that's why the variables
will have the names int0, int1, int2, int3, int4.
Finally, it ask to the user to type a number,
and this number will be stored in one of those variables,
then the maths:
'''
a = int0 + int1 + int2 + int3 + int4
'''sum all the inputs from the user'''
print ("The average marks are ", a/5)
#divide it by 5
A posible way to achieve the same, but a little more generalized:
total=0
numberOfMarks = 5
for x in range(numberOfMarks):
mark = input("Enter the marks of the students: ")
while(not mark or not mark.isdigit()):
print("please, enter a number value representin the mark")
mark = (input("Enter the marks of the students: "))
total += int(mark)
print ("The average marks are ", total/numberOfMarks)
I am trying to write a program that gets user information and adds it to a list and then I want to total how many user inputs there were, but I can't do it. I have tried running an accumulator, but I get TypeError: unsupported operand type(s) for +: 'int' and 'str'.
def main():
#total = 0
cel_list = []
another_celeb = 'y'
while another_celeb == 'y' or another_celeb == 'Y':
celeb = input('Enter a favorite celebrity: ')
cel_list.append(celeb)
print('Would you like to add another celebrity?')
another_celeb = input('y = yes, done = no: ')
print()
print('These are the celebrities you added to the list:')
for celeb in cel_list:
print(celeb)
#total = total + celeb
#print('The number of celebrities you have added is:', total)
main()
Here is the output as desired without the accumulator, but I still need to add the input together. I have commented out the accumulator.
Enter a favorite celebrity: Brad Pitt
Would you like to add another celebrity?
y = yes, done = no: y
Enter a favorite celebrity: Jennifer Anniston
Would you like to add another celebrity?
y = yes, done = no: done
These are the celebrities you added to the list:
Brad Pitt
Jennifer Anniston
>>>
Thanks in advance for any suggestions.
Total is an integer ( declared earlier on as )
total = 0
As the error code suggest, you are trying to join an integer with a string. That is not allowed. To get pass this error, you may :
## convert total from int to str
output = str(total) + celeb
print(" the number of celebrities you have added is', output)
or even better you can try using string formatting
##output = str(total) + celeb
## using string formatting instead
print(" the number of celebrities you have added is %s %s', % (total, celeb))
I hope this will work for you
Python is a dynamically typed language. So, when you type total = 0, the variable total becomes an integer i.e Python assigns a type to a variable depending on the value it contains.
You can check the type of any variable in python using type(variable_name).
len(object) returns integer value.
for celeb in cel_list:
print(celeb)
#end of for loop
total = 0
total = total + len(cel_list) # int + int
print('The number of celebrities you have added is:', total)
You can get the number of entries in a Python list by using the len() function. So, just use the following:
print('These are the celebrities you added to the list:')
for celeb in cel_list:
print(celeb)
total = len(cel_list)
print('The number of celebrities you have added is: ' + str(total))
Note the decreased indentation of the last two lines - you only need to run them once, after you've finished printing out the celeb's names.