NotASuperSpy
NotASuperSpy

Reputation: 53

Why Is 'user_input' Always A String?

def user_input_checker(user_input):

  if isinstance(user_input, int):
      print('user_input is an integer.')

  if isinstance(user_input, float):
      print('user_input is a float point.')

  if isinstance(user_input, str):
      print('user_input is a string')

print('What is your input?')
user_input = input()

print('Input = %s'%user_input)

user_input_checker(user_input)

I had created some code to check if a user's input was an integer, a float point, or a string, and everytime I would put use an integer or a float point, it would still output that it was a string. Is there something really easy that I'm missing?

Upvotes: 0

Views: 330

Answers (1)

Dai
Dai

Reputation: 155165

In your code, user_input is always a string because the input() function always returns string values. This is described in Python's documentation (emphasis mine):

https://docs.python.org/3/library/functions.html#input

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.

It's true that Python does not have statically declared types and Python has some type-juggling, but Python variables still have types that generally aren't "magic" and so if someone enters 1.2 into an input() prompt, it will still be returned as a string "1.2" and not a decimal value.

Your question title says pay_rate, which sounds like a monetary value. You must not represent monetary amounts (i.e. currency, money) with a floating-point type such as float. Instead use Decimal.

Upvotes: 2

Related Questions