Finding Even Numbers In Python - python

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.

Related

Modulo Operation for Odd & Even Number

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

Nested IF Statement with Odd / Even

I'm very much new to Python and have been trying out new exercises online and I've completed a few with If/Else/Else If.
This new program I'm trying to run asks the user to enter an integer and depending on what they enter the print feedback will be different. The program must us a Nested IF.
The first statement for 'entered is zero' is working perfectly. But when I enter an even number it still says 'Odd' and I can't work out why and I've been looking at many different tutorials.
Perhaps I'm not using the Nested If Statement in the correct manner?
All help very appreciated.
Thanks!
enter = int(input("Enter an Integer: "))
option = enter % 2
if (enter == 0):
print("The number you entered is zero")
if (option % 2) > 0:
print("The number you entered is larger than zero and even")
else:
print("The number you entered is larger than zero and odd")
Since, you specifically asked for nested if statements, check the answer below:
enter = int(input("Enter an Integer: "))
if enter > 0:
if enter % 2 == 0:
print ("Number entered is greater than 0 and even")
else:
print ("Number enetred is greater than 0 and odd")
else:
print ("Number entered is less than or equal to 0")
x = int(input("Enter an Integer: "))
if (x >= 0):
if (x ==0) :
print("Number is 0" %x)
elif (x %2 == 0):
print (" Number %d is a positive even number" %x)
else:
print ("Number %d is a positive odd number" %x)
else:
if (abs(x)%2 == 0):
print ( "Number %d is a negative even number" %x)
else:
print ( "Number %d is a negative odd number" %x)

Collatz sequence ends at 4

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

Can anyone figure out this code for me?

import random
print "Welcome to the number guesser program. We will pick a number between 1 and 100 and then ask you to pick a number between 1 and 100. If your number is 10 integers away from the number, you win!"
rand_num = random.randint(1, 100)
user_input = raw_input('Put in your guess:').isdigit()
number = int(user_input)
print number
if abs(rand_num - number) <= 10:
print "Winner"
else:
print "Loser"
Whenever I try to run this code, the computer always generates the number 1. And if I put in a number that is 10 (or less) integers away from one it will still display the else statement. I will have my gratitude to whoever can solve my predicament. I am new to python try to keep your answers simple please.
raw_input returns a string you entered as input. isdigit() checks whether a string is a digit or not and returns True or False.
In your code you're assigning the return value of isdigit to user_input So, you get either True or False. Then you convert it to a number, thus getting either one or zero. This is not what you want.
Let user_input be just a result of raw_input. Then check whether it is a valid number with user_input.isdigit(). If it's not a number, print an error message and exit (or re-ask for input), else convert user_input to an integer and go on.
The problem is product by this sentenc:
user_input = raw_input('Put in your guess:').isdigit().
The return value of isdigit() is True or False. When you enter 1 or any digit number, it will return True(True=1,False=0), so you will always get 1, if you enter digit. You can change like this:
import random
print "Welcome to the number guesser program.
We will pick a number between
1 and 100 and then ask you to pick a number
between 1 and 100. If your number is 10 integers
away from the number, you win!"
rand_num = random.randint(1, 100)
user_input= raw_input('Put in your guess:')
is_digit = user_input.isdigit()
if is_digit==True:
number = int(user_input)
print number
if abs(rand_num - number) &lt= 10:
print "Winner"
else:
print "Loser"
else:
print 'Your input is not a digit.'
Look at this line:
user_input = raw_input('Put in your guess:').isdigit()
The function raw_input gives you user input, but then you call isdigit and as consequence in your variable user_input you get result of isdigit. So, it has boolean value.
Then in
number = int(user_input) you cast it to integer type. In python true is 1 and false is 0. That's why you always get 1.

How to compare inputted numbers without storing them in list

