'except ValueError' is not executing - python

I am trying to ask the user for a string only but whenever the user types an integer or a float, it does not execute the except ValueError code.
Here is my code:
word = input('Enter a string.')
try:
word1 = str(word)
print(word1)
print(type(word1))
except ValueError:
print('The value you entered is not a string.')

The function input always returns a string. you can check if the input is a number in one of the following ways:
Use build in methods in str Class:
word = input('Enter a string.')
# Check if the input is a positive integer without try except statements:
if word.isnumeric():
# The word contain only numbers - is an positive integer.
print("positive int")
Try convert the variable in try expect statement:
word = input('Enter a string.')
# Check if the input is a positive integer with try except statements:
try:
word = float(word)
print("the input is a float")
except ValueError:
print("the input is a string")

input() function in python always takes input as string only. So your code will never throw an exception.
The valueError will catch the error in this case -> int(word). Where word does not contain a pure number.
Always include your statements in double-quotes. Eg.
input("Enter the name: ")
Good, you asked this doubt. It's always good to ask for mistakes.

By defaults input function in python consider your input as "string " whatever enter code hereyou type it is string .
for converting your input into integer you have to type this code .
word = int(input('Enter a string.'))
try:
word1 = str(word)
print(word1)
print(type(word1))
except ValueError:
print('The value you entered is not a string.')
In this case your code is working .

Related

The catch_error_str function isn't catching errors when the input is a integer. - Python

Please don't be too harsh because I'm new to coding. The problem I'm having is that the function catch_error_str does not work. For example, when I enter "2" as an input then it says last_name is 2 instead of catching the error.
def catch_error_str():
unvalid = True
while unvalid:
try:
string = str(input())
unvalid = False
return string
except ValueError:
print("You must not enter any numbers")
def surname ():
print("What is the surname of the lead booker ")
last_name = catch_error_str()
print(last_name)
print("Welcome to Copington Adventure Theme Park's automated ticket system\nplease press any button to see the ticket prices.")
enter = input()
print("\nAdult tickets are £20 each \nChild tickets are £12 each \nSenior citizen tickets are £11 each")
surname()
Python don't have a problem to covert a number to a string and because of that, there is no error rasing.
You can try
def catch_error_str():
unvalid = True
while unvalid:
try:
string = str(input())
if not string.isalpha():
raise ValueError
unvalid = False
return string
except ValueError:
print("You must not enter any numbers")
The isalpha() method of string will check if the input not containing numbers and if so it will raise the value error.
The value that is returned from Input() is of type str therefore, the conversion won't generate an error that you can catch with ValueError. Instead you should try to check the type() of the variable. Also, you are requiring the input within the try. I would use something like this:
def catch_error_str():
unvalid = True
while unvalid:
string = input()
try:
string = float(string)
print("You must not enter any numbers")
except ValueError:
unvalid = False
return string
Since floats/ints can be converted to strings without any problem, I'm facing the problem the other way around. I am trying to convert it into a float, if I'm able to, it's because the value is numeric, hence the error. If I am not able to, then that means it will generate ValueError because it is text
Input returns a string even if the user input is a digit.
name = input(“Enter last name: “)
if name.isdigit():
unvalid = True
If the prompt argument is present, it is written to standard output without a trailing newline. 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.
https://docs.python.org/3/library/functions.html#input

Python: How to demand a string as input rather than a specific value

