how to make a python program using "while" to print at 0? - python

My assignment is to make a program that prompts the user to input numbers to be categorized as even or odd. It will then add them together and count the amount of inputs of evens or odds. So far, I have that down, but I can't figure out how to get my program to run through the outputs when 0 is typed in.
Here's my code:
number = int(input("Input an integer (0 terminates the program): "))
zero = 0
count_odd = 0
count_even = 0
odd_sum = 0
even_sum = 0
sum = float(count_odd) + float(count_even)
while number >= 0:
if number%2 == 0:
count_even+=1
even_sum= even_sum + number
number = int(input("Input an integer (0 terminates the program): "))
elif number%2 != 0:
count_odd+=1
odd_sum = odd_sum + number
number = int(input("Input an integer (0 terminates the program): "))
elif number == zero:
print("Sum of odds: " +odd_sum)
print("Sum of evens: " + even_sum)
print("Odd count: " +count_odd)
print("Even count: " +count_even)
print("Total positive int count:" +sum)
else:
number = int(input("Input an integer (0 terminates the program): "))
I'm not even sure the ending is right at all. Especially not my attempt at creating a "zero."

Your current program does not work because 0 % 2 is also 0 , so it will go into the if block and it will never reach the elif number == zero: block.
You should move your elif to the top to become an if and move the if to elif , for your logic to work. and also, if you want to loop to break at 0 , you should add break statement in the number == zero block. Example -
while number >= 0:
if number == 0:
print("Sum of odds: ", odd_sum)
print("Sum of evens: ", even_sum)
print("Odd count: ", count_odd)
print("Even count: ", count_even)
print("Total positive int count:", even_sum + odd_sum)
break
elif number%2 == 0:
count_even+=1
even_sum= even_sum + number
number = int(input("Input an integer (0 terminates the program): "))
elif number%2 != 0:
count_odd+=1
odd_sum = odd_sum + number
number = int(input("Input an integer (0 terminates the program): "))
Other issues that I noticed in your program -
"Sum of odds: " +odd_sum would not work because you cannot add int and string like that, instead pass them as separate arguments to the print .
You do not need the else: part, as it would never reach there.

When you input "0", this condition is true as well:
if number%2 == 0:
So your program counts the "0" as a valid input (an even number).
Try comparing with zero first, then the rest of the ifs.
Also, you should use a "break" to end the program when "0" is inputted.
Try this version:
number = int(input("Input an integer (0 terminates the program): "))
zero = 0
count_odd = 0
count_even = 0
odd_sum = 0
even_sum = 0
sum = float(count_odd) + float(count_even)
while number >= 0:
if number == zero:
print("Sum of odds: ", odd_sum)
print("Sum of evens: ", even_sum)
print("Odd count: ", count_odd)
print("Even count: ", count_even)
print("Total positive int count:", sum)
break
elif number%2 == 0:
print "a"
count_even+=1
even_sum= even_sum + number
number = int(input("Input an integer (0 terminates the program): "))
elif number%2 != 0:
count_odd+=1
odd_sum = odd_sum + number
number = int(input("Input an integer (0 terminates the program): "))
else:
number = int(input("Input an integer (0 terminates the program): "))

I made some changes and addressed them with comments, the main problem was that you should have been checking for zero with the first conditional statement in your while loop.
# Setup your variables
# I removed the input line from here, since we only need to get input in the while loop
count_odd = 0
count_even = 0
odd_sum = 0
even_sum = 0
# Use a simple boolean flag to tell the while loop to keep going
keep_going = True
while keep_going == True:
# Grab the number from the user
number = int(input("Input an integer (0 terminates the program): "))
# IMPORTANT - Check for zero first
# If it is zero, set out flag to false, so we will exit the while loop
if number == 0:
keep_going = False
elif number % 2 == 0:
count_even += 1
even_sum += number
elif number % 2 != 0:
count_odd += 1
odd_sum += number
# Here we have exited the while loop
sum = float(count_odd) + float(count_even)
# Print everything here

