how do i get the min max to work? - python

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.

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

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

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