Palindrome Program Cannot Recognize Other [duplicate] - python

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

Related

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

Invalid literal for int() with base 10: 'x' error in Python? [duplicate]

This question already has an answer here:
How do I check if input is a number in Python?
(1 answer)
Closed 4 years ago.
I'm working on a program that prompts a user for a number within a range of integers they've entered. If the number they enter is out of range, they're prompted to give another, and if they enter a letter instead they're prompted to change their answer as well. Here is what I've got:
def code_one(d, f):
s = input('Enter a number between' + str(d) + 'and' + str(f) + ': ')
s = int(s)
if int(d) <= s <= int(f):
return s
else:
while s < int(d) or s > int(f):
s = input(str(s) + 'is out of range. Please try again. ')
s = int(s)
if s < int(d) or s > int(f):
continue
else:
return s
while s.isdigit == False:
s = input(str(s) + 'is not a number. Please try again.' )
if s.isdigit == False:
continue
else:
return s
It works fine up until the line reading "while s.isdigit == False:" and then, if I input a letter instead of a number, I get the error "invalid literal for int() with base 10: 'x'", (the x being whatever letter I happen to enter). What can I do to fix this?
def code_one(d, f):
while True:
answer = input('Enter a number between %d and %d: ' % (d, f))
try:
answer = int(answer)
except ValueError:
print('%s is not a number. Please try again.' % answer)
continue
if d <= answer <= f:
return answer
else:
print('%d is out of range. Please try again.' % answer)

How to Input numbers in python until certain string is entered

I am completing questions from a python book when I came across this question.
Write a program which repeatedly reads numbers until the user enters "done". Once done is entered, print out total, count, and average of the numbers.
My issue here is that I do not know how to check if a user specifically entered the string 'done' while the computer is explicitly checking for numbers. Here is how I approached the problem instead.
#Avg, Sum, and count program
total = 0
count = 0
avg = 0
num = None
# Ask user to input number, if number is 0 print calculations
while (num != 0):
try:
num = float(input('(Enter \'0\' when complete.) Enter num: '))
except:
print('Error, invalid input.')
continue
count = count + 1
total = total + num
avg = total / count
print('Average: ' + str(avg) + '\nCount: ' + str(count) + '\nTotal: ' + str(total))
Instead of doing what it asked for, let the user enter 'done' to complete the program, I used an integer (0) to see if the user was done inputting numbers.
Keeping your Try-Except approach, you can simply check if the string that user inputs is done without converting to float, and break the while loop. Also, it's always better to specify the error you want to catch. ValueError in this case.
while True:
num = input('(Enter \'done\' when complete.) Enter num: ')
if num == 'done':
break
try:
num = float(num)
except ValueError:
print('Error, invalid input.')
continue
I think a better approach that would solve your problem would be as following :
input_str = input('(Enter \'0\' when complete.) Enter num: ')
if (input_str.isdigit()):
num = float(input_str)
else:
if (input_str == "done"):
done()
else:
error()
This way you control cases in which a digit was entered and the cases in which a string was entered (Not via a try/except scheme).

can we make this script shorter ?even odd checking