To fully make your script function you'll need this:
import sys # allows the script to end after 0 properly
number = int(input("Input an integer (0 terminates the program): "))
zero = 0
count_odd = 0
count_even = 0
odd_sum = 0
even_sum = 0
summation = float(count_odd) + float(count_even) # don't use sum because it's already taken by python, and you can also remove it, see below why
while number >= 0:
if number%2 == 0 and number != 0:
count_even+=1
even_sum= even_sum + number
number = int(input("Input an integer (0 terminates the program): "))
elif number%2 != 0:
count_odd+=1
odd_sum = odd_sum + number
number = int(input("Input an integer (0 terminates the program): "))
elif number == 0: # pay attention to the concatenation of strings, not string and integer
print("Sum of odds: " + str(odd_sum))
print("Sum of evens: " + str(even_sum))
print("Odd count: " + str(count_odd))
print("Even count: " + str(count_even))
summation = float(count_odd) + float(count_even)
print("Total positive int count:" + str(summation)) # add everything up after it's been done NOT before
sys.exit() # to stop your infinite loop
else:
number = int(input("Input an integer (0 terminates the program): "))

Related

Intro to Python: How to ask the user if they want to repeat the for loop?

I need help figuring out how to ask the user if they would like to repeat the program. Any help is much appreciated. I am relatively new to Python and it would be great to receive some advice!
X = int(input("How many numbers would you like to enter? "))
Sum = 0
sumNeg = 0
sumPos = 0
for i in range(0,X,1):
number = float(input("Please enter number %i : " %(i+1) ))
# add every number to Sum
Sum = Sum + number # Sum += number
#only add negative numbers to sumNeg
if number < 0:
sumNeg += number # sumNeg = sumNeg + number
#only add positive numbers to sumPos
if number > 0:
sumPos += number # sumPos = sumPos + number
print ("------")
print ("The sum of all numbers = ", Sum)
print ("The sum of negative numbers = ", sumNeg)
print ("The sum of positive numbers = ", sumPos)
I'm not sure if I need to use a while loop, but how would I enter a (y/n) into my code because I am asking for an integer from the user in the beginning.
Ask the user for input at the end of the loop to continue or not. If the user doesn't want to continue, use a break statement to break out of the loop.
https://www.simplilearn.com/tutorials/python-tutorial/break-in-python#:~:text='Break'%20in%20Python%20is%20a,condition%20triggers%20the%20loop's%20termination.
Have an outer loop that comprises your whole processing.
It's an infinite loop.
You exit from this loop thanks to the break statement once the user has answered no.
In fact once he has answered everything else than Y or y. The user string is converted to lower() before comparison for more convenience.
while True:
X = int(input("How many numbers would you like to enter? "))
Sum = 0
sumNeg = 0
sumPos = 0
for i in range(0, X, 1):
number = float(input("Please enter number %i : " % (i + 1)))
# add every number to Sum
Sum = Sum + number # Sum += number
# only add negative numbers to sumNeg
if number < 0:
sumNeg += number # sumNeg = sumNeg + number
# only add positive numbers to sumPos
if number > 0:
sumPos += number # sumPos = sumPos + number
print("------")
print("The sum of all numbers = ", Sum)
print("The sum of negative numbers = ", sumNeg)
print("The sum of positive numbers = ", sumPos)
resp = input("Would you like to repeat the program ? (y/n)")
if resp.lower() != "y":
break
As an alternative to the while True loop.
You could declare at the top of the script a variable user_wants_to_play = True.
The while statement becomes while user_wants_to_play.
And set the variable to False when the user answers no.
The following program will keep on executing until user enter 0 to break the loop.
while True:
X = int(input("How many numbers would you like to enter? "))
Sum, sumNeg, sumPos = 0
for i in range(X):
number = float(input("Please enter number %i : " %(i+1) ))
Sum += number
if number < 0:
sumNeg += number
if number > 0:
sumPos += number
print ("------")
print ("The sum of all numbers = ", Sum)
print ("The sum of negative numbers = ", sumNeg)
print ("The sum of positive numbers = ", sumPos)
print ("------")
trigger = int(input("The close the program enter 0: "))
if trigger == 0:
break

Write an application that allows a user to enter any number of student test scores until the user enters 999

Write a python application that allows a user to enter any number of student test scores until the user enters 999. If the score entered is less than 0 or more than 100, display an appropriate message and do not use the score. After all the scores have been entered, display the number of scores entered and the arithmetic average.
I am having trouble breaking the loop when the score entered is less than 0 or more than 100.
The code I have is
total_sum = 0
count = 0
avg = 0
numbers = 0
while True:
num = input("Enter student test score: ")
if num == "999":
break
if num < "0":
break
print("Number is incorrect")
if num > "100":
break
print ("Number is incorrect")
total_sum += float(num)
count += 1
numbers = num
avg = total_sum / count
print("The average is:", avg)
print("There were " +str(count) + " numbers entered")
There are multiple issues with your code.
You want to compare numbers, not strings. Try using float(input(...))
break will break out of the loop in exactly the same way for numbers under 0, above 100, or for the "finished" token 999. That's not what you described that you want. Rather, for "incorrect numbers" just print the message, and don't add the numbers and counter...But no need to break the loop, amirite?
You've got an indentation problem for the < 100 case. Your print is missing an indentation.
No need to have avg = 0
numbers isn't used
Try something like -
total_sum = 0
count = 0
while True:
num = float(input("Enter student test score: "))
if num == 999:
break
elif num < 0 or num > 100:
print("Number is incorrect")
else:
total_sum += num
count += 1
avg = total_sum / count
print("The average is:", avg)
print("There were " +str(count) + " numbers entered")

