Why isn't this simple code working, for Python? - 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."

Related

Palindrome Program Cannot Recognize Other [duplicate]

This question already has answers here:
Python Palindrome
(3 answers)
Closed 1 year ago.
I am currently struggling with a homework problem and I need some help, as I feel like I'm a bit confused. I work on creating a program that looks for palindromes within integers only. The program I've made I know will accurately identify palindromes within integers, but I cannot get the program to identify when the input is not an integer (float, bool, str, etc.). I specifically want the program to note when an integer is not the input and print "The input is not an integer" before breaking. Here is my code below:
def Palindrome(n):
return n == n[::-1]
n = input("Please enter an integer: ")
ans = Palindrome(n)
if ans == True:
print("The number " + n + " is a palindrome")
elif ans == False:
print("The number " + n + " is NOT a palindrome")
I know this is kind of basic, but everyone needs to start somewhere! If anyone could explain what I could do to create the program and understand how it works, it would be very appreciated :)
Your palindrome() function has some indentation issues.
def palindrome(n):
return n == n[::-1]
This function can basically check whether a string str is a palindrome, and not just limited to integers.
n = input("Please enter anything: ")
is_palindrome = palindrome(n)
if is_palindrome:
print(n + " is a palindrome.")
else:
print(n + " is not a palindrome.")
Output
Test case A for racecar.
Please enter anything: racecar
racecar is a palindrome.
Test case B for 123.
Please enter anything: 123
123 is not a palindrome.
When you get an input it's always a string value, so a possible solution is to modify Palindrome. First, try to cast the input to int and then print and exit if it throws a ValueException in this way.
def Palindrome(n):
try:
int(n)
except ValueError as e:
raise ValueError('The value must be an integer')
return n == n[::-1]
if __name__ == "__main__":
try:
n = input("Please enter an integer: ")
ans = Palindrome(n)
if ans == True:
print("The number " + n + " is a palindrome")
elif ans == False:
print("The number " + n + " is NOT a palindrome")
except ValueError as e:
print(str(e))

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')

why do i get an error which says invalid, about this code?

why do i get an error whitch says invalid, about this code?
line = input("Enter an integer number : ")
num = int(line)
if (num % 2 == 0):
print("The number is even" ,num)
else:
print("The number is odd ", num)
You need to indent your code properly:
line = input("Enter an integer number : ")
num = int(line)
if (num % 2 == 0):
print("The number is even" ,num)
else:
print("The number is odd ", num)
If you're fairly new to python, a good point to start could be the documentation to learn about Block indentation.
Another problem could arise if its not possible to change the input within the variable line into an integer with int(line). You might want to have a look how to work with try and except to handle errors like that.

Python - Float doesn't equal the same float?

So I have this:
import random
rand=random.random()
print rand
inp = raw_input("Enter your guess: ")
print float(inp)
try:
if float(inp)==rand:
print "equal"
else:
print "not equal"
except:
print "error"
However it says it isn't equal. I know this is due to floating point inaccuracy, but how can I as a user input what come out to be equal?
Because you are using print on your float, it displays in a "nicer-looking" format that omits some decimal places. You can do print repr(rand) to show all the digits:
>>> rand = random.random()
>>> print rand
0.004312203809
>>> print repr(rand)
0.004312203809001436
If you use the latter form and then type all those numbers, you can get it to recognize the floats as equal.
Even you can use repr property
import random
rand=random.random()
print rand.__repr__()
inp = raw_input("Enter your guess: ")
print float(inp).__repr__()
try:
if float(inp)==rand:
print "equal"
else:
print "not equal"
except:
print "error"

Checking non-negative even integer in Python

I'm new to programming and currently learning Python. I would like to write a program that :
request user to input a non-negative even integer.
request the user to input again if not fulfil non-negative even integer.
N = input("Please enter an non-negative even integer: ") #request user to input
And the criteria checking code is:
N == int(N) #it is integer
N % 2 == 0 #it is even number
N >=0 # it is non-negative number
But how should I combine them?
since the question is tagged python-2.7, use raw_input instead of input (which is used in python-3.x).
Use str.isdigit to check if a string is an positive integer, int(N) would raise ValueError if the input couldn't be converted into integer.
Use a while loop to request user input if condition not fulfilled, break when you get a valid input.
e.g.,
while True:
N = raw_input("Please enter an non-negative even integer: ") #request user to input
if N.isdigit(): # accepts a string of positive integer, filter out floats, negative ints
N = int(N)
if N % 2 == 0: #no need to test N>=0 here
break
print 'Your input is: ', N
You can use the and operator:
while True:
s = input("Please enter an non-negative even integer: ")
# Use raw_input instead of input in Python 2
try:
N = int(s)
except ValueError:
continue # Not an integer, try again
if N % 2 == 0 and N >= 0:
break # Abort the infinite loop
Compared to other versions presented here, I prefer to loop without using the break keyboard. You can loop until the number entered is positive AND even, with an initial value set to -1:
n = -1
while n < 0 or n % 2 != 0:
try:
n = int(input("Please enter an non-negative even integer: "))
except ValueError:
print("Please enter a integer value")
print("Ok, %s is even" % n)
Just another solution:
>>> def non_neg(n):
... try:
... if n & 1 == 0 and n > 0:
... return 'Even Positive Number'
... except:
... pass
... return 'Wrong Number'
...
>>> for i in [-1,-2,2,3,4,0.5,'a']:
... print i, non_neg(i)
...
-1 Wrong Number
-2 Wrong Number
2 Even Positive Number
3 Wrong Number
4 Even Positive Number
0.5 Wrong Number
a Wrong Number
>>>
code for fun:
result=[ x for x in [input("Please enter a number:")] if isinstance(x,int) and x>0 and x%2 ==0]
Excuting this list comprehension ,will get you an empty list if occurs any illegal key-in like 0.1, 'abc',999.
code for best practice:
There is quite popular to take all validation expression into lambda for python, for example, like django so :
isPositiveEvenNum=lambda x: x if isinstance(x,int) and x>0 and x%2 ==0 else None
while not isPositiveEvenNum(input("please enter a number:")):
print "None Positive Even Number!"
this can also be writen as
isPositiveEvenNum=lambda x: (isinstance(x,int) and x>0 and x%2 ==0) or False
while not isPositiveEvenNum(input("please enter a number:")):
print "None Positive Even Number!"
to solve the input and raw_input difference between 2.x and 3.x:
import sys
eval_input =lambda str: input(str) if sys.version_info<(3,0,0) else eval(input(str))
then just call eval_input

Categories

Resources