I can get the program to count properly and I can get the program to not except float and strings but when i put the two pieces of code together the program won't run the count. Thanks for the help.
print("\tProgram counts the number of positive integers.")
def numCount():
even_count = 0
odd_count = 0
even_sum = 0
odd_sum = 0
total = 0
while True:
try:
num = int(input("Input an integer to count 0 exits program: "))
except ValueError:
print("Please enter an integer.")
continue
else:
return num
if num == 0:
break
elif num < 1:
continue
elif num % 2 == 0:
even_count += 1
even_sum += num
else:
odd_count += 1
odd_sum += num
total += 1
print("\nTotal positive intger count is:", total)
numCount()
You should not return num in the else statement of the try/except. This will immediately exit the function and return the current value of num, instead of it continuing to be processed in the rest of your code.
To fix this, you can simply remove the else statement.
You can simply remove:
else:
return num
This is because return will exit the function early and stop the while loop from continuing.
Related
I am trying to write a program where a user enters a bunch of numbers and when 0 is entered the program ends and prints how many positive numbers were entered. I am fairly close to solving this but can't get the positive sum to print.
Could you please explain where I have gone wrong?
Thanks in advance.
Please see attached my code.
userInput = None
oddNum = 0
evenNum = 0
while(userInput != 0):
userInput = int(input("Enter a number: "))
if(userInput > 0):
if(userInput % 2 == 0):
evenNum += 1
elif(userInput % 2 != 0):
oddNum += 1
print("positive numbers were entered".format(evenNum, userInput))
You are missing some of the required syntax for the string.format() command.
For each variable you want injected into the string to be printed, you must include a pair of curly braces {}. Otherwise, the arguments you pass to string.format() are just ignored.
userInput = None
oddNum = 0
evenNum = 0
while(userInput != 0):
userInput = int(input("Enter a number: "))
if(userInput > 0):
if(userInput % 2 == 0):
evenNum += 1
elif(userInput % 2 != 0):
oddNum += 1
print("positive numbers were entered; {} even numbers, and {} odd numbers".format(evenNum, userInput))
I am very new to python. I am trying to write a program that tests if a number is between a given range, then tells you if the number is odd or even. I am having trouble with the part that detects if it is odd or even. It seems that if it just repeats my even statement. Here is the code:
while True:
num = int(input("Please enter an integer between 1 and 50: "))
if num >= 1 and num <= 50:
for num in range (1, 50):
if (num % 2 == 0):
print("Your number is even.")
else:
print("Your number is odd.")
else:
print("Try again. Number must be 1 through 50.")
I don't think you need a for loop at all, and you forgot to indent the else part if your inner if-else:
while True:
num = int(input("Please enter an integer between 1 and 50: "))
if num >= 1 and num <= 50:
for num in range (1, 50): # not needed
if (num % 2 == 0):
print("Your number is even.")
else: # here
print("Your number is odd.")
else:
print("Try again. Number must be 1 through 50.")
for-else constructs exist (and are pretty neat), but it you're starting to learn Python, it's a story for another time.
Nope, you don't need the for loop:
while True:
num = int(input("Please enter an integer between 1 and 50: "))
if 1 <= num <= 50:
if num % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
else:
print("Try again. Number must be 1 through 50.")
I think you don't need for loop, Remove for loop and try again.
while True:
num = int(input("Please enter an integer between 1 and 50: "))
if num >= 1 and num <= 50:
if (num % 2 == 0):
print("Your number is even.")
else: # here
print("Your number is odd.")
else:
print("Try again. Number must be 1 through 50.")
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)
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.
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): "))