For the YourName input() I would like to get a value that's a string. Hence, it shouldn't be a float, int, etc. In this example I would like to replace "Sunny" with any value that's a string to make the while loop accept the input.
YourName = ''
while YourName != "Sunny":
print("Please type in your name")
YourName = input()
print(YourName + " is correct")
Thanks in advance, best
Sentino
As mentioned in the comments you could use something similar to the following:
YourName = input("Please enter your name: ")
while True:
if YourName.isalpha():
break
else:
print("Must enter string")
print("Please type in your name")
YourName = input("Please enter your name: ")
continue
isinstance() is a built-in function that checks to see if a variable is of a specific class, e.g. isinstance(my_var, str) == True. However, the Input() function always returns a string. Thus, if you want to make sure the input was all letters you want to use .isalpha(). You could also use Try/except. As #SiHa said this SO question has a great response.
As pointed out in the comments, this answer will not work if there is a space in the string. If you want to allow multiple name formats you can use Regex. for example you can do the following:
import re
YourName = input("Please enter your name: ")
while True:
if re.fullmatch(r"[a-zA-Z]+\s?[a-zA-Z]+", YourName) is not None:
break
else:
print("Must enter string")
print("Please type in your name")
YourName = input("Please enter your name: ")
continue
Using Regular Expressions will give you more control on the inputs than regular string methods. Docs, Python Regex HOWTO. re is a standard library that comes with python and will give you the most flexibility. You can use regex101 to help you test and debug.
What the re.fullmatch() will return a match object if found and None if not. It says the input can be any lower or uppercase letter with an optional space in the middle followed by more letters.
If you don't want to import a package then you can loop through your input object and check to see if all characters are a space or alpha using:
all([x.isalpha() | x.isspace() for x in YourName])
however this will not say how many spaces there are or where they are. It would be optimal to use Regex if you want more control.
It's possible that you're using Python 2.7, in which case you need to use raw_input() if you want to take the input as a string directly.
Otherwise, in Python 3, input() always returns a string. So if the user enters "3#!%," as their name, that value will be stored as a string (You can check the type of a variable by using type(variable)).
If you want to check to make sure the string contains only letters, you can use the method isalpha() and isspace() (in my example code, I'll assume you want to allow spaces, but you can exclude that part if you want to require one word responses).
Because these methods operate on characters, you need to use a for loop:
YourName =""
while YourName is not "Sunny" or not all(x.isalpha() or x.isspace() for x in YourName):
#You can pass a string as a prompt for the user here
name = input("please enter name")
print (YourName)
However, I should note that this check is totally redundant since no string containing a non-letter character could ever be equal to "Sunny".
As others have pointed out, input() always returns a string.
You can use the str.isalpha method to check the character is a letter.
YourName = ''
while True:
print("Please type in your name")
YourName = input()
failed = False
for char in YourName:
if not char.isalpha():
failed = True
if not failed:
break
Example:
Please type in your name
> 123
Please type in your name
> John1
Please type in your name
John
John is correct

How to check if user input is a string

I have two user inputs: in the first one user has to insert a text what is string type and in the second one to insert a number what is int type.
I used try/except ValueError, so user couln't insert a string where int is needed. Although ValueError wouldn't work when user inserts int where string is needed.
How can input value be false, when int is inserted, where str is asked?
This is my code now:
while True:
try:
name_input = input('Insert name')
name = str(name_input)
number = input('Insert number: ')
num = int(number)
except ValueError:
print('Wrong')
If you would like the whole name to be alphabetic you can simply add an if statement like this:
if not name.isalpha():
print("wrong, your name can only include alphabetic characters")
Or better fitting your short example:
if not name.isalpha():
raise ValueError
This will only accept input strings that don't contain any number at all.
If you would like to allow digits in your name as long as the name begins with a letter you could also have something like the following:
if len(name) < 1 or not name.isalnum() or not name[0].isalpha():
raise ValueError
This checks first whether the name is at least 1 character long, then it checks whether the whole name consists solely of alphabetic characters and numbers, followed by a final check to see if the first character is an alphabetic character.
A string with a number in it is still a valid string - it's a string representing that number as text.
If you want to check that the name is not a string composed just of digits, then the following code will work:
while True:
try:
name = input('Insert name: ')
if name.isdigit():
raise ValueError

Changing inputs into titles, issue with handling raw spaces

so I'm quite new to programming and I'm trying to learn python as a starter.
I'm trying to make a function that does multiple things (I'm going to use it for limiting inputs on names).
Rejects purely numerical inputs
Rejects inputs made purely of spaces
Rejects null inputs
Changes the input into a title
def debugstr(inputa):
inputa = inputa.replace(" ", "")
try:
int(inputa)
inputb = debugstr(input("Invalid input, please enter Alphabetic strings only: "))
except:
if inputa == "":
debugstr(input("Invalid input, please enter Alphabetic strings only: "))
else:
return inputa.title()
The issue that I have is that the code will only reject blank inputs on the first try when running the function, if something is rejected once and the user inputs a series of spaces again, then it will just accept it as an input.
Thanks for your time in advance! It's very appreciated :D
A more natural way of handling this (without calling the same function from within itself) is:
def make_title():
def get_user_input():
return input('Enter an alphabetic string: ')
while True:
s = get_user_input()
s = s.strip()
if not s:
print('blank input!')
continue
if s.isdigit():
print('contains only digits!')
continue
return s.title()
print(make_title())
Some notes:
Try not to repeat yourself (e.g. the duplicated error message in your code)
Python contains many useful string methods and s.isdigit() returns True if s contains only numbers
You can strip the whitespace from your input with s.strip() and if you're left with the empty string, '', if not s will be True (the empty string is equivalent to False.
In python 3, you can use isinstance to check if an object is a string.
word = input("Enter string: ")
def checkString(s):
if isinstance(s, str):
print('is a string')
elif not s:
print('empty')
else:
print('not a string')

How to ask the user for a specific string and loop until valid input is entered?

I am using Python 3.0. I'm trying to ask the user to enter the string 'Small', 'Medium' or 'Large' and raise an error if none of those are entered and then ask for input again.
while True:
try:
car_type = str(input('The car type: '))
except ValueError:
print('Car type must be a word.')
else:
break
Why doesn't this work? Even if a number is entered the program continues and comes to an error at the end.
You can simply do as follows:
valid_options = ['Small', 'Medium' , 'Large' ]
while True:
car_type = input('The car type: ') # input is already str. Any value entered is a string. So no error is going to be raised.
if car_type in valid_options:
break
else:
print('Not a valid option. Valid options are: ', ",".join(valid_options))
print("Thank you. You've chosen: ", car_type)
There is no need for any try and error here.
input always returns a str, so str(input()) never raises a ValueError.
You're confusing a string with a word. A string is just a series of characters. For example "123hj -fs9f032#RE##FHE8" is a perfectly valid sequence of characters, and thus a perfectly valid string. However it is clearly not a word.
Now, if a user types in "1234", Python won't try to think for you and turn it into an integer, it's just a series of characters - a "1" followed by a "2" followed by a "3" and finally a "4".
You must define what qualifies as a word, and then check the entered string if it matches your definition.
For example:
options = ["Small", "Medium", "Large"]
while True:
car_type = input("The car type: ")
if car_type in options: break
print("The car type must be one of " + ", ".join(options) + ".")

Categories