How to identify operators using isdigit in python? - python-3.x

I am making a program to check if the input given by user is positive or negative.
I have used isdigit to print "wrong choice/input".If user inputs a string.
Program is working fine... but one block is not working that is of negative number.
Whenever I give a negative value it shows wrong choice because isdigit checks for integers in a string but not symbols.
How can I fix this?

You could first check the first character and if it's a minus sign only apply isdigit() to the rest of the string, ie:
# py2/py3 compat
try:
# py2
input = raw_input
except NameError:
# py3
pass
while True:
strval = input("please input a number:").strip()
if strval.startswith("-"):
op, strval = strval[0], strval[1:]
else:
op = "+"
if not strval.isdigit():
print("'{}' is not a valid number".format(strval))
continue
# now do something with strval and op
But it's much simpler to just try and pass strval to int(), which will either return an integer or raise a ValueError if the string is not a valid representation of an integer:
# py2/py3 compat
try:
# py2
input = raw_input
except NameError:
# py3
pass
while True:
strval = input("please input a number:")
try:
intval = int(strval.strip())
except ValueError:
print("'{}' is not a valid number".format(strval))
continue
# now do something with intval

Related

How do I figure out my issue with placing the "try" function?

So I have been struggling to find out what is wrong with my exception code which is to only accept strings but also display text whenever there are non string inputs between the brackets which depends on where I put the "try" and except functions.
The first code I have here which 'try' is before return, any strings entered in will be accepted into the function, however the except functions will not work whenever non-strings are entered between the bottom brackets.
'''
def string_processor(string):
countA = 0
if (string.isalpha()):
for c in string:
if c == "a":
countA = countA + 1
try:
return countA / len(string)
except AttributeError:
print("Please enter a string instead")
except IndexError:
print("Please enter a string with quotation marks ")
else:
print("Please only enter a string")
string_processor("000")
'''
The second code I have which I put "try:" can sort out some things such as AttributeErrors, but only strings with letters can be inputted between the brackets and any string that contains non-numbers are omitted from the function.
'''
def string_processor(string):
try:
countA = 0
if (string.isalpha()):
for c in string:
if c == "a":
countA = countA + 1
return countA / len(string)
except AttributeError:
print("Please enter a string instead")
except SyntaxError:
print("Please enter a string with quotation marks ")
else:
print("Please only put letters in your string")
string_processor("000")
'''
I request help to fix this problem so my program can get any type of string, and will process except functions for any non-string values.
I could be wrong understanding your question. But here are my suggestions to solve your problem.
First of all, I couldn't understand your code because the else statement is not reachable there, so I slightly changed it, but nothing dramatically changed.
def string_processor(string):
# This is a bad way to check the types and the value
try:
if string.isalpha():
# If string has a type "string" and contains only letters
return string.count('a')/len(string)
elif string.isnumeric():
# If string has numbers only
print("Please enter a string instead")
except:
if isinstance(string, list):
# If type of the "string" is actually a list
print('This is not a string, this is a list')
elif type(string) == tuple:
# If type of the "string" is actually a tuple
print('This is not a string, this is a tuple')
else:
# If none of the above worked
print('It is definitely not a pure string')
a = string_processor(234)
As I commented, this is not a good way to implement the solution, the better way may be this:
def string_processor_another(value):
# It is better to RAISE exceptions, not to print them
if not isinstance(value, str):
raise TypeError('This must be a string')
# So if we come to this step we can be sure that we work with strings, so we can use the methods
if value.isalpha():
# If string has a type "string" and contains only letters
return value.count('a')/len(value)
elif value.isnumeric():
# If string has numbers only
print("Please enter a string instead")
b = string_processor_another(234)
And if you are going to add some extra logics or you want to have a cleaner code, I'd suggest you to make this in oop way
class StringProcessor:
def __init__(self, string):
self.__check_for_str(string)
self.string = string
#staticmethod
def __check_for_str(string):
return isinstance(string, str)
# Here you can add short functions to make all of your logic statements
def check_is_numeric(self):
print(self.string.isnumeric())
def check_is_alpha(self):
print(self.string.isalpha())
sp = StringProcessor('1234')
sp.check_is_numeric() # True
sp.check_is_alpha() # False
Hope it helped.

Making a simple input verifier