hi there i'm learning python
i like to know if this script can be better or shorter
import sys
g = 1
def trying():
q = input('enter (y or yes) to retry')
if not q == 'y' or q == 'yes':
return 0
while g == True:
try:
t = int(input('please enter an integer:'))
r = t % 2
if r == 0:
print('your number is even')
if trying() == 0:
g = 0
else:
print('your number is odd')
if trying() == 0:
g = 0
except ValueError:
print('sorry you need to enter numbers only')
If you want in shorter, here is my version..
while True:
try:
print('Your number is %s' % ('even' if int(input('Please enter an integer: ')) % 2 == 0 else 'odd'))
if input('Enter (y or yes) to retry: ') not in ['y', 'yes']: break
except ValueError:
print('Sorry you need to enter numbers only')
What you want here is a do-while loop. You can easily implement it by adding a break statement to a infinite while-loop. More on this topic can be found here.
Next thing, you have to add a try-except statement as there is a string to integer conversion is happening.
print('Your number is %s' % ('even' if int(input('Please enter an integer: ')) % 2 == 0 else 'odd'))
This statement will return "Your number is even" if the input is even else it will return "Your number is odd". This method is called python ternary operator.
Then you can wrap it with a print-function to print the returned string. Look here.
input('Enter (y or yes) to retry: ') not in ['y', 'yes']
This check whether the user input is not there in the given list. So if user input is neither "y" or "yes", while-loop will break.
Here is an example of how the code can be made simpler. Remember that code should rarely be repeated. In most cases, if you have repeating lines of code it can be simplified.
while True:
try:
t = int(input('please enter an integer:'))
if t % 2 == 0: print('your number is even')
else: print('your number is odd')
q = input('enter (y or yes) to retry')
if not (q == 'y' or q == 'yes'): break
except ValueError:
print('sorry you need to enter numbers only')
def trying():
question = input('enter (y or yes) to retry')
if not (q == 'y' or q == 'yes'):
return 1
return 0
while True:
try:
num1 = int(input('please enter an integer:'))
num2 = t % 2
if not num2:
print('your number is even')
else:
print('your number is odd')
if trying():
break
except ValueError:
print('sorry you need to enter numbers only')
You don't have to import sys in your program as you didn't used it and you don't have to. You don't have to store anything in a variable for a while loop. Just assigning True and breaking out will do. If you're looking for anything that is True (this includes an unempty list, string, and dictionaries; and numbers not equal to 0). You should make if var:. If the variable evaluates to True. The conditional block will be executed. This is a clearer syntax so it is recommended. Name your variables with words, not with letters. This will not make your code longer and it will make your code better.
This is all I can do with your code. If there is more, please state them.

Checking whether the user input is a number [duplicate]

This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 20 days ago.
I'm trying to compare a input that the user receives that checks if the input is actually a number. Here's what I have so far:
numstring = input("Choose a number between 1 and 10")
and then to compare I have it in a method like this:
def check(a):
if int(a) == int:
print("It's a number!")
else:
print("It's not a number!")
It always prints out that it's not a number, even though it is.
Goal of this program:
I'm making a guessing game:
import random
numstring = input("Choose a number between 1 and 10")
def check(a):
if int(a) == int:
print("It's a number!")
else:
print("It's not a number!")
if abs(int(a)) < 1:
print("You chose a number less than one!")
elif abs(int(a)) > 10:
print("You chose a number more than ten!")
else:
randomnum = random.randint(1, 10)
randomnumstring = str(abs(randomnum))
if randomnum == abs(int(a)):
print("You won! You chose " + a + "and the computer chose " + randomnumstring)
else:
print("You lost! You chose " + a + " and the computer chose " + randomnumstring)
check(numstring)
Thanks for any help! The actual code works, but it just fails at checking it.
You can just use str.isdigit() method:
def check(a):
if a.isdigit():
print("It's a number!")
else:
print("It's not a number!")
The above approach would fail for negative number input. '-5'.isdigit() gives False. So, an alternative solution is to use try-except:
try:
val = int(a)
print("It's a number!")
except ValueError:
print("It's not a number!")
int(a) and int are not equal because int() returns an integer and just int with no () is a type in python2.(or class in python3)
>>> a = '10'
>>> int(a)
10
>>> int
<type 'int'>
If you're only dealing with integers then use try-except with int as others have shown. To deal with any type of number you can use ast.literal_eval with try-except:
>>> from ast import literal_eval
>>> from numbers import Number
def check(a):
try:
return isinstance(literal_eval(a), Number)
except ValueError:
return False
>>> check('foo')
False
>>> check('-100')
True
>>> check('1.001')
True
>>> check('1+1j')
True
>>> check('1e100')
True
Try to cast an input to int in try/except block:
numstring = input("Choose a number between 1 and 10")
try:
a = int(numstring)
print("It's a number!")
except ValueError:
print("It's not a number!")
If you are using python 2, consider switching to raw_input() instead of input(). input() accepts any python expression and this is bad and unsafe, like eval(). raw_input() just reads the input as a string:
numstring = raw_input("Choose a number between 1 and 10")
try:
a = int(numstring)
print("It's a number!")
except ValueError:
print("It's not a number!")
Note that raw_input() has been renamed to input() in python 3.
Also see:
Python: user input and commandline arguments
Is it ever useful to use Python's input over raw_input?
What's the difference between raw_input() and input() in python3.x?
Hope that helps.

Categories

Resources