Python program prompts user to enter number until they enter 0, then program adds even and odd integers [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed last month.
I'm taking a class in Python and our prof wants us to write a program that prompts the user to enter an integer repeatedly until they enter 0. Then, have the program ignore all negative numbers, if any, and display the number of even integers, the number of odd integers, the sum of the even integers, the sum of the odd numbers, and the number of positive integers.
I've been trying and trying to do this program in small parts. However, I always end up getting stuck. I've started over about 5 times now and I would really appreciate if someone were to point me in the right direction.
So far, I have this:
num_str = input("Input an integer (0 terminates):")
num_int=int(num_str)
even_count=0
odd_count=0
even_sum=0
odd_sum=0
while num_int !=0:
num_str = input("Input an integer (0 terminates):")
num_int=int(num_str)
for num_int in num_str:
if num_int%2 == 0:
even_count += 1
else:
odd_count +=1
print("")
print("Sum of odds:", odd_sum)
print("Sum of evens:", even_sum)
print("Even count:", even_count)
print("Odd count:", odd_count)
print("Total positive int count:")
I know it's not much and I'm missing a whole lot, but I just wrote what I know needs to be included so far. I keep getting stuck because the program keeps giving me errors. Any sort of help is very appreciated because I have really no idea where to start!
Your code has a few problems, but they're small:
1) You're asking for numbers before your main loop, so the first integer entered wouldn't be summed (lines 1 and 2)
2) It doesn't make sense for you to have a for loop like the one in your main loop. What you were doing is trying to check for each character in the string. Just not what you'd want.
3) To ignore negative numbers, just check if they're less than 0 and continue (break the loop) if they are.
4) You were using indentation with 3 spaces. It's probably your text editor's fault, so try to configure it to use 4 spaces instead, which is the standard in Python.
5) Convention says there should be a space around operators.
6) Positive integer count is just another simple counter.
All that revised, this is what your code should look like:
num_int = None
even_count = 0
odd_count = 0
even_sum = 0
odd_sum = 0
while num_int != 0:
num_str = input("Input an integer (0 terminates):")
num_int = int(num_str)
if num_int < 0:
continue # Continue the loop and go back to asking input
# If the loop reaches this point we know it's a positive number, so just add one
positive_count += 1
if num_int % 2 == 0:
even_count += 1
even_sum += num_int
else:
odd_count +=1
odd_sum += num_int
print("")
print("Sum of odds:", odd_sum)
print("Sum of evens:", even_sum)
print("Even count:", even_count)
print("Odd count:", odd_count)
print("Total positive int count:", positive_count)
You should declare a variable
total = 0
to count the number of integers the user has entered.
It's also more readable to have a
while True:
loop that breaks when the input is zero, instead of the loop you have.
Within the loop, you should
break
if the input is equal to 0,
continue
if the input is less than 1, increment even_count and add to even_sum if the input is even,
even_count += 1
even_sum += num
and increment the odd_count and odd_sum otherwise,
odd_count += 1
odd_sum += num
finally, you should increment the total:
total += 1
Also make sure to change the last line of your code to:
print("Total positive int count:", total)
to display the total
Your end result should look like this:
even_count = 0
odd_count = 0
even_sum = 0
odd_sum = 0
total = 0
while True:
num = int(input("Input an integer (0 terminates): "))
if num == 0:
break
if num < 1:
continue
if num % 2 == 0:
even_count += 1
even_sum += num
else:
odd_count += 1
odd_sum += num
total += 1
print("")
print("Sum of odds:", odd_sum)
print("Sum of evens:", even_sum)
print("Even count:", even_count)
print("Odd count:", odd_count)
print("Total positive int count:", total)
try this
userInput = None
oddSum = 0
oddCount = 0
evenSum = 0
evenCount = 0
while(userInput != 0):
userInput = int(input("Enter a number: "))
if(userInput > 0):
if(userInput % 2 == 0):
evenSum += userInput
evenCount += 1
elif(userInput % 2 != 0):
oddSum += userInput
oddCount += 1
print("even numbers: {} sum: {}".format(evenCount, evenSum))
print("odd numbers: {} sum: {}".format(oddCount, oddSum))
to ignore negative numbers, you could have them put it in agian, with an if loop like this
if (num_str>0):
num_str = input("That was not an even number, input an integer (0 terminates)")
Then to add them you would have to add the integer version of num_str to it like this
odd_sum += int(num_str)
here's some code for you to try
num_str = input("Input an integer (0 terminates):")
num_int=int(num_str)
even_count=0
odd_count=0
even_sum=0
odd_sum=0
total = even_count + odd_count
while num_int !=0:
num_str = input("Input an integer (0 terminates):")
num_int=int(num_str)
if num_int < 0:
num_str = input("Input an integer greater than 0.")
for num_int in num_str:
num_int = int(num_str)
if num_int % 2 == 0 and not num_int == 3 and not num_int == 0:
even_count += 1
even_sum = even_sum + num_int
elif not num_int == 0:
odd_count +=1
odd_sum = odd_sum + num_int
total = even_count + odd_count
print("")
print("Sum of odds:", odd_sum)
print("Sum of evens:", even_sum)
print("Even count:", even_count)
print("Odd count:", odd_count)
print("Total positive int count:", total)
val = []
inpt = None
evensm, oddsm = 0, 0
while inpt != 0:
inpt = int(input("Enter a number: "))
val.append(inpt)
for i in val:
if i % 2 == 0:
evensm += i
else:
oddsm += i
print("Sum of even integers is", evensm)
print("Sum of odd integers is", oddsm)
Or if you don't prefer using lists:
oddsm = 0
evensm = 0
while 1:
inpt = int(input("Enter a number: "))
if inpt == 0:
break
elif inpt % 2 == 0:
evensm += inpt
else:
oddsm += inpt
print("Sum of odd integers is", oddsm)
print("Sum of even integers is", evensm)
Write a Python program to take input of positive numbers, with an appropriate prompt, from the user until the user enters a zero. Find total number of odd & even numbers entered and sum of odd and even numbers. Display total count of odd & even numbers and sum of odd & even numbers with appropriate titles.
sumOdd =0
sumEven = 0
cntOdd =0
cntEven = 0
while True :
no = int(input("enter a number (0 for exit)"))
if no < 0 :
print("enter positive no......")
elif no == 0 :
break
elif no % 2 == 0 :
cntEven = cntEven+1
sumEven = sumEven + no
else :
cntOdd = cntOdd+1
sumOdd = sumOdd + no
print ("count odd == ",cntOdd)
print ("sum odd == ",sumOdd)
print ("count even == ",cntEven)
print ("sum even == ",sumEven)
Write a Python program to take input of a positive number, say N, with an appropriate prompt, from the user. The user should be prompted again to enter the number until the user enters a positive number. Find the sum of first N odd numbers and first N even numbers. Display both the sums with appropriate titles.
n = int(input("enter n no.... : "))
sumOdd =0
sumEven = 0
for i in range (n) :
no = int(input("enter a positive number : "))
if no > 0 :
if no % 2 == 0 :
sumEven = sumEven + no
else :
sumOdd = sumOdd + no
else :
print("exit.....")
break
print ("sum odd == ",sumOdd)
print ("sum even == ",sumEven)

