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
Related
The homework question is: "Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total
and average of the input values (not counting zeros). Your program ends with the
input 0. Display the average as a floating-point number."
positive = 0
negative = 0
total = 0
count = 0
number = eval(input("Enter an integer, the input ends if it is 0:"))
while number != 0:
total += number
count += 1
if number > 0:
positive += 1
elif number < 0:
negative += 1
else:
break
average = total/count
print("The number of positives is", positive)
print("The number of negatives is", negative)
print("The total is", total)
print("The average is", average)
After a number is inputted, the program does not output anything else.
Write a program that reads an unspecified number of integers
That implies that you have to repeatedly take number inputs from the users, but using input() would only really input a single number at a time.
So you should input your number inside the while-loop, example:
while True:
number = int(input("Enter an integer, the input ends if it is 0:"))
total += number
count += 1
if number > 0:
positive += 1
elif number < 0:
negative += 1
elif number == 0:
break
You need to continue prompting for numbers until a zero is entered. An easy way to do this is to put your numbers into a list, which you can then compute the different stats from at the end:
numbers = []
while not numbers or numbers[-1] != 0:
numbers.append(int(input("Enter an integer, the input ends if it is 0: ")))
numbers.pop() # discard the 0
print("The number of positives is", sum(n > 0 for n in numbers))
print("The number of negatives is", sum(n < 0 for n in numbers))
print("The total is", sum(numbers))
print("The average is", sum(numbers) / len(numbers))
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)
I'm trying to figure out the 2nd half of this question using python 3 but can't seem to figure it out. The first half of the code that I have is the following below...
A = [1,2,3,4]
print(average(A))
2.5
num = int(input('How many numbers: '))
total_sum = 0
for n in range(num):
numbers = float(input('Enter number : '))
total_sum += numbers
avg = total_sum/num
print('Average of ', num, ' numbers is :', avg)
number = int(input("Enter number: "))
if number < 2.5:
print("Your number is smaller than 2.5")
else:
print("Your number is greater than 2.5")
Save the numbers in list. Sort the list and check the number which is equivalent to or greater than an average number. U can then easily find the count of numbers less than and greater than avarage number.
This program is designed to count an unspecified amount of integers,
determines how many negative and positive values have been read,
and computes the average and total of the input values.
If the user inputs a 0, the program will end. Every time I enter a 0, I get an error stating "division by zero". The debugger says it is from the very last line.
I guess it has to to with the sum / count part. When I use negative numbers, it says the same thing, from the same line of code. Lastly, I am unsure how to display the text "You didn't enter any number". I tried doing the if else statement, but I don't think I'm doing that correctly.
data = eval(input("Enter an integer, the input ends if it is 0: "))
count = 0
sum = 0
negCount = 0
if data != 0:
while data > 0:
count = count + 1
sum = sum + data
data = eval(input("Enter an integer, the input ends if it is 0: "))
while data < 0:
negCount = count + 1
sum = sum + data
data = eval(input("Enter an integer, the input ends if it is 0: "))
while data != 0:
sum = sum + data
data = eval(input("Enter an integer, the input ends if it is 0: "))
break
else:
print("You didn't enter any number")
print("The number of positives is", count)
print("The number of negatives is", negCount)
print("The total is", sum)
print("The average is", sum / count)
output = []
while True:
data = int(input("Enter an integer, the input ends if it is 0: "))
if data == 0:
break
output.append(data)
positives = len([i for i in output if i > 0])
negatives = len(output) - positives
total = sum(output)
if len(output) != 0:
print("The number of positives is", positives)
print("The number of negatives is", negatives)
print("The total is", total)
print("The average is", total / len(output))
else:
print("You didn't enter any number")
If you enter 0, the if block is skipped (if data != 0). If the if block is skipped, count is 0. If count is 0, sum / count is undefined mathematically, and will raise a ZeroDivisionError.