Python 2 Odd or Even numbers - python

I'm trying to fix a problem like if a number is odd print smth. if even print smth. else. My Python code is as follows ;
import sys
import math
N = int(raw_input().strip())
def dec(num):
if num % 2 == 0 and num != 0:
print 'Not Odd'
elif num == 0:
print 'Case Zero'
else:
print 'Even'
dec(N)
Why I can't compile this code ?

You have a ' within the string enclosed by 's.
Try:
print 'Zero can\'t be odd or even!'
As I see, your indent is bad as well.
Pleas align the elif and else below the if.
You also have a not syntactical problem.
"Not even" and "Odd" are the two possibilities for you which is bad.
I've corrected these errors for you:
def dec(num):
if num % 2 == 0 and num != 0:
print 'Even'
elif num == 0:
print 'Zero can\'t be odd or even!'
else:
print 'Odd'
for N in range(5):
dec(N)
One more thing is that you should think about the question about 0 wheter you really want to say that it's not even.
Ask your math teacher about this.

Related

Why my for loop is not iterating all the values

When I run this code and give input as 25 it should return me its not a prime num,
But when I debug the code the range values are not iterating into if condition, only the first value of the range is passed and if its not == 0 it moves to the else part.
def find(x):
if x > 1:
for i in range(2,x):
if x % i == 0:
return "its not a prime num"
else:
return "Its a prime num"
user = int(input("Enter your no: "))
print(find(user))
Please help me why its working like this , I am new to programming . TIA
As stated in a comment, this is an easy fix. Simply move the else statement's return to outside of the loop.
def find(x):
if x > 1:
for i in range(2,x):
if x % i == 0:
return "its not a prime num"
return "Its a prime num"
user = int(input("Enter your no: "))
print(find(user))
Using a return inside of a loop will break it and exit the function even if the iteration is still not finished. use print instead.
I discovered that for whatever reason for loops never run with the final value an easy fix is to just add 1 to the ending value.

What's wrong with my use of if / then in this script?

I'm learning if and then statements. I'm trying to write code that takes any decimal number input (like 2, 3, or even 5.5) and prints whether the input was even or odd (depending on whether the input is actually an integer.)
I get an error in line 8
#input integer / test if any decimal number is even or odd
inp2 = input("Please enter a number: ")
the_number = str(inp2)
if "." in the_number:
if int(the_number) % 1 == 0
if int(the_number) % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
else:
print("You dum-dum, that's not an integer.")
else:
the_number = int(inp2)
if the_number % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
I'm just starting with python so I appreciate any feedback.
You have to include a colon at the end of second if statement, like you did in your other conditional statements.
if int(the_number) % 1 == 0:
Next time, give a closer look at the error message. It'll give you enough hints to fix it yourself, and that's the best way to learn a language.
EOL.
You forgot a :. Line 8 should read if int(the_number) % 1 == 0:.
Try putting the : at the end of the if statement
if int(the_number) % 1 == 0:
You can test your input as following code snippet
num = input('Enter a number: ')
if num.isnumeric():
print('You have entered {}'.format(num))
num = int(num)
if num%2:
print('{} is odd number'.format(num))
else:
print('{} is even number'.format(num))
else:
print('Input is not integer number')

how can i print two character of a string if it's even or one if it's odd?

how can one find middle character in a string if the string is odd, or the two middle if the string is even? I have been trying but coming up empty-handed. i will appreciate any help.
def middle(s):
for length in userInput:
if len(userInput) % 2 == 0:
return i
elif len(userInput) % 2 != 0:
this is what i have so far. i know it needs to be different, i'm just not sure how to change it.
thanks
I'm not really sure where userInput is defined or why you're iterating, but this will return what you're looking for from string s:
def middle(s):
s_len = len(s)
if s_len % 2 == 0:
return s[int(s_len/2)-1:int(s_len/2)+1]
else:
return s[int(s_len/2)]

Python indentation, allignment of IFs and ELSEs