Python: Write a program that counts positive and negative numbers and computers the average of numbers

I saw a similar post, but it included functions, which mine does not.
Objective: Write a program that reads an unspecific number of integers, determines how many positive and negative values have read, and computes the total and average of the input values (not counting 0's) while the program will halt at 0.
ISSUE I AM HAVING: When using the following test values
1,
2,
-1,
3
I get the following:
The number of positives: 1
The number of negatives: 2
The total amount of numbers used: 3
The average is 1.33 which is 4 / 3
It should be:
The number of positives: 1
The number of negatives: 3
The total amount of numbers used: 4
The average is 1.25 which is 5 / 4
My Attempt below:
positive_number = 0
negative_number = 0
average = 0
count = 0
new_number = 0
user_input = eval(input("Enter enter as many integers as you want, 0 will halt: "))
if user_input == 0:
print("You didn't enter any number, code ended")
else:
while user_input != 0:
user_input = eval(input("Enter enter as many intergers as you want, 0 will halt: "))
if user_input == 0:
print("You didn't enter any number, code ended")
elif user_input != 0 and user_input > 0:
new_number += user_input
positive_number += 1
count += 1
else:
user_input != 0 and user_input < 0
new_number += user_input
negative_number += 1
count += 1
average = (new_number / count)
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(new_number), "/", str(count))
What is causing such error? I can only assume that this is a minor fix?
I've fixed the problems in your code and refactored to trap error conditions and removed unnecessary complications:
positive_number = 0
negative_number = 0
average = 0
count = 0
total = 0
user_input = None
while user_input != 0:
try:
user_input = int(input("Enter enter as many intergers as you want, 0 will halt: "))
except ValueError:
user_input=0
if user_input > 0:
total += user_input
positive_number += 1
count += 1
elif user_input<0:
total += user_input
negative_number += 1
count += 1
if count==0:
print("You didn't enter any number, code ended")
else:
average = total / count
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(total), "/", str(count))
First, the first if statement is redundant as you test for user_input != 0 as the loop condition. Second, the reason it was going wrong was because on your first input you immediately overwrote the value of user_input, so I put the reprompt code at the end of the loop. Finally, I cleaned up the if elif else statement as this does the exact same with fewer characters. The print statement for the closing line is also executed once we pull out of the loop - sinc eby definition that means user_input == 0
positive_number = 0
negative_number = 0
average = 0
count = 0
new_number = 0
user_input = eval(input("Enter enter as many integers as you want, 0 will halt: "))
while user_input != 0:
if user_input > 0:
new_number += user_input
positive_number += 1
count += 1
else:
new_number += user_input
negative_number += 1
count += 1
average = (new_number / count)
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(new_number), "/", str(count))
user_input = eval(input("Enter enter as many intergers as you want, 0 will halt: "))
print("You didn't enter any number, code ended")
Like it was said in the comments, your first input is getting ignored. Here is an alternative that should work. I excluded a few redundant check statements.
positive_number = 0
negative_number = 0
average = 0
count = 0
new_number = 0
user_input = 1
while user_input != 0:
user_input = eval(input("Enter enter as many integers as you want, 0 will halt: "))
if user_input == 0:
print("You didn't enter any number, code ended")
elif user_input > 0:
new_number += user_input
positive_number += 1
count += 1
else:
new_number += user_input
negative_number += 1
count += 1
average = (new_number / count)
print("\nThe number of positives:", positive_number)
print("The number of negatives:", negative_number)
print("The total amount of numbers used:", count)
print("The average is", format(average,".2f"), "which is", str(new_number), "/", str(count))
There are a number of issues with your code. First of all, the first number that the user prompts is not being evaluated by the code; it's being overwritten once you get to the while loop. There are multiple ways to fix this, but the best would be along the lines:
cont = True
while cont is True:
user_input = int(input("Prompt user"))
if user_input == 0:
cont = False
You could do a break statement too, it doesn't matter.
So that takes care of why the first number isn't being read, and why the code thinks there were only 3 inputs (as well as your count being off). Now what about the two negatives? I don't know why you got that. When I inputted the numbers you listed, I got one negative and two positives. Try it again and see if it works now, I suspect you must've mistyped.

