-2

Here is my code:

age = input("How old are you?: ")
print (age)
print (type(age))

Result:

How old are you?: 35
35
class 'str' <<--- This is problem!

But, If I use..

age = int(input("How old are you?: "))
print (age) 
print (type(age))

and entered "Alex"

How old are you?: alex
Traceback (most recent call last):
File "/Users/kanapatgreenigorn/Desktop/test.py", line 1, in age = int(input("How old are you?: ")) ValueError: invalid literal for int() with base 10: 'alex'

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • 1
    This is where validation comes in. If you're asking for an age, you *expect* a number. Don't cast the input, or throw it into a try/expect block and return an error if the type isn't what was expected. – Sterling Archer Apr 14 '17 at 17:06
  • 3
    Isn't that a useful thing instead of a problem? Do you want to consider "alex" a valid answer to the question "how old are you?" – trincot Apr 14 '17 at 17:07
  • 2
    Might want to check out http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float-in-python – Marshall Davis Apr 14 '17 at 17:49

6 Answers6

1

If you want it to return string then I think it does that by default but if you want it to return like a number or integer then you can put the int( in front of the input. You put in 'alex' and the reason why it came as an error was because 'alex' is a string. not an integer (which is int)

1

The string is the default of input. There are two options below to change it.

sample = input("Sample")
sample = int(sample)

or

sample = int(input("Sample")
James
  • 1,928
  • 3
  • 13
  • 30
0

Here's one way of making it an integer.

age = int(input("How old are you?: ")

This makes it so that whatever number is written as the answer will be converted to an integer.

The Laggy Tablet
  • 100
  • 1
  • 12
0

There is a problem with input() function that it consider everything as string.

you can use simple check for your usecase.

if age.isdecimal():
if age.isdigit():

that way you can move ahead with your program without any error.

-1

#is simple but it's works

x = input()

if type(x) is str: try: x = int(x) except: TypeError

-1

In Python, we use the built-in input() function to receive input from the user. The input function converts any value that you enter into a string. If you enter an integer value into the input() function, it will be automatically converted into a string.

For example:

height = input("what is your height?: ")
print (height)
print (type(height))
Digital Farmer
  • 1,705
  • 5
  • 17
  • 67