How can I determine if user input is a valid hexadecimal number? - python

#Hex Check
def Check():
while False:
for char in UserInput:
if char not in Valid:
print ('That is an invalid hex value.')
print('That is a valid hex value.')
return Check
UserInput=input('Enter a hex number: ')
Valid='1''2''3''4''5''6''7''8''9''10''A''B''C''D''E''F'
EDIT: I've tried this. When I enter a hex value e.g. B2 no message comes up.

Change line 6 to
Hex=int(input('Enter a hex number: '), 16)
This line would successfully parse any hexadecimal input (for example, '0x123f') and would throw a ValueError on an invalid input (such as 'hello').
ETA: Based on your comments, the following is all you need:
user_input = input('Enter a hex number: ')
try:
hexval = int(user_input, 16)
print 'That is a valid hex value.'
except:
print 'That is an invalid hex value.'
ETA: If you really have to have a Check function, this structure would be the best way to do it:
import re
def Check(s):
"""Check if a string is a valid hexadecimal number"""
# code for checking if it is a valid hex number here
user_input = raw_input("Enter a hex number: ")
if Check(user_input):
print 'That is a valid hex value.'
else:
print 'That is an invalid hex value.'
Since this is a homework question I'm not going to finish the answer- just know that the Check function has to return True if the string is a valid hex statement or False if the string is not.
There are many ideas among everyone's answers of how to do it, and you could indeed use a try/except statement like I do above. One of the best ways to do it would be to use regular expressions, which are a very powerful way to parse strings.

Investigate the regex library. Or do explicit cast to int then catch any errors and process them accordingly.

The only valid values for hex strings are 0-9, A-F . It should be possible to store these values in a list / array and then do a simple contains call. Something along the lines of this:
for char in userInput:
if not char in validTokens:
print 'invalid hex value'

Here is a nice, Python way to check your input for a valid hex number.
def Check():
while not Valid:
try:
Hex=int(raw_input('Enter a hex number: '), 16)
print('That is valid.')
return True
except ValueError:
print('That is an invalid entry.')
return False

I am answering this question from a Python philosophy point of view, because you have already received good answers, some of them involving try: .. except.
The Pythonic thing about using exception handling try: .. except is the way Python programmers seem to be encouraged to use it is, at least for me, a departure from exception handling in other languages.
In Python, you are encouraged to raise an exception, either explicitly using raise or more implicitly within the construct of try .. except.
When I posed a question a while back about how to deal with null integer values in a .csv file, I was encouraged to go ahead with the assignment to the Python integer variable within try: .. except, instead of testing first to test to see if the value was null.
The answer went on to say don't bother to test and then take action, use exception handling, because it is more Pythonic. Using try: .. except also appeared to consume fewer instructions.
That attitude got me to write more exception handling than I would have thinking using try: .. except was reserved only for when bad things happen.

The expression
string.translate(x, None, "0123456789abcdefABCDEF") == ''
is True iff x contains valid hexadecimal characters, or x is the null string.(You need to "import string".)
Obviously this can be used to validate that a string contains only characters from any given set (or is null).

Related

Why Is 'user_input' Always A String?

def user_input_checker(user_input):
if isinstance(user_input, int):
print('user_input is an integer.')
if isinstance(user_input, float):
print('user_input is a float point.')
if isinstance(user_input, str):
print('user_input is a string')
print('What is your input?')
user_input = input()
print('Input = %s'%user_input)
user_input_checker(user_input)
I had created some code to check if a user's input was an integer, a float point, or a string, and everytime I would put use an integer or a float point, it would still output that it was a string.
Is there something really easy that I'm missing?
In your code, user_input is always a string because the input() function always returns string values. This is described in Python's documentation (emphasis mine):
https://docs.python.org/3/library/functions.html#input
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
It's true that Python does not have statically declared types and Python has some type-juggling, but Python variables still have types that generally aren't "magic" and so if someone enters 1.2 into an input() prompt, it will still be returned as a string "1.2" and not a decimal value.
Your question title says pay_rate, which sounds like a monetary value. You must not represent monetary amounts (i.e. currency, money) with a floating-point type such as float. Instead use Decimal.

How to determine the type of input? [duplicate]

This question already has answers here:
How to accept the input of both int and float types?
(6 answers)
Closed 5 years ago.
I'm trying to make a factorial calculator.
Input and Expected output:: If the user input is a positive integer, I want the program to give the outcome. And if the user input is not a positive integer(negative integer, float, or string), I want the program to ask for the input again. Also, I want the program to end when the user input is 0.
Problem: Since inputs are always perceived as string data, I am stuck with coding according to the type of input.
It would be of great help if someone would give answers to this problem, as I am studying by myself.
If you want to ensure it's a positive integer, and if you want to keep asking for input as specified in your question, you'll need a few more control structures:
from math import factorial
def get_input():
while True:
try:
inp = int(input("Enter a positive integer> "))
if inp < 0:
raise ValueError("not a positive integer")
except ValueError as ve:
print(ve)
continue
break
return inp
print(factorial(get_input()))
This works by just trying to convert the input to an integer, and retrying if this fails. The continue statement is used to skip past the break. The try/except structure catches the error if it's not an integer, or the error explicitly raised if it's less than 0. It also uses the as feature of except to print a better indication of the error. It's encapsulated in a function to make things easier - I find factorial(get_input()) to be pretty expressive, with the added bonus of being more reusable.
This currently doesn't end when the user input is 0, as 0 is a perfectly valid input for factorial, although it should be easy enough to adapt to this with an if statement.
This program might be used like this:
Enter a positive integer> abc
invalid literal for int() with base 10: 'abc'
Enter a positive integer> 0.2
invalid literal for int() with base 10: '0.2'
Enter a positive integer> -5
not a positive integer
Enter a positive integer> 6
720
By the way, this code works according to EAFP - it just tries to convert to an integer, and handles failure. This is more idiomatic Python than first trying to determine if it could be an integer (LBYL).
If you're using Python 2, you'll need to change input to raw_input.
Check if input is positive integer check this link out along with the link provided by user #cricket_007 above. Combining those two information should get you in the right direction.
Try to think of it as an algorithm problem not as a Python problem, you may find a solution because in general every language has its functions and they all almost the same only with different name.
In python they are a function call isnumeric() and it returns true if every single character is a number or false if it's not.
str.isnumeric()
us it with a statement condition like if
if str.isnumeric()==true // so it's numeric
// what to do!!!!!
the best choice it to use while and if
while true
//read data as string
if str.isnumeric()==true
break; // this to break the while loop
hope this can help you

