My program keeps getting an error "division by zero" - python

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.

Related

I have just started coding and am stuck solving this python problem

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

Why does my loop end after the input is entered?

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))

Getting the minimum value from user input in a while loop

I am writing a Python program that continuously asks a user for a number from 1 to 100, then once the user inputs the number 0, the program print out the smallest number and largest number provided, as well as the average of all the numbers.
My only problem: I keep getting 0 as the smallest value of the input when I want to exclude 0.
I have already tried doing the following:
count = 0
total = 0
number = 1
smallest = 0
largest = 0
while number != 0:
number = int(input("Please input a value from 1 to 100: "))
if number < 0 or number > 100:
print("Why you give me value outside of range :(\n")
count -= 1
continue
count += 1
total = total + number
if number > largest:
largest = number
if number == 0:
count -= 1
average = total / count
if number < smallest:
smallest = number
print("The results are: ")
print('Smallest: {}'.format(smallest))
print('Largest: {}'.format(largest))
print('Average: {}'.format(average))
print("\nThank you!")
You need to track both the largest and the smallest as the numbers are being input.
Also I have checked for the out of range numbers before any processing takes place:
count = 0
total = 0
number = 0
smallest = 101 # starts bigger than any input number
largest = 0 # starts smaller than any input number
while True:
number = int(input("Please input a value from 1 to 100: "))
if number == 0:
break
if number < 0 or number > 100:
print("Why you give me value outside of range :(\n")
continue
count += 1
total = total + number
if number > largest:
largest = number
if number < smallest:
smallest = number
if number == 0:
average = total / count
print("The results are: ")
print('Smallest: {}'.format(smallest))
print('Largest: {}'.format(largest))
print('Average: {}'.format(average))
print("\nThank you!")
Just add smallest = 101 in the beginning, and
if number < smallest:
smallest = number
to your while block, and remove the same code in the end.
Also, your count is off, you should just remove the two decrements count -= 1 to fix that.
You can also remove the if number == 0:, since you already have while number != 0: in the while condition, so you know it is zero.
Here is another version, this time using a list to hold the valid numbers:
numbers = []
while True:
number = int(input("Please input a value from 1 to 100: "))
if number == 0:
break
if number < 0 or number > 100:
print("Why you give me value outside of range :(\n")
continue
numbers.append(number)
if numbers:
average = sum(numbers) / len(numbers)
print("The results are: ")
print('Smallest: {}'.format(min(numbers)))
print('Largest: {}'.format(max(numbers)))
print('Average: {}'.format(average))
print("\nThank you!")

Calculating Running Total with a Validation Loop in python

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)

how do i get the min max to work?

this is what I have so far but max comes back as 1 and min comes back as zero no matter what the user inputs. Everything else works and calculates properly. please help, not sure what else to try
num=input("How many numbers would you like to enter?")
num_int=int(num)
sum=0
count_even=0
count_odd=0
num_pos=0
num_neg=0
if num_int==0:
print("You requested no numbers so there are no results reported")
elif num_int<0:
print("You entered a negative number, so the program terminates")
else:
for n in range(num_int):
integer=input("Enter an integer number")
integer_int=int(integer)
sum+=integer_int
avg=sum/num_int
if integer_int%2==0:
count_even=count_even+1
else:
count_odd=count_odd+1
if integer_int>=0:
num_pos=num_pos+1
else:
num_neg=num_neg+1
for i in range(num_int):
maximum=max(integer)
minimum=min(integer)
print("Number of integers entered:",num_int)
print("Sum of those integers is:",sum)
print("Average of those integers is:",avg)
print("Number of evens is:",count_even)
print("Number of odds is:",count_odd)
print("Number of negatives is:",num_neg)
print("Number of positives is:",num_pos)
print("Maximum number is:",maximum)
print("Minimum number is:",minimum)
You should add the inputs to a list, and then take the max and min of that list.
So, it'll look like:
numbers = []
# parse num_int
for n in range(num_int):
integer_int = # parse integer from input
numbers.append(integer_int)
# do your calculations for even, odd, pos, and neg
maximum = max(numbers)
minimum = min(numbers)
# print stuff
The argument passed into max and min should be a list.
just keep track of the highest and lowest with mn and mx variables. also don't use sum as a variable name:
num = input("How many numbers would you like to enter?")
num_int = int(num)
sm = 0 # don't use sum as a variable name
count_even = 0
count_odd = 0
num_pos = 0
num_neg = 0
mn = None
mx = None
if num_int == 0:
print("You requested no numbers so there are no results reported")
elif num_int < 0:
print("You entered a negative number, so the program terminates")
else:
for n in range(num_int):
integer = input("Enter an integer number")
integer_int = int(integer)
# if it is the first number or this number is higher than the highest so far
if integer_int is None or integer_int> mx:
mx = integer_int
# if it is the first number or this number is lower than the lowest so far
if mn is None or integer_int < mn:
mn = integer_int
sm += integer_int
avg = sm / num_int
if integer_int % 2 == 0:
count_even += 1
else:
count_odd += 1
if integer_int >= 0:
num_pos += 1
else:
num_neg += 1
print("Number of integers entered:", num_int)
print("sum of those integers is:", sm)
print("Average of those integers is:", avg)
print("Number of evens is:", count_even)
print("Number of odds is:", count_odd)
print("Number of negatives is:", num_neg)
print("Number of positives is:", num_pos)
print("Maximum number is:",mx)
print("Minimum number is:",mn)
Using a list and sum the correct way can shorten your code a lot:
num = input("How many numbers would you like to enter?")
num_int = int(num)
if num_int == 0:
print("You requested no numbers so there are no results reported")
elif num_int < 0:
print("You entered a negative number, so the program terminates")
else:
ints = [int(input("Enter an integer number")) for _ in range(num_int)]
sm = sum(ints)
ln = len(ints)
print("Number of integers entered:", ln)
print("sum of those integers is:", sm)
print("Average of those integers is:", sm / ln)
print("Number of evens is:", sum(1 for x in ints if not x % 2))
print("Number of odds is:", sum(1 for x in ints if x % 2))
print("Number of negatives is:", sum(x < 0 for x in ints))
print("Number of positives is:", sum(x >=0 for x in ints))
print("Maximum number is:",max(ints))
print("Minimum number is:",min(ints))
The reason it is not working is because you are not storing any of the integers entered. Every time the user enters a new integer, your code forgets the last one entered and works with the new number entered.
sum+=iteger_int
is only adding up the values, and not storing them as individual values. As stated above, using a list is probably the best way to store all of the values entered by the user.

Categories