并非所有参数都在字符串格式化过程中转换.没有 % 变量 [英] not all arguments converted during string formatting.. NO % variables

查看:57
本文介绍了并非所有参数都在字符串格式化过程中转换.没有 % 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

x = input()y = 1打印 (x)而 1 == y:如果 x == 1:y == y + 1elif x % 2 == 0: #evenx = x//2打印 (x)别的:x = 3 * x + 1打印 (x)

如果您知道 Collat​​z 猜想是什么,我正在尝试为此制作一个计算器.我想将 x 作为我的输入,这样每次我想尝试一个新数字时,我都不必更改 x 的数字并保存.

我得到以下错误

<块引用>

TypeError: 并非所有参数都在字符串格式化过程中转换'在第 7 行.

请帮助一个菜鸟.

解决方案

问题在于你接受用户输入:

x = input()

现在 x 是一个 str.所以,在这一行:

 elif x % 2 == 0: #even

% 运算符 充当字符串插值运算符.

<预><代码>>>>mystring = "这里是一个字符串:%s,这里是一个 int: %d" % ('FOO', 88)>>>打印(我的字符串)这是一个字符串:FOO,这里是一个整数:88>>>

但是,您提供的 input 没有格式说明符,因此:

<预><代码>>>>没有格式说明符的字符串..." % 10回溯(最近一次调用最后一次):文件<stdin>",第 1 行,位于 <module>类型错误:并非所有参数都在字符串格式化期间转换>>>

您需要将用户输入转换为 int 以便 % 运算符执行模运算.

x = int(input())

现在,它会做你想做的:

<预><代码>>>>x = int(input("给我一个整数!"))给我一个int!88>>>% 108>>>

x = input()
y = 1 
print (x)
while 1 == y:
if x == 1:
    y == y + 1
elif x % 2 == 0: #even
    x = x // 2
    print (x)
else:
    x = 3 * x + 1
    print (x)

If you know what the Collatz conjecture is, I'm trying to make a calculator for that. I want to have x as my input so I don't have to change x's number and save every time I want to try out a new number.

I get below error

TypeError: not all arguments converted during string formatting' at line 7.

Please help a noobie out.

解决方案

The problem is that you take user input:

x = input()

Now x is a str. So, on this line:

    elif x % 2 == 0: #even

The % operator acts as a string interpolation operator.

>>> mystring = "Here goes a string: %s and here an int: %d" % ('FOO', 88)
>>> print(mystring)
Here goes a string: FOO and here an int: 88
>>>

However, the input you gave does not have a format specifier, thus:

>>> "a string with no format specifier..." % 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
>>>

You need to convert your user input into an int for the % operator to perform the modulo operation.

x = int(input())

Now, it will do what you want:

>>> x = int(input("Gimme an int! "))
Gimme an int! 88
>>> x % 10
8
>>>

这篇关于并非所有参数都在字符串格式化过程中转换.没有 % 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