Sometimes get a ValueError from passing a float to int() method, but not always

Python newbie here. I've been messing around with flow control and have come across a situation I don't quite understand related to exceptions.
In the following code I want the user to enter an integer in a given range and, in the case of non-compliance, keep asking them until they give a valid value:
while True:
try:
x = int(raw_input("Pick an integer between 2 and 9. "))
except ValueError:
print "Please enter an integer!"
continue
else:
if 2 <= x <= 9:
print("Your number is {0}.").format(x)
break
else:
print "That's not between 2 and 9!"
continue
As far as I can tell, this code works exactly as I want it to. I've thrown every other type of input I can think of at it and it only lets you exit the loop when an integer from 2-9 is entered. Not even floats are accepted.
My question is, given that int() can be successfully called on floats,
>>> int(2.1)
2
why does this try/except construct raise the exception when the input is a float? If I run the code without the try/except statements and enter anything other than an integer, it throws an error and exits.
I'm running python 2.7 from windows powershell.
This is because raw_input returns a string.
Under the hood, when you call int, it actually calls an objects object.__int__() method. This is different from object to object.
For a float, this truncates a value (Rounds towards 0).
On a string, it tries to parse an int according to https://docs.python.org/3/reference/lexical_analysis.html#integer-literals (Which can't have a .).
The issue here is that you are calling int() on a string that could potentially contain a period. To fix this I would recommend you change the int() to float(). This should fix your problem
x = float(raw_input("Pick an integer between 2 and 9. "))
Not sure what version of Python you are using but if it is Python 3.0 or above you might want to carefully check the print statements in the following clips
except ValueError:
print "Please enter an integer!"
else:
print "That's not between 2 and 9!"
they are not formatted for 3.0 but will probably work ok if you use version 2.x
I think the other answers covered your original problem adequately so I will defer to them.. they know that area better than I.
Good Luck,
Poe

python 2.7 isnan() function not working

I am having a slight issue with math's .isnan() function in python. Pretty much, I have this code:
import math
diceChoice = raw_input('Which dice will you throw?\n 4 sides\n 6 sides\n 12 sides?\n>')
if math.isnan(float(diceChoice)):
print(str(diceChoice) + ' is an invalid choice')
and if diceChoice isn't a number (eg 'a') it gives me the error:
ValueError: could not convert string to float: a
If I don't convert it to a float, it gives me another error saying that it needs to be a float. I must be doing something wrong as the isnan function would be useless if it only accepts numbers. Can someone please help me
Thanks in advance
The float() function used on any other string other than a decimal number, 'nan', '-inf' or 'inf' (or slight variants of those strings) will throw a ValueError instead, because anything else is not a valid floating point value. math.isnan() only works on the special float value float('nan'), but it is not ever called if float() raises an exception first.
Use exception handling to catch that error instead:
try:
diceChoice = int(diceChoice))
except ValueError:
print(diceChoice, 'is an invalid choice')
I used int() instead because your input requires that the user enters a whole number.
Just to be explicit: float('nan') is a specific floating point value to signify the output of certain mathematical operations that are not an exception. It is never used to signify invalid input.
isnan() is really only used to check if a number doesn't have a finite value. Consider instead doing something like:
if not diceChoice.isdigit():
The error is raised because you attempt to convert a string to an integer with float('a'). Easier to just do the above.
NaN are used to define things that are not numbers in a floating point context like 0/0 or the square root of a negative number for example. You can use isdigit or something else.

Convert string literal to string or raise error, Python

I have a string, which may or may not contain a syntactically valid Python string literal. If it does, I want to convert it to the string it represents, otherwise I want to raise an error. Is there a better way to accomplish this than
# 'x' contains the putative string literal
s = ast.literal_eval(x)
if not isinstance(s, basestring):
raise ValueError("not a valid string literal: " + x)
In particular, because of the origin of this string, it could potentially contain the repr of a complex object, and I don't want to waste time parsing that and then throwing it away.
Another way to put it is that I want the behavior of float or int when applied to a string, only for, well, strings.
[Note: The existing question Python convert string literals to strings recommends ast.literal_eval, but that is what I am hoping to be able to beat.]
I think that you could use a regular expression. A syntactically valid Python string is:
'' on one line containing anything except ' preceeded by an even number of \
"" on one line containing anything except \n " preceeded by an even number of \
""" """ containing anything except """ preceeded by an even number of \
''' ''' containing anything except ''' preceeded by an even number of \
Theoretically you should be able to write a regex to match one of those, and I think that should work.
It might not be any faster or better than ast.literal_eval, even with a complex object.
Now that I think about it, you could simply do:
if x.lstrip().startswith(("'", '"')): #Might be a string
as a pre-filter.

Categories