I want to check the Even or Odd numbers therefore I have written the following code:
number = int(input("Which number do you want to check? "))
if number % 2 == 0:
print("This is an even number")
else:
print("This is an odd number")
It gives the following result:
Which number do you want to check? 20
This is an even number
But when is change the above code inversely like this
number = int(input("Which number do you want to check? "))
if number % 2 == 0:
print("This is an odd number")
else:
print("This is an even number")
It gives the following result:
Which number do you want to check? 20
This is an odd number
even if I change the "If modulo operation" to % 7 == 2 it would still give even as odd or vice versa
if number % 2 == 0: print("This is an even number")
else: print("This is an odd number")
But when is change the above code inversely like this
if number % 2 == 0: print("This is an odd number")
else: print("This is an even number")
You only switched the print statements but you didn't update the if condition.
We know that if an integer mod 2 is 0, then it is even... or if an integer mod 2 is 1, then it is odd. So you should change the condition of the bottom piece of code to if number % 2 != 0
Related
This question already has answers here:
Check if a number is odd or even in Python [duplicate]
(6 answers)
Closed 1 year ago.
number = int(input("Type your number to check even or odd :"))
for number in range (1,100):
if(number%2) == 0:
print("This is even number")
elif number > 100:
print("Enter the valid number from 1 to 100")
else:
print("This is ODD number")
i am a beginner in python language , I have written code to read the number as EVEN or ODD in for loop condition between (1,100). correct me if making any mistakes in my code .
Why are you using for loop, just check the condition like if number > 100;the number is invalid.Check this example
nos=int(input())
if(nos>100):
print("Enter the valid number from 1 to 100 ")
else:
if(nos % 2 ==0):
print("Number is Even")
else:
print("Number is Odd")
There are mistakes in your code.
1.Indentation error at the 2nd line.(Remove whitespace before for loop.)
2.The name of the input variable and the iterator name in for loop is same. So your intended logic would run on the numbers from 1 ,2, 3 ..... 99. It never runs on the user entered value. So change the name of any variable. Both cant be 'number'.
3.Although you change the name of the variable, you initialised for loop with 100 iterations so you see output 100 times.
so if you want to check the numbers between given range which are even or odd you can try this..
num = int(input(" Please Enter the Maximum Number : "))
for number in range(1, num+1):
if(number % 2 == 0):
print("{0} is Even".format(number))
print("{0} is Odd".format(number))
I am trying to write a short python script that gives the user a prime number starting with 3 and continues providing the next prime number if the user wishes to see it.
Here is the function I have created. When I run it I cannot move past the number 3 which is where it starts by design. I get the print statement "3 is not a prime number" and then the input() field pops up to which I enter 'Yes' and I expect the variable 'count' to be incremented to 4 and the script to check again if it is prime.
It should go through this process checking every number and returning just the primes, then asking the user if they wish to see another one. Any ideas why I am stuck on and endless loop of "3 is not a prime number"
def prime_number():
game_on = True
while True:
count = 3
for num in range(2,count):
if count % num == 0:
print(f'{count} is not a prime number')
break
elif count % num != 0:
print(f'{count} is a prime number')
break
else:
pass
question = input("Would you like to see another prime number?? Please enter Yes or No: ")
if question == "Yes":
count += 1
else:
break
game_on = False
You should put the starting count value outside of the main loop.
count = 3
while True:
for num in range(2,count):
def prime_number():
game_on = True
count = 3
while True:
for num in range(2, count):
if (count % num) == 0:
print(count,"is not a prime number")
break
else:
print(count,"is a prime number")
question = input("Would you like to see another prime number?? Please enter Yes or No: ")
if question == "Yes":
count = count + 1
continue
return
This solution works well. You could in fact used int(count/2) since no number has a factor greater than itself divided by 2.
Create a function that checks whether a number is a prime number
1 def is_prime(num):
2 for i in range(2,num):
3 if num%i != 0:
4 return False
5 return True
You put the "count = 3" line inside the for loop, so count will just equal 3 for every iteration. The solution would be to declare count before the While loop
game_on = True
count = 3
while True:
...
I am writing a Collatz sequence program using the practice projects from chapter 3 of Automate the boring stuff with python.
The program outline is:
Write a function named collatz() that has one parameter named number.
If number is even, then collatz() should print number // 2 and return
this value. If number is odd, then collatz() should print and return
3 * number + 1.
Then write a program that lets the user type in an integer and that
keeps calling collatz() on that number until the function returns the
value 1.
My code runs however it stops on 4 rather than 1. For every number I have tried so far the output goes past 1 back to 4.
example output:
6,3,10,5,16,8,4,2,1,4
I am using python 3.4.2
def collatz(number):
if number % 2 == 0:
number = number //2
print(number)
return number
elif number % 2 == 1:
number = 3 * number + 1
print(number)
return number
print ("pick a number:")
while True:
try:
number = int(input())
while number != 1:
number = collatz(number)
collatz(number)
break
except ValueError:
print("Error: Please enter a valid integer")
print("Magic! You are down to 1.")
The problem is that you call collatz() once more after the loop finishes with 1. Just remove that line, and it works fine.
Also if you move the "pick a number" to the input function, you can avoid the new line after the question and are asked again every time, if you input an invalid value.
Additionally you should also check if the number is greater than or equal to 1, to avoid endless loops. The code to do all that would look like that:
while True:
try:
number = int(input("pick a number: "))
if number < 1:
print("Error: Please enter a integer greater than or equal to 1 ")
continue
while number != 1:
number = collatz(number)
# removed the additional call to collatz
break
except ValueError:
print("Error: Please enter a valid integer")
print("Magic! You are down to 1.")
def collatz(number):
number = number // 2 if number % 2 == 0 else 3 * number + 1
print(number)
return number
number = int(input("Pick a Number\n"))
while number != 1:
number = collatz(number)
print("Magic! You are down to 1.")
This question already has an answer here:
Python Checking 4 digits
(1 answer)
Closed 1 year ago.
I want to write a program that only accepts a 4-digit input from the user.
The problem is that I want the program to accept a number like 0007 but not a number like 7 (because it´s not a 4 digit number).
How can I solve this? This is the code that I´ve wrote so far:
while True:
try:
number = int(input("type in a number with four digits: "))
except ValueError:
print("sorry, i did not understand that! ")
if number > 9999:
print("The number is to big")
elif number < 0:
print("No negative numbers please!")
else:
break
print("Good! The number you wrote was", number)
But if I input 7 to it it will just say Good! The number you wrote was 7
Before casting the user's input into an integer, you can check to see if their input has 4 digits in it by using the len function:
len("1234") # returns 4
However, when using the int function, Python turns "0007" into simple 7. To fix this, you could store their number in a list where each list element is a digit.
If it's just a matter of formatting for print purposes, modify your print statement:
print("Good! The number you wrote was {:04d}", number)
If you actually want to store the leading zeros, treat the number like a string. This is probably not the most elegant solution but it should point you in the right direction:
while True:
try:
number = int(input("Type in a number with four digits: "))
except ValueError:
print("sorry, i did not understand that! ")
if number > 9999:
print("The number is to big")
elif number < 0:
print("No negative numbers please!")
else:
break
# determine number of leading zeros
length = len(str(number))
zeros = 0
if length == 1:
zeros = 3
elif length == 2:
zeros = 2
elif length == 3:
zeros = 1
# add leading zeros to final number
final_number = ""
for i in range(zeros):
final_number += '0'
# add user-provided number to end of string
final_number += str(number)
print("Good! The number you wrote was", final_number)
pin = input("Please enter a 4 digit code!")
if pin.isdigit() and len(pin) == 4:
print("You successfully logged in!")
else:
print("Access denied! Please enter a 4 digit number!")
I have a Python assignment that is as following: "Write a complete python program that asks a user to input two integers. The program then outputs Both Even if both of the integers are even. Otherwise the program outputs Not Both Even."
I planned on using an if and else statement, but since I'm working with two numbers that have to be even instead of one, how would I do that?
Here is how I would do it if it was one number. Now how do I add the second_int that a user inputs???
if first_int % 2 == 0:
print ("Both even")
else: print("Not Both Even")
You can still use an if else and check for multiple conditions with the if block
if first_int % 2 == 0 and second_int % 2 == 0:
print ("Both even")
else:
print("Not Both Even")
An even number is an integer which is "evenly divisible" by two. This means that if the integer is divided by 2, it yields no remainder. Zero is an even number because zero divided by two equals zero. Even numbers can be either positive or negative.
Use raw_input to get values from User.
Use type casting to convert user enter value from string to integer.
Use try excpet to handle valueError.
Use % to get remainder by dividing 2
Use if loop to check remainder is 0 i.e. number is even and use and operator to check remainder of tow numbers.
code:
while 1:
try:
no1 = int(raw_input("Enter first number:"))
break
except ValueError:
print "Invalid input, enter only digit. try again"
while 1:
try:
no2 = int(raw_input("Enter second number:"))
break
except ValueError:
print "Invalid input, enter only digit. try again"
print "Firts number is:", no1
print "Second number is:", no2
tmp1 = no1%2
tmp2 = no2%2
if tmp1==0 and tmp2==0:
print "Both number %d, %d are even."%(no1, no2)
elif tmp1==0:
print "Number %d is even."%(no1)
elif tmp2==0:
print "Number %d is even."%(no2)
else:
print "Both number %d, %d are NOT even."%(no1, no2)
Output:
vivek#vivek:~/Desktop/stackoverflow$ python 7.py
Enter first number:w
Invalid input, enter only digit. try again
Enter first number:4
Enter second number:9
Firts number is: 4
Second number is: 9
Number 4 is even.