Specific application of the while loop - python

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)

Related

How to add to a counter using decisions and input

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)

Average not calculating right in python3

This is a work in progress code. As you can tell, I am a complete beginner and been trying new things. I usually get an error and I try and fix that but here this one is not giving me any error. It's just that the answer to the average is a wrong number. Without any error, its hard for me to know what's wrong with the code. Any suggestion?
sum = 0.0
count = 0
ids = [ ]
scores = [ ]
ids = eval(input("Enter an id number:"))
if ids <= 0.0:
print("Can't be 0 or a negative number, please enter a number greater than 0")
exit(1)
scores = eval(input("Enter a score:"))
while ids >= 0.0:
ids = eval(input("Enter another id number (or 0 to quit):"))
if ids <= 0.0:
break
scores = eval(input("Enter another score:"))
sum = sum + scores
count = count + 1
avg = sum / count
for i in range(ids):
print(i)
print("The average of the scores is", avg)
There are several mistakes in your code.
First of all in python you must use right indentation.
Next you have declared ids = [ ] and scores = [ ] without any reason
Why do you use ids?
Instead of eval(input()), use int(input())
A simple code to calculate average:
scores = list(map(int, input('Enter Space Separated Elements : ').split()))
print('Average is ' + str(sum(scores) / len(scores)))
Explanation:
Learn about input here
Learn about input().split() here
Learn about map() here
As map returns a map object, we must convert it to a list
Learn about sum, len and other built-in functions here
Hope this helps!

python 2.7.5, getting multiple user input for loading more than 1 array/list, problems with looping

I'm doing a programming problem for school in which I need to get 3 student ages/ names, I got the prompt working correctly to load the 2 arrays but for some reason the loop doesn't exit? Here is my code so far. I've been having trouble with arrays/list so please elaborate on your answer and I appreciate the reply.
Here is the code:
#the sample input was:
#joe 35, bill 25, mary 50
g = 0 #index for age
n = 0 #index for name
while g <= 3 and n <= 3: #1st loop to get 3 names/ ages
st_names = [0] * 3
st_age = [0] * 3
g = g + 1
n = n + 1
for n in range(0,3): #loop used in our book for loading arrays
st_names[n] = raw_input("Enter Student name")
st_age[g] = int(raw_input("Enter student age "))
g = g + 1 #I'm not sure where to increment
n = n + 1
#the loop goes on forever, my goal was to get the student age/ name one after another,
#for example enter name, then age, 3 times then move on.
Use just one for:
g = 0 # index for age
n = 0 # index for name
st_names = [0] * 3
st_age = [0] * 3
for n in range(0, 3): # loop used in our book for loading arrays
st_names[n] = raw_input("Enter Student name")
st_age[n] = int(raw_input("Enter student age ")) # Change g to n, because that's the variable increment in the loop
print st_names
print st_age

Python 2.7.5, display count of array average, proper syntax and looping with empty space?

trying to display the count of how many values in an array are above a calculated average, when I run my code for some reason it skips the counter loop for counting the amount of student ages above the average: I load the array with 3 age values 35,25, and 50 and want to display the count of how many are above the average but it skips this? Please assist,
Also if I want to exit the loop and not put anything on the else in a if/else, what can you put if you want empty space on the else so nothing changes? Here is my code so far:
st_age = [0] * 3
for g in range(0,3):
st_age[g] = int(input("Enter student age "))
g = 0
sum = 0
count = 1
count2 = 0
while g < len(st_age):
sum = sum + st_age[g]
g += 1
average = sum / len(st_age) #the average calc.
print "the average is:", average
#starting counter loop here:
g = 0
while g < len(st_age):
if st_age[g] > average:
count = count + 1
else: count = count + 1 # I don't know what to put here, it skips the whole thing
print "the number above the average is:", count
Well if you are starter you should watch not to use function names as variables:
age = [3,14,55]
sum_age = 0
count = 1
count2 = 0
g = 0
while g < len(age):
sum_age += age[g]
g += 1
average = sum_age / len(age) #the average calc.
print "The average is:", average
g = 0
while g < len(age):
if age[g] > average:
count = count + 1
g += 1
print "The number above the average is:", count
You are not obliged to put an else block. Just add 1 to count if the list element satisfies your condition, and don't forget to increment g in every case, because you are actually not traversing the list but always referring to its first element.
My proposition:
for age in st_age: # examine all items in st_age one by one
if age > average:
count += 1
print "the number above the average is:", count
To sum all list elements, you can use built-in sum() function.
You cycle by g, but you never change g in the cycle. In other words, g is always equal to 0 and the while cycle never ends.
You can use list comprehensions to write this much easier. For example:
print len(age for age in st_age if age > average)
"Also if I want to exit the loop and not put anything on the else in a if/else, what can you put if you want empty space on the else so nothing changes?"
you can write
pass
to do nothing in else part.
possible solution is :
st_age = [0] * 3
for g in range(0,3):
st_age[g] = int(input("Enter student age "))
average = sum(st_age)/len(st_age)
print "the number above the average is:", sum([1 for eachAge in st_age if eachAge>average])

Writing python code to calculate a Geometric progression

Im new to programming and python. I need help with coding a geometric progression thats supposed to calculate the progression 1,2,4,8,16... Heres what I have so far:
def work_calc (days_worked, n):
temp=int(1)
if days_worked<2:
print (1)
else:
while temp <= days_worked:
pay1 = (temp**2)
pay = int(0)
pay += pay1
temp +=1
print ('your pay for ',temp-1,'is', pay1)
main()
Right now it gives me this output: 1, 4, 9, 16, 25
i need : 1,2,4,8,16,32...
im writing code that basically should do this:
Example:
Enter a number: 5
your value 1 is: 1
your value 2 is : 2
your value 3 is : 4
your value 4 is : 8
your value 5 is : 16
your total is: 31
Thanks in advance for your help and guidance!
P.S: Im like a dumb blonde sometimes(mostly) when it comes to programming, so thanks for your patience..
As I said, looks like you need powers of 2:
def work_calc (days_worked, n):
for temp in range(days_worked):
print ('your pay for ', temp + 1, 'is', 2 ** temp)
if you want to print strings (not tuples as you're doing now):
def work_calc (days_worked):
for temp in range(days_worked):
print 'your pay for {} is {}'.format(temp + 1, 2 ** temp)
>>> work_calc(5)
your pay for 1 is 1
your pay for 2 is 2
your pay for 3 is 4
your pay for 4 is 8
your pay for 5 is 16
Just to note - your code is calculating squares of temp, not powers of 2 that's why is not working
I understand this is probably overkill for what you are looking to do and you've been given great advice in the other answers in how to solve your problem but to introduce some other features of python here are some other approaches:
List comprehension:
def work_calc(days):
powers_of_two = [2**x for x in range(days)]
for i, n in enumerate(powers_of_two):
print('your pay for {} is {}'.format(i+1,n))
print('your total is {}'.format(sum(powers_of_two)))
This is compact and neat but would hold the whole list of 2^n in memory, for small n this is not a problem but for large could be expensive. Generator expressions are very similar to list comprehensions but defer calculation until iterated over.
def work_calc(days):
powers_of_two = (2**x for x in range(days))
total = 0
for i, n in enumerate(powers_of_two):
total += n
print('your pay for {} is {}'.format(i+1,n))
print('your total is {}'.format(total))
Had to move the total to a rolling calculation and it still calculates 2**n each time, a generator function would avoid power calculation:
import itertools
def powers_of_two():
n = 1
while True:
yield n
n *= 2
def work_calc(days):
total = 0
for i, n in enumerate(itertools.islice(powers_of_two(), days)):
total += n
print('your pay for {} is {}'.format(i+1,n))
print('your total is {}'.format(total))
As I said overkill, but hopefully introduces some of the other features of python.
Is this a homework question? (insufficient rep to comment)
In the sequence 1,2,4,8,16,32 each term is double the previous term.
So, you can keep a record of the previous term and double it to get the next one.
As others have mentioned, this is the same as as calculating 2^n (not, as I previously stated, n^2) , where n is the number of terms.
print ('your pay for 1 is' 1)
prevpay = 1
while temp <= days_worked:
pay1 = prevpay*2
pay = int(0)
pay += pay1
temp +=1
prevpay = pay1
print ('your pay for ',temp-1,'is', pay1)
That is all too complicated. Try always to keep things as simple as possible and especially, keep your code readable:
def main():
i = int(input("how many times should I double the value? "))
j = int(input("which value do you want to be doubled? "))
double_value(i,j)
def double_value(times,value):
for i in range(times):
i += 1
value = value + value
print(f"{i} --- {value:,}")
main()
Hope I could help.

Categories