Python: (Count positive and negative numbers and compute the average of numbers)

Problem statement: 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.
Sample output (ignore bullets, didn't know how to format text into console output):
Enter an integer, the input ends if it is 0: 1
Enter an integer, the input ends if it is 0: 2
Enter an integer, the input ends if it is 0: -1
Enter an integer, the input ends if it is 0: 3
Enter an integer, the input ends if it is 0: 0
You didn't enter any number
The number of positives is 3
The number of negatives is 1
The total is 5
The average is 1.25
Attempted solution:
def main():
i = int( input ("Enter an interger, the input ends if it is 0: "))
count_pos = 0
count_neg = 0
total = 0
if (i != 0):
while (i != 0):
if (i > 0):
count_pos += 1
elif (i < 0):
count_neg += 1
total += i
i = int( input ("Enter an interger, the input ends if it is 0: "))
count = count_pos + count_neg
average = total / count
print ("The number of positives is", count_pos)
print ("The number of negatives is", count_neg)
print ("The total is", total)
print ("The average is", float(average))
else:
print ("You didn't enter any number.")
main()
You do not need this line (which is why your error is happening):
main(i)
To continuously get user input, use an infinite loop, and test for the condition to break the loop.
while (true):
i = input("Enter an integer (0 to stop): ")
if(i == 0)
break
sum1 += i
if (i > 0):
count_pos += 1
elif (i < 0):
count_neg += 1
Then calculate and return average.
You are calling the main function with the parameter 'i', which does not exist. You can't use variables declared in a function outside of that function
Check out: Python Scopes

Categories

Resources