【问题标题】:Is it possible to make the type of raw_input an integer or string depending on the input itself?是否可以根据输入本身将 raw_input 的类型设为整数或字符串?
【发布时间】:2021-03-15 05:02:38
【问题描述】:

我正在尝试制作一个用户猜数字的猜数字游戏。理想情况下,我想将数字的整数和字符串版本都作为有效答案。据我所知,我必须将 raw_input 设置为整数或将其保留(作为字符串),然后创建一个 if 语句,如果输入与起始数据类型不同,则将其转换为整数或字符串。如果 %s 用于字符串但 %d 用于整数,我也对如何使用字符串连接格式化 else 语句感到困惑。对于我在帖子或代码中犯的任何新手错误,我深表歉意,我几周前才开始。这是我的代码中让我绊倒的部分:

call = int(raw_input('Guess: ')) #defining for use outside of the function definitions

if call.isalpha():
  str(call)

def call_and_response():
  if call == 76 or call.lower() == 'seventy-six':
    print 'Fantastic! 76 is correct. \nThank you for playing!'
  else:
    print 'Good try, but %s is incorrect.' %(call)
      
call_and_response()

【问题讨论】:

  • 你为什么还在使用 Python 2.7?
  • @Barmar 必须,这是我的计算机科学入门课程。

标签: python string python-2.7 integer


【解决方案1】:

使用isdigit() 判断输入是否为数字。

call = raw_input('Guess: ')
if call.isdigit():
    call = int(call)
    correct = call == 76
else:
    correct = call.lower() == 'seventy-six'
if correct:
    print 'Fantastic! 76 is correct'
else:
    print 'Good try'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-28
    • 2013-04-25
    • 2019-04-07
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多