【问题标题】:Python: not all arguments converted during string formattingPython:并非所有参数都在字符串格式化期间转换
【发布时间】:2013-03-07 22:41:29
【问题描述】:

这段代码出错

print('type a whole number:')
n = input()
if n % 2 == 1:
    print('Odd');
else:
    print('Even');

我假设我必须对 if 语句中的变量 n 做一些特别的事情?我是 Python 初学者。

【问题讨论】:

  • Python 2.x 或 Python 3.x ???
  • @Schoolboy 肯定是py3.x,因为input()在py2.x中返回一个整数,而错误not all arguments converted during string formatting明确表明input()在这里返回了一个字符串。

标签: python string format


【解决方案1】:

首先将用户输入n 转换为整数。
即只需更改:

n = input()

收件人:

n = int(input())

另外,input() 可以将字符串作为参数,在输入之前打印。
所以,你可以改变

print('type a whole number:')
n = int(input())

n = int(input('type a whole number:'))

【讨论】:

    【解决方案2】:

    解决方法如下:

    n = int(input("type a whole number:"))
    

    由于input()返回的是字符串,所以需要先将其转换为int,使用int()

    【讨论】:

    • 在 Python 2.7 中 >>> type(input("type a whole number:")) type a whole number:23 <type 'int'>>>> type(raw_input("type a whole number:")) type a whole number:23 <type 'str'>
    • 因为就像@Ashwini 所说,在 Py 3.x 中 input() 返回一个字符串。
    【解决方案3】:

    你需要先将n转换为整数,在py 3.x中input()返回一个字符串。:

    n = int(input())
    

    【讨论】:

      猜你喜欢
      • 2015-10-28
      • 2013-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      相关资源
      最近更新 更多