I'm a newbie of python and I'm trying to practice some exercises, however I'm stuck with the line "total = 0" in this code. Actually I don't really understand why this value is initialized to 0.
Could anyone please explain it for me ?
def main():
print("This program allows you to total up some numbers")
print()
n = int(input("How many numbers do you have? "))
total = 0
for i in range(n):
num = float(input("Enter a number: "))
total = total + num
print()
print("The sum of the numbers is:", total)
main()
Remove that line and you see you will get an error:
NameError: name 'total' is not defined
This is because both total and num must be initialised before you can use them in total = total + num
You initialise it before the for loop otherwise it would be reset to 0 each time.
Related
Write a program that always asks the user to enter a number. When the user enters the negative number -1, the program should stop requesting the user to enter a number. The program must then calculate the average of the numbers entered excluding the -1.
This is what I have come up with so far
num = int(input("How many number's are there?"))
total_sum = 0
avg = total_sum / num
for n in range (num):
number = float(input("Enter a number"))
while number <0:
print = ("Average is", avg)
number >0
print(number)
total_sum += number
avg = total_sum / num
print = ("Average is", avg)
I need it to stop at -1 one and still give an average of the numbers listed.
Easy.
emp = []
while True:
ques = int(input("Enter a number: "))
if ques != -1:
emp.append(ques)
continue # continue makes the code go back to beginning of the while loop
else:
if len(emp) != 0:
avg = sum(emp) / len(emp) # average is the sum of all elements in the list divided by the number of elements in said list
print(f"Average of all numbers entered is {avg}")
break
else:
print("Give me at least one number that's not -1")
continue # emp is empty we need at least one number to calculate the average so we go back to the beginning of the loop
I need to create something that can multiply values no matter how many values there are. My idea is to use a list and then get the sum of the list with the sum function or get the first value of the list and set it as the total and then multiply the rest of the list by that total. Does anyone have a way to do it?
Here was my original idea:
total = 0
while True:
number = float(input("Enter a number and I’ll keep multiplying until you enter the number 1: "))
if number == 1:
break
else:
total *= number
print(f"The total is: {total}")
however as you may have guessed it just automatically multiplies it to 0 which equals zero. I would also like the code to work for subtraction and division (Already got Addition working)
thanks!
Thanks to the comments I worked out that the way to do it is by changing the beginning total to a 1 when fixed it is this:
total = 1
while True:
number = float(input("Enter a number and I’ll keep multiplying until you enter the number 1: "))
if number == 1:
break
else:
total *= number
print(f"The total is: {total}")
Since you are multiplying, you must start with 1 cause anything multiplied by 0 is 0. And idk why you need sum()
total = 1
while True:
number = float(input("Enter a number and I’ll keep multiplying until you enter the number 1: "))
if number == 1:
print(f"The total is: {total}")
break
else:
total *= number
I am new to python and trying to calculate a running total while validating the user input. If the user inputs invalid data I am showing an error and asking the user to input the correct data. My issue is I am unable to determine how to calculate only the valid data input from the user instead of all values.
# This program calculates the sum of a series
# of numbers entered by the user.
#Initialize an accumulator variable.
total = 0
#Request max value from user.
max_value = int(input("Enter a value for the maximum number: "))
#Request user to enter value between 1 and max value.
number = int(input("Enter a number between 1 and " + str(max_value) + " or negative number to end: "))
#Calculate total of user input values.
while number > 0:
total = total + number
number = int(input("Enter a number between 1 and " + str(max_value) + " or negative number to end:"))
#Display error if user entered invalid value.
if number == 0 or number > max_value:
print("Number entered is invalid!")
#Print sum of valid user input data.
else:
print("Sum of all valid numbers you entered:", total)
I can see that you have added too much unnecessary code and this is a very bad practice in python. I believe that this is the answer you are looking for:
f"" = is called a formatted string and
the while loop is unnecessary
so after that, you should import sys and use the exit function under a while loop and exit under a for loop
from sys import exit as exit1
while True:
max_value = int(input("Enter a value for the maximum number: "))
if max_value<0:
break
number = int(input(f"Enter a number between 1 and {max_value} or negative number to end: "))
total = max_value + number
if number == 0 or number > max_value:
print("Number entered is invalid!")
else:
print("Sum of all valid numbers you entered:", total)
So after reevaluating the code I wrote the first time I came up with the below and it functions as I would like. For a beginner that has only learned three chapters I think it is good. Current knowledge base is Input, Processing, Output, Decision Structures, Boolean Logic, and Repetition Structures.
# This program calculates the sum of a series
# of numbers entered by the user.
#Initialize an accumulator variable.
total = 0
# Request max value from user.
max_value = int(input("Enter a value for the maximum number: "))
#Request number between 1 and max value.
number = int(input("Enter a number between 1 and " + str(max_value) + " or negative
number to end: "))
#Validate the user input is between 1 and max value
# if so accumulate the number.
while number >= 0:
if number > 0 and number <= max_value:
total = total + number
elif number == 0 or number > max_value:
print("Number entered is invalid!")
number = int(input("Enter a number between 1 and " + str(max_value) + " or negative number to end: "))
#Once user select a negative number, print total.
else:
print("Sum of all valid numbers you entered:", total)
This is for one of my assignments.
Here is the question just for clarity on what I am trying to do. Please do not give me the answer, just if you could help me understand what I need to do.
Write a Python program that uses a WHILE loop. The program must prompt the user to enter an integer number. The value must be added to a total. The loop must continue until the total exceeds 45. After the loop, the average of the numbers must be calculated. The program must display each of the input values, as well as the sum of all values and the average value.
*** enhancement, replace the user prompt with a random number selector.
This is the current code I am using:
num = int(input('Enter as many integers as you want: '))
numList =num.split()
print('All entered numbers ', numList)
sum = 0
while num >= 45:
print('Sum of all numbers ', sum)
avg = sum / num
print('Average of all numbers ', avg)
This, of course, is not working, I have figured out how to do it with a for loop ( from the internet ) I just cannot seem to understand how to link the input function with the while loop.
You want to read numbers one at a time, until the sum exceeds 45.
total = 0
num_list = []
while total < 45:
num = int(input(...))
num_list.append(num)
total += num
# Now compute the average and report the sum and averages
To make sure the last number is not added to the list if that would put the total over 45,
total = 0
num_list = []
while True:
num = int(input(...))
new_total = total + num
if new_total > 45:
break
num_list.append(num)
total = new_total
The while loop should be used to get values from the user : While the total of the given values is lower than 45, ask the user for another value
numList = []
total = 0
while True:
num = int(input('Enter an integer: '))
if (total + num) > 45:
break
numList.append(num)
total = total + num
avg = total / len(numList)
print('Sum of all numbers ', total)
print('Average of all numbers ', avg)
This code needs to calculate an average to retrieve an integer between 0-100. Any suggestions would be great.
Prompt the user for the number of points they expect to receive
for engagement at the end of class. This number should not be
adjusted by the program (engagement is a total of 302).
Calculate the final based on an average of the quiz scores to
date.
Prompt the user for the various scores. -1 = no more scores, 0 -
zero for that assignment. Keep looping for the grade until the user
enters a -1.
Here is my code, I definitely do not understand lists very well. Probably clearly.
list1 = []
g=1
totalnum = 0
total=0
tot = int(input("Total Points? :"))
list1.append(tot)
eng = int(input("How many points do you expect to get in engangement, out of 302?: "))
list1.append(eng)
while g !=0:
num = int(input("Please enter a grade"))
if num == -1:
break
totalnum+=1
total= total+num
list1.append(num)
average= tot/eng+num
counter=0
while counter<totalnum:
print(list1[counter])
counter+=1
print("your average is",average)
If you can use built ins you can just use sum(your_list) / len(your_list) for the average.
If len(your_list) is zero, you will get a ZeroDivisionError, because you just broke math.
It's not clear to me that this is what you're trying to accomplish, but if you just want an average of all the values in the list, you can just do:
average = sum(list)/len(list)
This would return an integer, if you don't want it rounded you could do:
average = sum(list)/float(len(list))
As an aside, you have this:
counter=0
while counter<totalnum:
print(list1[counter])
counter+=1
Which could be made simpler, like:
for e in list1:
print e
Python will do the counting for you. :)
list1 = []
g=1
totalnum = 0
total=0
tot = int(input("Total Points? :"))
eng = int(input("How many points do you expect to get in engangement, out of 302?: "))
list1.append(eng)
while g !=0:
num = int(input("Please enter a grade"))
if num == -1:
break
else:
list1.append(num)
totalnum+=1
total= (num+eng)/tot
print(len(list1))
average = (sum(list1)/tot)*100
counter=0
for e in list1:
print (e)
print("your average is",average)
This is more what I was looking for. Thanks to #Tommy, #SQLnoob, and #Slayer for the tips that I have implemented into the code.