How to add to a counter using decisions and input - python

I have tried for the past hour to make this program. The aim of the program is to record the preference of food for 15 people and count and display the total at the end. Each person can only choose 1 food. Here is where I'm stuck. None of this code seems to work(add to the counters). If anybody can help or send me the correct code it would be greatly appreciated:)
#Choices of food for the customers
meatplate_1 = 0
fishplate_2 = 0
vegetableplate_3 = 0
#Decision making as input data
for i in range (15):
num = int(input("What do you want for lunch?"))
if num == 1 :
meatplate + 1
print(meatplate_1)

As already mentioned by #0x5453 in comments, you should increment meatplate_1 variable.
And, If condition should come inside for loop, increment should be done by += operator.
You can refer below code.
#Choices of food for the customers
meatplate_1 = 0
fishplate_2 = 0
vegetableplate_3 = 0
#Decision making as input data
for i in range (15):
num = int(input("What do you want for lunch?"))
if num == 1 :
meatplate_1+=1
elif num==2:
fishplate_2+=1
elif num==3:
vegetableplate_3+=1
else:
pass
print(meatplate_1)

Related

Shadow name error and Local variable not used

self teaching myself how to code and starting with this book and a Udemy course.
have been working on this practice project for 2 days now and I keep running into "Local variable 'streaks' not used when I have the streak counter placed inside the htcheck function even though I'm Cleary defining the variable, I tried placing the streak variable outside of the function at the top of the code to declare as it a global value but that still doesn't work and then I get the "Shadow name" error.
what the code should be doing is flipping a coin 10000 times then checking for streaks of 6 then present the user with how many streaks of 6 occurred and a percent value of how often a streak of 6 was, I'm sure a lot of you have seen this question been asked before as it's from Al Sweigart's Automate The Boring Stuff with python 2nd edition <- I just cant find the answer to my specific error hence this post.
I just need help with figuring out why my variable ' streaks = 0 ' isn't working as shown below. and why it doesn't work as a global variable declared where I have heads tails and x. I would prefer a solution that keeps streaks inside the htcheck function but i'm open to any and all solutions.
Thank you in advance.
# Automate Python - Coin Flips Streaks
heads = []
tails = []
x = 0
#Flips a coin, then stores result into respective list
def coinflip():
y = random.randint(0, 1)
if y == 0:
heads.append('H')
tails.clear()
elif y == 1:
tails.append('T')
heads.clear()
#checks if list len is 6 then clears and adds +1 to streak
def htcheck():
streaks = 0
if len(heads) == 6:
streaks = streaks + 1
heads.clear()
elif len(tails) == 6:
tails.clear()
streaks = streaks + 1
while x < 10000:
x = x + 1
coinflip()
htcheck()
print('# Streaks of 6: ", streaks)
While you can use global variables for something like this, I generally prefer using return statements and tracking the variables separately for easier debugging and readability
Something like this is an option
# Automate Python - Coin Flips Streaks
heads = []
tails = []
num_streaks = 0
#here we eliminate the need for a counter variable x by using a for loop instead of a while loop below, instead creating a counter for our streaks
#Flips a coin, then stores result into respective list
def coinflip():
y = random.randint(0, 1)
if y == 0:
heads.append('H')
tails.clear()
elif y == 1:
tails.append('T')
heads.clear()
#checks if list len is 6 then clears and adds +1 to streak
def htcheck():
streaks = 0
if len(heads) == 6:
streaks = streaks + 1
heads.clear()
elif len(tails) == 6:
tails.clear()
streaks = streaks + 1
#here we return the local variable instead of trying to use the global scope
return streaks
#using a for instead of a while loop is a bit of a stylistic choice but can prevent problems arising from forgetting a `break` condition or messing up counter incrementation
for x in range(1000):
coinflip()
#here we add to the streak counter we declared in the outer scope by using the local variable returned from the function
num_streaks += htcheck()
print('# Streaks of 6: ', num_streaks)

Python loop not adding to list, therefore not providing an output

I am making a piece of code that generates bingo cards. It makes sure that there are going to be 5 numbers on each horizontal row and that each vertical column has the numbers between 1-9, 10-19, 20-29, 30-39, 40-49, 50-59, 60-69, 70-79, and 80-90. However the list values never has anything appended to it, so it can never get to the next loop. Here is the code:
def generate_nums(nums): #nums looks like this: [[],[],[]] - which is how it is inputed
for i in range(0, len(nums)):
while True:
values = []
Min = 1
Max = 9
counter = 0
for j in range(0, len(nums[i])):
value = random.randint(0, 1)
values.append(value)
if value == 1:
counter += 1
if counter == 5:
for item in values:
if item == 1:
nums[i].append(random.randint(Min, Max))
else:
nums[i].append(" ")
if Min == 1:
Min = 10
else:
Min += 10
if Max == 79:
Max = 90
else:
Max += 10
break
#Function call
if __name__ == "__main__":
nums = [[],[],[]]
print(generate_nums(nums))
Any help is appreciated, I am only looking to improve my knowledge as I am doing computer science GCSE and I love python and the challenges it presents, though I don't know what to do here.
Thanks!

The sentinel value isn't working and the program runs too early

So when I put in the values that I was given the program stops before it is supposed to which is at 123 as opposed to -1. I did replace{while grade_entered >=0 and grade_entered <= 100:} with {while grade_entered != '-1':} ,a sentinel value, but the program doesn't run if I do that. I also added continue as I thought it keeps the program running if I enter a number that isn't In the 0 - 100 range but that didn't help at all. My question is where am I supposed to add the sentinel value{while grade_entered != '-1':} in order for the program to end after I insert -1?
<You need to count how many passing grades are entered. Use a sentinel-controlled while loop that will ask the user to enter student grades until a value of -1 is entered. Use a counter variable to count all the grades that are passing grades, where 50 is the minimum passing grade. If there are any grades that are out of the valid range (0 through 100), present an error message to the user, and do not count that grade as passing (or valid). We also would like to see what percentage of the valid grades are passing.>
# 1st Test Case
# 45
# 90
# 70
# 87
# 123 That is not a valid test grade!
# 100 You have entered 4 passing grades.
# -1 80.0% of the valid grades are passing.
count = 0
total = 0
grade_entered = 0
print('Enter test scores to average. Enter -1 to Quit:')
while grade_entered >= 0 and grade_entered <= 100:
grade_entered = float(input(""))
if grade_entered >= 0 and grade_entered <= 100:
total += grade_entered
count += 1
continue
else:
print('This is not a valid grade!')
print("You have entered " + str(count) + " passing grades.")
average = total / count
print("{:.2f}% of the valid grades are passing".format(average))
This is the result that I get
Enter test scores to average. Enter -1 to Quit:
45
90
70
87
123
This is not a valid grade!
You have entered 4 passing grades.
73.00% of the valid grades are passing
it is important to do correct indentations when using python, your else clause is not part of the while loop anymore because it is too far left.
The whole thing should look somewhat like this:
grade_entered = float(input(""))
while grade_entered != -1:
if grade_entered >= 0 and grade_entered <= 100:
total += grade_entered
count += 1
#continue this is unnecesarry
else:
print('This is not a valid grade!')
grade_entered = float(input(""))

Specific application of the while loop

I wonder if you could help me with this practical exercise:
Make a Program that asks for the 2 grades of 2 students, calculate and store the average of each student in a list, print the number of students with an average greater than or equal to 7.0.
I managed to do it using the for loop, but I would like to use the while loop. I'm trying this code, but the list of averages is not coming out correctly. I appreciate any help.
notesStudents = []
listNotes = []
student = 1
notes = 1
average = 0
while student <= 2:
while notes <= 2:
notesStudents.append(float(input(f"What is the {notes}ª grade of the Student {student}?")))
notes += 1
notes = 1
student += 1
average += notesStudents[notes]
average = average / 3
listNotes.append(average)
print(listNotes)
The notes and studentNotes variables should be re-initialized within the loop, otherwise you just keep appending to the same list of studentNotes. Also, right now you just set average to the studentNodes[1] / 3, which is not correct. You should get the sum of all the notes and divide them by the proper number.
listNotes = []
student = 1
while student <= 2:
notes = 1
notesStudents = []
while notes <= 2:
notesStudents.append(float(input(f"What is the {notes}ª grade of the Student {student}?")))
notes += 1
average = sum(notesStudents) / len(notesStudents)
listNotes.append(average)
student += 1
print(listNotes)
This would however be much simpler and less verbose with for loops and maybe even a list comprehension:
listNotes = []
for student in range(1, 3):
notesStudents = [float(input(f"What is the {n}ª grade of the Student {student}? "))
for n in range(1, 3)]
average = sum(notesStudents) / len(notesStudents)
listNotes.append(average)
print(listNotes)

Take input from the keyboard using a loop till the time the user presses 0 and print their average value on the screen

What this is supposed to do is:
To ask the user for numbers using while loop until they enter 0
when 0 is pressed we need to print the average of the numbers entered so far.
(Kindly help)
import statistics as st
provided_numbers = []
while True:
number = int(input('Write a number'))
if number == 0:
break
else:
provided_numbers.append(number)
print(f'Typed numbers: {provided_numbers}')
print(f'The average of the provided numbers is {st.mean(provided_numbers)}')
Take each number and print the average so far and stop it when input is zero, right?
s = 0
count = 0
while True:
num = int(input('Write a number: '))
if num == 0:
break
s += num
count += 1
print("Average so far:",(s/count))
Could you add a piece of code you have tried or sample input and output too?

Categories