I want to accept data from the user in int format..but the .get() method returns a str object.
using IntVar also is not helping. the following is somewhat what i want to do:
inp = Entry(master)
#some code here
num = inp.get()
if num >5:
#do something
Entry.get() returns a string. use int to convert the string into an integer.
if int(num) >5: #do something
Of course, this may raise an Exception if the string can't be converted to an integer. For example, if the user enters "Hello" instead of a number, or just doesn't write anything at all.
Related
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
So i have a code that changes the text of a class, but instead of manually entering the number, i would like the number to be equal to whatever X is, and convert that number into a string if thats what needs to be done
try:
newButton = WebDriverWait(driver, 100).until(
EC.presence_of_element_located((By.CLASS_NAME, "btn-full")))
finally:
driver.execute_script('arguments[0].innerHTML = "X";', newButton)
driver.execute_script("arguments[0].setAttribute('class','NEWBUTTON')", newButton)
How do i make sure its made in such a way that it takes a variable that holds an integer value, and its written out in place of the X
Well you can pass it as arguments[1] like this:
x = #some number
driver.execute_script('arguments[0].innerHTML = arguments[1];', newButton, x)
If you want it to be an int you can leave it as it is, but if you want it as a string then just convert it wherever you want and pass it into the method.
The arguments[n] is the (n+2)'nd argument you pass into the method execute_script().
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!")
i am making a python script that talks back to just for fun and i want it to pick a random subject to talk about each time here is a snippet of my code
def randsub():
rand = random.randrange(1,3)
rand.toString()
randsub = "sub" + rand
randsub()
but it keeps giveing me this error
TypeError: Can't convert 'int' object to str implicitly
Put the functions in a list, then use the random.choice() function to pick one at random for you. Functions are just objects, just like any other value in Python:
import random
def sub_hello():
print('Well, hello there!')
def sub_nice_weather():
print("Nice weather, isn't it?")
def sub_sports():
print('What about them Broncos, eh?')
chat_functions = [sub_hello, sub_nice_weather, sub_sports]
randsub = random.choice(chat_functions)
randsub()
You got your specific error because you tried to concatenate an integer with a string ("sub" is a string, rand an integer); you'd normally convert the integer to a string first, or use a string template that supports converting other objects to strings for you (like str.format() or str % (values,)). But the string doesn't turn into a function, even if the string value was the same as a function name you happen to have defined.
i am learning python from code academy, and i'm trying to complete their review assignment.
I am supposed to define a function, and then set up a if/else loop to check the type of input i get, and then return either absolute value of an int/float or an error message.
I tried to look at similar questions, but i don't understand those codes are a lot more complicated than i can understand O_O. I looked at the function module lessons again, but i think i followed the function making pattern correctly ? Is there supposed to be an extra line before i call the function ? I tried to keep going, but then i am gettnig this same error message in the other exercises.
I would appreciate any responses :)
def distance_from_zero(thing):
thing = input
if type(thing) != int or float:
return "Not an integer or float!"
else:
return abs(thing)
distance_from_zero(thing)
Are you trying to use the input function to get a value from the user ?
if so, you must add parenthesis to it:
thing = input()
# If you're using python 2.X, you should use raw_input instead:
# thing = raw_input()
Also, you don't need the input parameter if that's what you're trying to do.
If you do mean input to be a parameter, then you're trying to use variables before defining them. distance_from_zero(thing) can't work since thing hasn't been defined outside your function, so you should either define that variable first or call it with a litteral value:
thing = 42
distance_from_zero(thing)
# or
distance_from_zero(42)
thing isn't defined when you pass it to the distance_from_zero function?
def distance_from_zero(input):
if type(input) != int or float:
return "Not an integer or float!"
else:
return abs(input)
thing = 5
distance_from_zero(thing)
You do not define the thing. Please try
def distance_from_zero(thing):
if type(thing) != int or float:
return "Not an integer or float!"
else:
return abs(thing)
thing = 1
distance_from_zero(thing)
Or your meaning is this, accepting the user input?
def distance_from_zero():
thing = int(input())
if type(thing) != int or float:
return "Not an integer or float!"
else:
return abs(thing)
distance_from_zero()
And your code if type(thing) != int or float: will always go to True for it is if (type(thing) != int) or float. Change it to if not isinstance(thing, (int, float)):.