【问题标题】:Im trying to input string in python can you teach me please我想在python中输入字符串,你能教我吗
【发布时间】:2017-02-09 10:14:09
【问题描述】:

我是编程新手。如果我在 Python 中使用 if else 语句输入字符串,如何得到错误消息。

x = int(input("Enter the no."))

if (x>5):
    print (x ,'Is greater than 5')
elif (x==str):enter code here
    print('Incorrect input')
elif (x==5):
    print (x ,'Is equal to 5')
elif (x<5):
    print (x ,'Is less than 5')
else:
    print (x ,'none of the above!')

【问题讨论】:

标签: python


【解决方案1】:

我不知道你是如何学习 Python 的,但要么你的源代码很糟糕,要么你跳得太快了。

问题

  1. 将您的输入转换为int
    在 Python 3 中,您通过input() 函数接收到的任何用户输入都被视为string。因此,当你做x = input()时,x的类型是string。通过将input() 函数与int() 函数包装在一起,您可以将此输出(应该是string)转换为int
    .

  2. 检查条件时,将x 直接与str 进行比较,这不会起作用。 strstring classx 是它的实例。如果要比较两者,显然必须使用 type() 函数 - type(x) == str

【讨论】:

  • 你能推荐我可以下载学习python的好教程视频吗?
  • 不用抱歉,我也自学了 Python,所以我只是建议您先迈出小步。也不,我不能,我最初像其他人一样使用 Codecademy.. 哈哈
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
  • 1970-01-01
  • 2014-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多