Getting the minimum value from user input in a while loop - python

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

Related

How to debug my Python program, which sums positive numbers based on their evenness

I'm trying to write program that asking the user for positive numbers, if it is an odd number, the software sums all of the odd digits in the number, same for even numbers. After that the software asking non stop for numbers and does the same thing as before, till the user type 0/negative number.
After that the software should print the number with the maximal sum. Sometimes it works and sometimes not.
Code:
def sum_Digits(n):
sum = 0
if n % 2 == 0: #For even numbers
while n>0:
if (n%10)%2 == 0:
sum += n%10
n = n//10
else:
n = n//10
print("sum: " , sum)
return sum
elif n % 2 != 0 : #For odd numbers
while n>0:
if (n%10)%2 != 0:
sum += n%10
n = n//10
else:
n = n//10
print("sum: " , sum)
return sum
def read_Numbers(N):
maX = 0
while N > 0: #while askNum Positive continue summing
suM = sum_Digits(N)
if suM > maX:
maX = N
N = int(input("Please eneter a Natural number: "))
if N <= 0:
return maX
def main():
num = int(input("Please enter a Natural number: ")) #asking the user to enter number
sum_Digits(num)
askNum = int(input("Please eneter a Natural number: "))
maxSum = read_Numbers(askNum)
print("Number with maximal sum: " , maxSum)
main()
Bug:
if user enter a negative number it will continue the loop and print the last entered number
because the program doesn't check for negative numbers
Fix:
I have added a condition if N <= 0:
return maX
this will return the last entered positive number
Bug:
sum_Digits(num)
I have removed this line because it is not needed
because we already call the function sum_Digits in the main function

Program that separately adds positive and negative inputs and displays the two sums

I'm trying to solve this hw problem:
Write a program that allows a user to keep inputting numbers until the number zero is entered. The program should keep track of two separate sums: The sum of all positive numbers entered and the sum of all negative numbers entered. Once the loop ends the program should display the two sums.
This is what I have so far:
number = int(input("Please enter a number, press 0 to end"))
sum1 = 0
sum2 = 0
while number != 0:
number = int(input("Please enter a number, press 0 to end"))
if number > 0:
sum1 += number
else:
sum2 += number
print("positive sum is", sum1)
print("negative sum is", sum2)
the problem i'm facing is that number needs to be defined in order to start the while loop, and then for the loop to keep asking the question, i need to define number inside the loop too and that messes up the count because the first user input is used just to start the loop and is not counted.
How do i fix this?
You can simply initialize number to something other than 0, so the number isn't asked twice at the start of the program.
sum1 = 0
sum2 = 0
number = -1
while number != 0:
number = int(input("Please enter a number, press 0 to end"))
if number > 0:
sum1 += number
else:
sum2 += number
print("positive sum is", sum1)
print("negative sum is", sum2)
Try doing this. You can delete the sample_input lines and uncomment your original line taking input from stdin:
sample_input = iter([3, -3, 2, -2, 1, -10, 0])
sum1 = 0
sum2 = 0
number = 999
while number != 0:
number = next(sample_input)
#number = int(input("Please enter a number, press 0 to end"))
if number > 0:
sum1 += number
else:
sum2 += number
print("positive sum is", sum1)
print("negative sum is", sum2)
Sample output:
positive sum is 6
negative sum is -15
Use the walrus:
sum1 = 0
sum2 = 0
while number := int(input("Please enter a number, press 0 to end")):
if number > 0:
sum1 += number
else:
sum2 += number
print("positive sum is", sum1)
print("negative sum is", sum2)
And I'd suggest sum_pos and sum_neg as better more meaningful variable names.
Don't use the number test in the while condition. Check for it being 0 after getting the input and break out of the loop.
while True:
number = int(input("Please enter a number, press 0 to end"))
if number == 0:
break
elif number > 0:
sum1 += number
else:
sum2 += number
I prefer this style because it doesn't require you to initialize the variable to a special value. Also, it allows the end value to be something that wouldn't be useful in the rest of the computation.

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

How can I get the first and second largest input without using list?

How can I get the first and second largest input without using list?
li = []
while True:
number = int(input("Please enter a number (Enter 0 to finish) : "))
if number == 0:
break
else :
li.append(number)
print("The Largest number is ",max(li))
li.remove(max(li))
print("The Second Largest number is ",max(li))
I want to get the largest and the second largest number without using Python list. Also I want the number of times largest number is input.
max, secondmax, temp = -1
numOfMax = 1
while True:
number = int(input("Please enter a number (Enter 0 to finish) : "))
if number == 0:
break
temp = max
if number == max:
numOfMax += 1
elif number > max:
max = number
elif secondmax <= number <= max:
secondmax = number
if secondmax < temp < max:
secondmax = temp
print("the largest number is {}".format(max))
if secondmax != -1:
print("The second largest number is {}".format(secondmax))
else:
print("There isn't a second largest number")
print("The largest number is inputted {} times".format(numOfMax))
This one works fine. Let me know if it hits to any bug
first,second=0,0
while True:
number=int(input('Please enter a number (Enter 0 to finish) : '))
if number ==0:
break
if number> first:
second = first
first=number
elif number> second:
second= number
print(f'The Largest number is {first} \nThe Second Largest number is {second} \n')

My program keeps getting an error "division by zero"

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.

Categories