String Check with if Statement in Python - python

I want to check input is an equal to string or not. But, my code cannot see if statement. I think the problem is in if statement equation:
name = input("Name: ")
if name != str:
print("Please enter letter answer ...")
name = str(input("Name: "))
else:
print(input(name))
I guess I cannot write name != str. But I don't know how to check input is equal to string. ???

First of all, you can't check an input string against a type str. inputs will always be of type str. If you want to check for strings in general, you can use type(var) == str.

input will always return a string, so you don't have to check if it is a string.
Also, this line: print(input(name)) asks for input again, you probably just want print(name)
This code should work just fine for what you would want:
name = input("Name: ")
print(name)
If you want the name to not include any numbers or spaces, so it is just a single name, you can try isalpha():
if name.isalpha():
pass # Do your stuff with the name here

I would recommend using isinstance(object, type) function because it is a boolean function already
for example: if isinstance(name,str):
you can also use the type() function if you want to use an approach more like what you are already using. The type() function can be useful overall
for example:
if type(name) != str:
print("Error; name is ",type(name))

In Python, Whatever you enter as input, the input() function converts it into a string. If you enter an integer value, still it will convert it into a string.
Using isaplha() like #funie200 said:
while True:
name = input("Name: ")
if name.isalpha():
print(name.title)
break
else:
print("Please enter your name...")

Related

How to give an error output when there's not enough values given to input in Python?

There's a part of my schoolwork. I need to give an error output when user doesn't give an second input, but as you know python gives an error itself when you don't give the second output. Is there any way to do that or do I have to change my implementation?
I have to check the second argument that's why I am getting the arguments seperately.
I tried this but obviously it didn't work:
option, person = input("Choose an option and person: ").split()
if person==None:
print("Missing argument")
Also sorry for my poorly written code I just started learning..
Hope the below code helps :)
try:
option, person = input("Choose an option and person: ").split()
print(option, person)
except ValueError:
print("Missing argument")
either wrap the line that throws an error in a try: except block or don't do the tuple unpacking on the same line:
data = input("Choose an option and person: ").split()
if len(data) != 2:
raise ValueError("RELEVANT ERROR HANDLING HERE")
else:
option, person = data
note that typing "a me b" also causes problems so checking that the length is exactly 2 is relevant instead of just >1
How about this? Treat the "rest" part as a list and check if its length is zero.
option, *person = input("Choose an option and person: ").split()
if len(person) == 0:
print("Missing argument")
Hope this would help!
data=input("Choose A and B: ").split()
if len(data)!=2:
print("Missing argument")
else:
A=data[0]
B=data[1]
print(A)
print(B)

Python cannot ignore str when input is int()

SO I have a program where the input is in an int, but when the user enters a str, the program crashes. I want the program to ignore any str that it can't convert to an int. I tried declaring a variable that said type(input). Then, I added an if statement:
if (variable) == str:
print(oops)
Remember I declared the input as an int. So I don't know.
Thank you.
You can use exceptions for this. You get a Value Error when you try to convert a string input to int. By enclosing it in a try clause here, it is telling that if a Value Error arises, you can ignore it. For now I've used the pass statement, but if there's something else you want to do if the input is a string, you can add it there.
try:
x = input()
value = int(x)
print(value)
except ValueError:
pass
You can use try-except to handle the case.
try:
value = int(input())
except ValueError:
print("Input is not an int type")
pass
In python you can call isinstance() on the variable passing the datatype you want to check for-
sent = 'your_string'
num = 24
isinstance(sent, int) # returns False
isinstance(num, int) # returns True
isinstance(sent, str) # returns True
isinstance(num, str) # returns False
Applicable with other data types too!
So a simple-
if not isinstance(str, int):
print('Only integer values accepted')
if my_input.isdigit():
int(my_input)
# your code goes here
else:
print('oops')
exit() # maybe you like to exit
You could do something like
input_number = input("Enter your number")
if type(eval(input_number)) == int:
#Do stuff
else:
print('Sorry that is an invalid input')
I also noticed you said
Remeber I declared the input as an int
Python is not statically typed, so you don't have to declare a variable as a certain data type, and along with that even if you do, their type can still be changed.
You can use str.isnumeric() to check if input is of int type or not. THis is better than using try..except
input_number = input("enter a number: ")
if input_number.isnumeric():
input_number = int(input_number)
# do magic

is it bad practice to overwrite a variable in a different datatype python

I was wondering when I was input validating in python whether it is good practice to overwrite a variable in a different data type, example:
x = "initialise"
while x == "initialise":
try:
x = int(input("what is the number "))
except ValueError:
print ("it has to be a number\n")
print (x)
if it is bad practice then can you tell me a different way in which I can input validate this if it is ok then can you help me aswell? thanks.
In your particular example, you should use the special None keyword when initializing a variable without a value.
In general, try not to use the same variable for multiple datatypes.
Is this what you intended to do..?
x = "initialise"
guess_value = None
while guess_value != x:
try:
guess_value = eval(input("what is the number: "))
except NameError:
print ("it has to be a number\n")
print (guess_value)
Regarding the overwriting the data type, it doesn't matter as the variable name being assigned to new data type. Only thing what you need to make sure is that the new data type works for your program.

Python 3 allowing only one input data type

I want to make this program print "Only str type supported" when 'name' gets any data type that isn't str. What should i change in this code?
while True:
name =(input("Whats ur name?"))
if name == 'Richard':
print('ok')
break
elif name == "gosha":
print('FEUER FREI! "BANG BANG BANG BANG"')
else:
print('denied')
while True:
name =(input("Whats ur name?"))
check = True
for ele in name:
try:
fl = float(ele)
nu = int(ele)
print("Only str type supported")
check = False
except:
pass
if check:
if name == 'Richard':
print('ok')
break
elif name == "gosha":
print('FEUER FREI! "BANG BANG BANG BANG"')
else:
print('denied')
It checks individual characters of the name and tries to convert them to float or int. If a value can be converted, it fails, throws the error and asks for name again
For what i know, all input is a string, but I understand that what you want is to only receive letters and no numbers in the input. In that case, you can check each element of the string to see if they are numbers, and if one is found, return the error message.
To check it you would have to use:
for c in name:
if c.isdigit():
print("Only str type supported")
break
This will iterate through the input string and check if any of the elements on it is a number.
EDIT: you could just use name.isalpha() to check if all the characters are letters. Would be easier to read and eliminates the unnecessary loop.
You can branch on the type of name such as:
if type(name) is not str:
print('Only str type supported')
or
if not isinstance(name, str):
print('Only str type supported')
But as others have pointed out, input() will always return a str.
https://docs.python.org/3/library/functions.html#input
Your current question is hard to answer. The input function will always return a string. That string might be a "1" or at "3.14159" or empty "" but it will always be a string.
When you say you want it to only support string types, maybe you mean you want to check if the given input can be converted to an int, a float, or is empty?
If that's the case use try and except and rely on the cast to int or float failing to "prove" it's a string by eliminating it's ability to be a different type.
Add additional type checks as needed to make your logic more robust.
Do something like this:
while True:
name = input("Whats ur name? ")
try:
float(name)
int(name)
print("I only support strings that are names")
break
except ValueError:
pass
print("It's not a float or an int so it's a string!")

Python's type() function and its 'if' related problems

So I have the following code:
user_input = raw_input("Enter an integer, string or float:")
input_type = type(user_input)
if input_type == "str":
print "Your string was %s." % user_input
elif input_type == "int":
input_type = int(input_type)
print "Your integer was %d." % user_input
elif input_type == "float":
input_type = int(input_value)
print "Your float was %d." % user_input
else:
print "You did not enter an acceptable input."
This does not work — I believe because of the if — so I changed it to be:
if "str" in input_type
and "int" for the float and integer, but get an error:
Traceback (most recent call last):
File "types.py", line 4, in <module>
if "str" in input_type:
TypeError: argument of type 'type' is not iterable
Why do I get this and how can I fix it?
There are a number of problems here.
user_input = raw_input("Enter an integer, string or float:")
input_type = type(user_input)
Since raw_input always returns a string, input_type will always be str here.
if input_type == "str":
print "Your string was %s." % user_input
input_type will be str—that is, the actual object representing the string type—not "str", which is just a string. So, this will never be true, and neither will any of your other tests.
Changing this to:
if "str" in input_type:
… can't possibly help anything, unless you're expecting input_type to be either a collection of strings, or a longer string with "str" in the middle of it somewhere. And I can't imagine why you'd expect either.
These lines:
input_type = int(input_type)
… are trying to convert the input_type—which, remember, is a type, like str or int, not the value—to an integer. That can't be what you want.
These lines:
print "Your integer was %d." % user_input
Are printing the original string you received from the user, not the thing you converted to an int. This would work if you used %s rather than %d, but it's probably not what you were trying to do.
print "Your float was %d." % user_input
Even if you fix the previous problem, you can't use %d to print floats.
Next, it's almost always a bad idea to test things by comparing types.
If you really need to do it, it's almost always better to use isinstance(user_input, str) not type(user_input) == str.
But you don't need to do it.
In fact, it's generally better to "ask forgiveness than permission". The right way to find out if something can be converted to an integer is to just try to convert it to an integer, and handle the exception if it can't:
try:
int_value = int(user_input)
print "Your integer was %d." % int_value
except ValueError:
# it's not an int
First of all, "does not work" is not useful. Please in the future explain exactly how it's not working, what you expect and what you get that is unsatisfactory.
Now to your problem: raw_input will always return a string. It is up to you to see if contents of that string conform to something that looks like an integer or a float, and convert accordingly. You know how to convert; the conformity testing would normally be done through a regular expression.
You would need to use isinstance and input to get your code to do what you expect as follows:
user_input = input("Enter an integer, string or float:")
if isinstance(user_input, str):
print "Your string was %s." % user_input
elif isinstance(user_input, int):
print "Your integer was %d." % user_input
elif isinstance(user_input, float):
print "Your float was %f." % user_input
else:
print "You did not enter an acceptable input."
raw_input always returns a string.
When using input, you must include ' or " around a string input. Also, never use input like this because it can be very dangerous. Use the try except method suggested by abarnert.
While I don't think this is a true duplicate, Differences between isinstance() and type() in python contains a very relevant answer and is good to read.
You would ultimately want to write a try/except that treats the data appropriately.
if isinstance(user_input, str): #or basestring, if you prefer, but Python 3 apparently doesn't use it
useThisLikeAString(user_input)
try:
intInput = int(user_input)
useThisLikeAnInt(user_input)
except TypeError:
useThisLikeSomethingElse(user_input)
The accepted answer is totally right, in other words, but the link to that discussion is worthwhile.
Add another variable to the code with value as string and do the type compare of that with other variables.
a="test"
type(a)==type(user_input)
This will be simpler.

Categories