Note: This is not my homework. Python is not taught in my college so i am doing it my myself from MITOCW.
So far i have covered while loop, input & print
Q) Write a program that asks the to input 10 integers, and then prints the largest odd number that was entered. If no odd number was entered it should print a message to the effect
How can i compare those 10 number without storing them in some list or something else? Coz i haven't covered that as if yet.
print "Enter 10 numbers: "
countingnumber=10
while countingnumber<=10:
number=raw_input():
if number % 2 == 0:
print "This is odd"
countingnumber=countingnumber+1
else:
print "This is even. Enter the odd number again"
i think the program will look something like this. But this has some unknown error & How can i compare all the numbers to get the largest odd number without storing those 10 numbers in the list.
print "Enter 10 numbers: "
countingNumber = 1
maxNumber = 0
while countingNumber<=10:
number=int(raw_input())
if (number % 2 == 0):
countingNumber = countingNumber+1
if (maxNumber < number):
maxNumber = number
else:
print "This is even. Enter the odd number again"
print "The max odd number is:", maxNumber
you can just define a maxnum variable and save the max in it! also you must use int(raw_input()) instead raw_input()
print "Enter 10 numbers: "
maxnum=0
for i in range(10):
number=int(raw_input())
if number%2 == 0:
print "This is odd"
if number>maxnum:
maxnum=number
else:
print "This is even. Enter the odd number again"
print "max odd is :{0}".format(maxnum)
DEMO:
Enter 10 numbers:
2
This is odd
4
This is odd
6
This is odd
8
This is odd
12
This is odd
14
This is odd
16
This is odd
100
This is odd
2
This is odd
4
This is odd
max odd is :100
Whenever I do input, I like to make sure I don't leave room for human error giving me bugs.
Because I put in extra checks I break code into a lot of separate function. This also gives code the quality of being non-coupled. ie) You can reuse it in other programs!!
def input_number():
while true:
input = raw_input("Enter Value: ")
if not input.isdigit():
print("Please enter numbers only!")
else:
return int(input)
Designing the input function in this fashion gives the code no opportunity to crash. We can now use it in a function to get odd numbers!
def input_odd_number():
while true:
input = input_number()
if input % 2 == 0:
print("Please enter odd numbers only!")
else:
return input
Now we can finally move onto the main code. We know we need ten numbers so lets make a for loop. We also now we need to hold onto the largest odd number, so lets make a variable to hold that value
def largest_odd(count = 10): // its always nice to make variables dynamic. The default is 10, but you can change it when calling!
max_odd = input_odd_number() // get the first odd number
for i in range(count - 1): // we already found the first one, so we need 1 less
new_odd = input_odd_number()
if new_odd > max_odd:
max_odd = new_odd
print("The largest odd value in '{}' inputs was: {}".format(count, max_odd)
In your solution are multiple flaws.
A syntax error: The colon in number=raw_input():.
raw_input returns a string and you have to cast it to an int.
Your while loop just runs one time, because you start with 10 and compare 10 <= 10. On the next iteration it will be 11 <= 10 and finishes.
Also you have mixed odd an even. even_number % 2 gives 0 and odd_number % 2 gives 1.
To get the biggest value you only need a additional variable to store it (See biggest_number in my solution). Just test if this variable is smaller then the entered.
You ask again if the number is odd, but you should take every number and test only against odd numbers.
A working solution is:
print "Enter 10 numbers"
count = 0
max_numbers = 10
biggest_number = None
while count < max_numbers:
number=int(raw_input("Enter number {0}/{1}: ".format(count + 1, max_numbers)))
if number % 2 == 1:
if biggest_number is None or number > biggest_number:
biggest_number = number
count += 1
if biggest_number is None:
print "You don't entered a odd number"
else:
print "The biggest odd number is {0}".format(biggest_number)
If you wonder what the format is doing after the string take a look in the docs. In short: It replaces {0} with the first statement in format, {1} with the second and so on.
here is the correct code for that:
print "Enter 10 numbers: "
countingnumber=1
MAX=-1
while countingnumber<=10:
number=int(raw_input())
if number%2==1:
if number>MAX:
MAX=number
if MAX==-1:
print "There Weren't Any Odd Numbers"
else:
print MAX
here are some notes about your errors:
1- you should cast the raw input into integer using int() function and the column after calling a function is not needed and therefor a syntax error
2- your while loop only iterates once because you initial counting number is 10 and after one iteration it would be bigger than 10 and the while body will be skipped.
3-an even number is a number that has no reminder when divided by 2 but you wrote it exactly opposite.
4- you don't need to print anything in the while loop, you should either print the biggest odd number or print "There Weren't Any Odd Numbers".
5- an additional variable is needed for saving the maximum odd number which is MAX.
Last note: in the code provided above you can combine the two ifs in the while loop in to one loop using 'and' but since you said you are a beginner I wrote it that way.

Categories