简体   繁体   English

ValueError: ValueError: Int() 的无效文字在 Python 中以 10 为基数

[英]ValueError: ValueError: invalid literal for int() with base 10 in Python

It says ValueError.它说 ValueError。 I've tried using int('') as well.我也试过使用 int('') 。 Didn't work.没用。

first = []
a=int(input());

for i in range(0,a):
    ele = int(input());
    first.append(ele);

second = first[::-1];

th = [x + y for x, y in zip(first, second)];
print(th);

According to the official documentation , the class constructor for int is as follows.根据官方文档,int的类构造函数如下。

class int(x, base=10)

So a base of 10 is assumed (I guess because a decimal number system is the most prevalent) unless and otherwise you state something else.所以假设基数为 10(我猜是因为十进制数字系统是最普遍的),除非你另有说明。

So what should be x?那么x应该是什么?

Again as per the docs.再次根据文档。

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base.如果 x 不是数字或给定了基数,则 x 必须是字符串、字节或字节数组实例,表示以基数为基数的整数文字。

So the x should be an integer literal of that base.所以 x 应该是那个基数的整数文字。 If you supply an alphabet say 'A' for int like below, the 'A' can not be represented as an integer using a decimal number system.如果像下面这样为 int 提供字母表“A”,则“A”不能使用十进制数系统表示为整数。 Trying to do the below ..尝试做以下..

Num = int('A')
print(Num)

will get you an error ...会给你一个错误......

ValueError: invalid literal for int() with base 10: 'A'

However, if your number system (base) is hexadecimal then you can say base=16 and it will faithfully convert 'A' it into an integer.但是,如果您的数字系统(基数)是十六进制的,那么您可以说 base=16,它将忠实地将 'A' 转换为整数。 So the below ...所以下面...

Num = int('A', base=16)
print(Num)

gives ..给..

10

So please check what is your number system (base) is and see if the string (that you are trying to convert to an integer) makes sense for that particular number system.因此,请检查您的数字系统(基数)是什么,并查看字符串(您尝试转换为整数的字符串)对于该特定数字系统是否有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM