-1

If I have such a simple code

varry = 1
print(type(varry))

it gives me - class 'int'

But if I have this:

varry = input()
print(type(varry))

And I type 1, it gives me class 'str'

Tell me please - why is it so and how should I write a program so that it defines a variable I enter correctly as int, str or float?

1
  • The input() function will return whatever is entered as a string. Commented Aug 22, 2018 at 16:44

3 Answers 3

3

What you input to your program is always of type str. if you want Python to deduce the type of the input itself, use data = eval(input()) or, for more safety:

import ast 
data = ast.literal_eval(input())
Sign up to request clarification or add additional context in comments.

2 Comments

It works, thank you! But if I enter a string without "". like just an apple and not an "apple", it tells me "NameError: name 'apple' is not defined". While I enter "apple", it says class 'str'
apple is not a string, according to Python's syntax, while "apple" is.
3

The built-in function input always returns a string, regardless of whether that string might be comprised of solely numerical characters. If you are sure the result can represent a number, then convert it:

varry = int(input())

Now the type of varry will be int, assuming this conversion doesn't raise a ValueError

Comments

0
varry = int(input())

print(type(varry))

You have to convert it to int using int() method

2 Comments

The thing is - I want it to define what variables is entered. Like I dunno it in advance.
In python the type of a variable changes with assignment. If varry="hello" it is a string and in the next statement varry=7 it is of type int. I'm not sure about your intent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.