【问题标题】:How to make a user input both a string and integer如何让用户同时输入字符串和整数
【发布时间】:2018-05-07 11:32:46
【问题描述】:

我正在尝试创建一款类似于游戏策划者的游戏。 我有一个部分,用户必须猜测数字或键入“退出”来停止游戏。我如何使代码允许整数和字符串输入? 代码是:

PlayerNum = int(input("Type your number in here:"))
if PlayerNum == "exit":
    print "The number was:",RandNum1,RandNum2,RandNum3,RandNum4
    print "Thanks for playing!
    exit()

如果有人可以提供帮助,那就太好了。 谢谢。 :D

【问题讨论】:

  • PlayerNum.isalpha()?

标签: python


【解决方案1】:

您可以使用 isdigit() 函数来检查输入是 int 还是 string。

让用户输入 "32" 然后 "32".isdigit() 将返回 True 但如果用户输入 "exit" 然后 "exit".isdigit() 将返回 False。

player_input = input("enter the number")
if player_input.isdigit():
   # Do stuff for integer
else:
   # Do stuff for string

【讨论】:

  • 感谢您的帮助:D
【解决方案2】:
PlayerNum = input("Type your number in here:")

你可以删除 int 以便它同时接受 integet 和 string 作为输入

【讨论】:

    【解决方案3】:

    整数和字符串分类是 Python 特有的(它们是函数)。当用户输入他们的响应时,系统会将其解释为标准输入(标准输入)。

    一旦用户输入标准输入并在 PlayerNum 变量下分配,您可以随意将其转换为 int/str/bytes。

    【讨论】:

      猜你喜欢
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2013-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多