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)
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
print("Enter some number (9999 is for exit): ")
count = 0
sum = 0.0
number = 1
while number != 9999:
number = int(input("-> "))
sum = sum + number
count += 1
if count == 0:
print("Input some numbers")
else:
print("Average of the above numbers are: ", ((sum-9999) / (count-1)))
print("Sum of the above numbers is :", sum-9999)
'''
The average and sum can work properly but just don't know how to display the total entered numbers that the user input?
'''
Just use
print(number)
To print the user input.
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))
This is my Task:
Require the user to enter their name, with only a certain name being able to trigger the loop.
Print out the number of tries it took the user before inputting the correct number.
Add a conditional statement that will cause the user to exit the program without giving the average of the numbers entered if they enter a certain input
numbers = []
number = 0
count = 0
total = 0
name = 0
while number >= 0:
number = int(raw_input("Please enter any number: \n"))
if number == -1:
break
numbers.append(number)
avg = float(sum(numbers)) / len(numbers)
print "The average of the numbers you entered is " + str(avg) + "!"
while name >= 0:
name = int(raw_input("Please enter the number of characters your name contains: \n"))
count += 1
total += count
if name == 6:
break
tries = sum(total)
print tries
tries = sum(total)... sum takes an iterable whereas total is an int hence the error.
If total = [ ]
and you can append count values in total that would be fine.
so total.append(count)
would create list then you can use sum(total) on it
but here you can simply use print total or count both are same.
numbers = []
number = 0
count = 0
total = 0
name = 0
while number >= 0:
number = int(raw_input("Please enter any number: \n"))
if number == -1:
break
numbers.append(number)
avg = float(sum(numbers)) / len(numbers)
print "The average of the numbers you entered is " + str(avg) + "!"
while name >= 0:
name = int(raw_input("Please enter the number of characters your name contains: \n"))
count += 1
total += count
if name == 6:
break
tries = total
print tries
and you try to reduce your code.
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.