I am new to python and i am still strugling to understand how the sytnax works, how you need to allign your If and else to make it work correctly. How do i really know which else goes with which if? especially when using nested code blocks.
In the code below for the else followed by the comment Prime! from what i understand that else goes with the statement if (n % div == 0): but then why is it alligned with the FOR statement instead?
the last else statement i think goes with if n == 2: but the else is not alligned with it, instead it is after. For the same statement if n == 2: why is n += 1 alligned before pime_count +=1 and not after it.
I understand that the placement of the Else and if is very important because if i decided to move any of them the code stops working. What i can't seem to understand is how does python know which else goes with which if, if the allignment doesnt seem to be consistent.
#!/usr/bin/env python
#
# Problem Set 1a
#
# A program that computes and prints the 1000th prime number.
# Finds primes using trial division (least efficient method)
#------------------------------------------------------------
prime_count = 0
n = 2
while (prime_count <= 1000):
#if even, check for 2, the only even prime
if (n % 2 == 0):
if n == 2:
prime_count += 1
n += 1
else:
# number is odd, possible prime
for div in range(3, n, 2):
if (n % div == 0):
# not a prime
n += 1
break
else:
# prime!
prime_count += 1
if prime_count == 1000:
print "The 1000 prime is", n
else:
n += 1
The rule is very simple: the else clause must have the same indentation as the statement it refers to (most commonly, an if statement).
Now, here:
for div in range(3, n, 2):
if (n % div == 0):
# not a prime
n += 1
break
else:
...
you are not using if-else, you are using for-else!
This construct means "execute the else block unless the loop has terminated through a break".
See for ... else in Python for a discussion.
An if goes with an else at the same indentation, so long as there are no other things at lower indentation between them. They have to be in the same "block". However, in your case, the else that's followed by # prime! is not actually joined to an if at all, but rather to the for div in range(3, n, 2): loop before it!
An else attached to a for loop means "execute this code if the for loop completed without hitting a break statement". It can be useful sometimes, but it is often confusing for people who haven't encountered it before!
I think this can help you to understand how python indentation works http://psung.blogspot.com/2007/12/for-else-in-python.html
In a construct like this one:
for i in foo:
if bar(i):
break
else:
baz()
the else suite is executed after the for, but only if the for terminates normally (not by a break).
In other situations else goes after if
There are 2 rules which are fairly simple,
The indent of the if and else have to be the same
for x in range(15):
if x > 10:
print 'x is more than 10'
else:
print 'x is less than or equal to 10'
Nothing with an indent lower than or equal to that of if and elseshould come in between them
So, this is invalid/ will raise a SyntaxError.
for x in range(15):
if x > 10:
print 'x is more than 10'
print x
else:
print 'x is less than or equal to 10'
Also, As stated in PEP 8
Use 4 spaces per indentation level.
for div in range(3, n, 2):
if (n % div == 0):
# not a prime
n += 1
break
else: # at same indent as for
# prime!
Also, your indent above means for...else loop is made (here else clause is executed if the for loop is exited using break), not if..else.

Why isn't this simple code working, for Python?

x = raw_input("Write a number")
if x.isalpha():
print "Invalid!"
elif x%2==0:
print "The number you have written is EVEN"
elif x%2!=0:
print "The number you have written is ODD"
else:
print "Invalid!"
It is supposed to check if the number is odd or even and print it out. My if statement checks if the raw_input was an alphabet because that won't work. And my elif statements check for odd or even.
The return value of raw_input is always a string. You'll need to convert it to an integer if you want to use the % operator on it:
x = raw_input("Write a number")
if x.isalpha():
print "Invalid!"
x = int(x)
Instead of x.isalpha() you can use exception handling instead:
try:
x = int(raw_input("Write a number"))
except ValueError:
print 'Invalid!'
else:
if x % 2 == 0:
print "The number you have written is EVEN"
else:
print "The number you have written is ODD"
because int() will raise ValueError if the input is not a valid integer.
The return value of raw_input is a string, but you need a number to do the parity test.
You can check whether it's an alpha string, and if not, convert it to an int.
For example:
xs = raw_input("Write a number")
if xs.isalpha():
print "Invalid!"
else:
xn = int(xs)
if xn % 2 == 0:
print "The number you have written is EVEN"
elif xn % 2 != 0:
print "The number you have written is ODD"
else:
print "The universe is about to end."

Categories

Resources