what I want is to validate user input in python 3.9 under these conditions:
1-No numbers bigger than 100 allowed.
2-No strings allowed.
3-No floats allowed.
The code seems to work well only with string detection.
Thanks in advance.
import random
name = input("Type in your name, sir.\n")
print("Hi", name, "!")
print(
"\n\n\n##This is a guessing game, where you guess a number that is between zero and the top number that you choose.##")
print("\n\nEnter a top number, and don't exaggerate babe.")
n = input()
verifier = 5
while True:
try:
verifier = int(n)
except ValueError or int(n) > 100:
print("Nope, neither floats nor strings are allowed buddy...Also don't pick a big'ol num like a 100.")
n = input()
continue
Your max check isn't working since int(n) > 100 only runs if it wasn't able to convert the string into an integer.
Move the condition after verifier = int(n) and it should work.
Your code should look something like this:
while True:
try:
verifier = int(n)
if int(n) > 100:
raise ValueError() # Brings us to the except statement
break
except ValueError:
print("Nope, neither floats nor strings are allowed buddy...Also don't pick a big'ol num like a 100.")
n = input()
continue
By the way, you can probably just remove the verifier = int(n) line, assuming you don't use it for anything else.

How do I continue looping, even through an error? Python

I have two conditions in my story using the question that I made to ask the users.
The first condition is true and second condition is false. In the first condition, if it's true, I want the program to finish. In the second condition, if it's false, I want to loop back to the question that I asked.
I have the following code, but so far it will loop back if the first is true and the second is false.
Any ideas?
invalid = ValueError
def age():
user_input = input("Enter your Age")
try:
val = int(user_input)
print("Input is an integer number. Number = ", val)
except ValueError:
print("No.. input is not a number. It's a string")
while invalid:
age()
I'd make things easier and just use a boolean as your continuation flag, rather than the ValueError:
ask_again = True
def age():
user_input = input("Enter your Age")
try:
val = int(user_input)
print("Input is an integer number. Number = ", val)
ask_again = False
except ValueError:
print("No.. input is not a number. It's a string")
while ask_again:
age()
Does that look like what you want? Happy Coding!
The simplest way to execute a while loop is to just use while True and then break from the loop once the condition is satisfied
def age():
while True:
try:
val = int(input("Enter your Age"))
print("Input is an integer number. Number = ", val)
break
except ValueError:
print("No.. input is not a number. It's a string")
age()

How to verify if input is not a letter or string?

I'm writing a basic program in IDLE with a menu choice with options from 1 to 4.
If a user input anything else then a number, it gives a ValueError: invalid literal for int() with base 10: 'a'
How can I check if the input is not a letter, and if it is, print a error message of my own?
def isNumber (value):
try:
floatval = float(value)
if floatval in (1,2,3,4):
return True
else:
return False
except:
return False
number_choice = input('Please choose a number: 1, 2, 3 or 4.\n')
while isNumber(number_choice) == False:
number_choice = input('Please choose a number: 1, 2, 3 or 4.\n')
else:
print('You have chosen ' + number_choice + '.\n')
This will check if the number is 1,2,3 or 4 and if not will ask the user to input the number again until it meets the criteria.
I am slightly unclear on whether you wish to test whether something is an integer or whether it is a letter, but I am responding to the former possibility.
user_response = input("Enter an integer: ")
try:
int(user_response)
is_int = True
except ValueError:
is_int = False
if is_int:
print("This is an integer! Yay!")
else:
print("Error. The value you entered is not an integer.")
I am fairly new to python, so there might very well be a better way of doing this, but that is how I have tested whether or not input values are integers in the past.
isalpha() - it is a string method which checks that whether a string entered is alphabet or words(only alphabets, no spaces or numeric) or not
while True:
user_response = input("Enter an integer : ")
if user_response.isalpha():
print("Error! The value entered is not an integer")
continue
else:
print("This is an integer! Yay!")
break
This program is having infinite loop i.e. until you enter an integer this program will not stop. I have used break and continue keyword for this.

showing result of try except integer check as a string

I need a function to check that different user input variables are integers.
The results should be confirmed to the user at the end.
The check works in that it keeps looping until integer is typed in,
but cannot get the results to display...
def chkint(msg):
while True:
try:
n = input(msg)
return(int(n))
except ValueError:
print("Please enter an actual integer.")
number1 = input (chkint("Please enter first value:"))
number2 = input (chkint("Please enter second value:"))
results = (number1, number2)
print ("I have accepted: " + str (results))
No answer, so I just played about with this and hey presto, it works...
def chkint(msg):
while 1:
try:
n = input(msg)
return(int(n))
except ValueError:
print("Please enter an integer.")
number1 = chkint("Please enter first value:")
number2 = chkint("Please enter second value:")
results = [number1, number2]
print ("I have accepted: " + str (results))
Casting it to int() in a try: block is a good way to check a number. In your original attempt you were asking for an input whose message relied on further input.
Simplified version of the mistake:
def getMessage():
return input() # this asks the user what to ask the user for
input(getMessage()) # this waits for getmessage to finish before asking the user
Removing the input() statements was the easiest fix, as you did.
But a more readable fix would be to make chkint(msg) do nothing but return true or false based on whether or not the string was a number, like this
def chkint(msg): # returns true if the string can be converted, false otherwise
try:
int(msg)
except ValueError:
return False
return True

Resources