简体   繁体   English

为什么'user_input'总是一个字符串?

[英]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.我创建了一些代码来检查用户的输入是 integer、浮点数还是字符串,并且每次我使用 integer 或浮点数时,它仍然是字符串 Z78E6221F63983D135DZ681DB3。 Is there something really easy that I'm missing?我真的很想念一些简单的东西吗?

In your code, user_input is always a string because the input() function always returns string values.在您的代码中, user_input始终是一个string ,因为input() function 始终返回string值。 This is described in Python's documentation (emphasis mine):这在 Python 的文档中有所描述(重点是我的):

https://docs.python.org/3/library/functions.html#input 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. function 然后从输入中读取一行,将其转换为字符串(去除尾随换行符),然后返回。 When EOF is read, EOFError is raised.读取 EOF 时,会EOFError

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. 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作为字符串"1.2"而不是decimal值。

Your question title says pay_rate , which sounds like a monetary value.您的问题标题是pay_rate ,这听起来像是一个货币价值。 You must not represent monetary amounts (ie currency, money) with a floating-point type such as float . 您不得使用浮点类型(例如float )表示货币金额(即货币、货币)。 Instead use Decimal . 而是使用Decimal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM