How do I figure out my issue with placing the "try" function? - python-3.x

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.

Related

How can I make my python script determine if a number is an integer or a floating point depending on the mode its set to?

I am trying to create a function that would take a user inputted number and determine if the number is an integer or a floating-point depending on what the mode is set to. I am very new to python and learning the language and I am getting an invalid syntax error and I don't know what to do. So far I am making the integer tester first. Here is the code:
def getNumber(IntF, FloatA, Msg, rsp):
print("What would you like to do?")
print("Option A = Interger")
print("Option B = Floating Point")
Rsp = int(input("What number would like to test as an interger?"))
A = rsp
if rsp == "A":
while True:
try:
userInput = int(input("What number would like to test as an interger"))
except ValueError as ve:
print("Not an integer! Try again.")
continue
else:
return userInput
break
The problem with the code you shared is :
The syntax error you mentioned is probably because the except clause has to be at the same indentation level as try, and same for if and else of the same if/else clause. All the code in the function should be indented 1 level too. Python requires all this to identify blocks of code.
You don't need to give 4 arguments to the getNumber() function if you're not using them. This isn't really a problem, but you'll have to pass it some 4 values each time you call it (for example getNumber(1,2,3,4) etc...) to avoid missing argument errors; and these won't matter because you're not doing anything with the given values inside the function - so it's a little wasted effort. I rewrote it in the example below so that you aren't dealing with more variables than you need - it makes the code clearer/simpler.
You also don't need break after a return statement because the return will exit the enitre function block, including the loop.
Try this and see if it makes sense - I've changed a lot of the code :
def getNumber():
while True:
try:
userInput = int(input("What number would like to test as an integer ? "))
return userInput
except ValueError as ve:
print("Not an integer! Try again.")
continue
print("What would you like to do?")
print("Option A = Interger")
print("Option B = Floating Point")
chosen_option = input()
if chosen_option == 'A':
integer_received = getNumber()
print(integer_received, "was an int !")
else:
print("You did not choose 'A' or 'B'")
To determine whether a number is a float or integer, you can use this approach
float is nothing but the integer with floating-point(.).
to determine this we first need to convert it to string and find does it contain a point or not.
number = input("Enter a numbeer\n")
if number.find(".") == -1:
# find will return -1 when the value is not in string
print("it is integer")
else:
print("it is float")

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 identify operators using isdigit in python?

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

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