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.")
Related
I’m trying to create a Python program that can tell you how many digits there are in a number. For example, the input 2345 yields the output 4 digits. I tried making it a while loop but now it prints how many digits are in the number infinitely.
interger = int(input('please type an interger and the programme will tell you how many digits it has!: '))
while interger != 0:
if 0 < interger < 10:
print ('1 digit')
elif 9 < interger < 100:
print('there are 2 digits')
elif 99 < interger < 1000:
print('there are 3 digits')
elif 999 < interger < 10000:
print('there 4 digits')
elif 9999 < interger < 100000:
print('there are 5 digits')
elif 99999 < interger < 1000000:
print ('there are 6 digits')
elif 999999 < interger < 10000000:
print('there are 7 digits')
elif 9999999 < interger < 100000000:
print('there are 8 digits.')
break
elif interger == interger:
print('that is correct')
Your 'while' condition is the cause of the infinite printing, as the value of interger is never changed. If you would like it to simply execute the print once, change
while interger!=0:
to
if interger != 0:
My suggestion for your script:
run = None
while run != 'q':
integer = input("Enter number: ")
print(f'There are {len(integer)} digits')
run = input("Enter q to quit, enter any other key to do another")
If not helpful for you, I will suggest another way.
interger= int(input('please type an interger and the programme will tell you how many digits it has!: '))
dig = 0
while(interger != 0) :
interger /= 10
dig += 1
print("There are " + str(dig) + " digits.")
How about this?
Python code to tell number of digits in an input number and print answer only once
interger = int(input('please type an interger and the programme will tell you how many digits it has!: '))
#to print once
print(f"given input {interger} has {len(str(interger))} digits")
output
please type an interger and the programme will tell you how many digits it has!: 65
given input 65 has 2 digits
Leaving aside the fact that the algorithm is less than ideal, you just don't need a loop.
interger= int(input('please type an interger and the programme will tell you how many digits it has!: '))
if 0<=interger<10: # zero is also 1 digit
print ('1 digit')
elif 9<interger<100:
print('there are 2 digits')
#etc.
In the below code, if the input is even, the number doubles, if not 1 is added. This goes on until the number is greater than 100.
number=int(input("Enter a number: "))
print(number)
while number < 100:
if number % 2 == 0:
number *= 2
else:
number = number+1
print(number)
Once it has reached 100, I want it to repeat the same process for input+1. I can't use number=number+1 because it would use the last version of number rather than the original input.
Thank you for any help!
You can use two loops with to copies of number, for instance:
number=int(input("Enter a number: "))
print(number)
while number < 100:
num = number
while num < 100:
if num % 2 == 0:
num *= 2
else:
num += 1
print(num)
number += 1
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 have to write a program that tells the user the factorial of any integer between 1 and 15 while using the while loop. I wrote the code below and the output gives me endless factorials/numbers.. Do you know what I did wrong? Thank you!
Update: I realized that I should use "while" for what num isn't, so I now have this code below, but it still says invalid syntax for the second "while".
# take input from the user
num = int(input("Please enter a number from 1 to 15: "))
factorial = 1
# check if the number is negative, positive or zero
while num < 0:
num = int(input("Negative numbers don't have factorials! Please enter a number between 1 and 15: ")
while num > 15:
num = int(input("Please enter a number between 1 and 15! ")
if num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
I would do this:
from math import factorial as factorial
while True:
num = int(input("Please enter a number from 1 to 15: "))
if 1 <= num <= 15:
fact = factorial(num)
print 'the factorial of {n} is {f}'.format(n=num, f=fact)
else:
num = int(input("Please enter a number from 1 to 15: "))
You missed a closing parenthesis:
while num > 15:
num = int(input("Please enter a number between 1 and 15! "))
^ here
you have missed the braces at the end of int() funtion
# take input from the user
num = int(input("Please enter a number from 1 to 15: "))
factorial = 1
# check if the number is negative, positive or zero
while num < 0:
num = int(input("Negative numbers don't have factorials! Please enter a number between 1 and 15: ")) # brace was missing
while num > 15:
num = int(input("Please enter a number between 1 and 15! ")) # brace was missing
if num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
You might have meant like the below in order to loop until you get correct input:
# take input from the user
num = int(input("Please enter a number from 1 to 15: "))
factorial = 1
while(True):
if num < 0:
num = int(input("Negative numbers don't have factorials! Please enter a number between 1 and 15: ")) # brace was missing
continue
if num > 15:
num = int(input("Please enter a number between 1 and 15! ")) # brace was missing
continue
if num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
break
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): "))