|
cwa1110 0 / 0 / 0 Регистрация: 27.04.2019 Сообщений: 113 |
||||||||
|
1 |
||||||||
Как исправить следующую ошибку?18.11.2019, 00:38. Показов 2337. Ответов 6 Метки abc pascal, pascal abc, pascal abc net, pascalabc, pascalabc.net (Все метки)
Написал следующий код для общего понимания, он возводит в степень необходимое число, но для больших чисел (больших чем позволяет переменная int64) он не работает. Если использовать biginteger, то выдает ошибку. Как это можно исправить? (p.s. все должно остаться особенно цикл for, так как в другом коде его никак не заменить, здесь он, чтобы лишь понять как можно это реализовать для больших чисел) Работающий код:
Не работает:
0 |
|
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
18.11.2019, 00:38 |
|
Ответы с готовыми решениями: Как исправить ошибку PROGRAM EXAMPLE; Как исправить ошибку Как исправить ошибку Как исправить ошибку? 6 |
|
Пс 254 / 147 / 69 Регистрация: 29.07.2018 Сообщений: 1,177 |
||||
|
18.11.2019, 17:21 |
2 |
|||
|
cwa1110, попробуйте
0 |
|
0 / 0 / 0 Регистрация: 27.04.2019 Сообщений: 113 |
|
|
18.11.2019, 17:39 [ТС] |
3 |
|
попробуйте Все равно это маленькое значение, нужно с biginteger как то делать, хм…
0 |
|
2182 / 1310 / 498 Регистрация: 07.04.2017 Сообщений: 4,569 |
|
|
18.11.2019, 17:58 |
4 |
|
нужно с biginteger как то делать Зачем? Кроме того, если у вас счётчик
0 |
|
cwa1110 0 / 0 / 0 Регистрация: 27.04.2019 Сообщений: 113 |
||||
|
18.11.2019, 18:01 [ТС] |
5 |
|||
|
Зачем? Как тогда в степень возводить
Выдает ошибку: Нельзя преобразовать тип System.Numerics.BigInteger к integer
0 |
|
Sun Serega 2182 / 1310 / 498 Регистрация: 07.04.2017 Сообщений: 4,569 |
||||
|
18.11.2019, 18:01 |
6 |
|||
|
Для целых —
0 |
|
5059 / 2633 / 2346 Регистрация: 10.12.2014 Сообщений: 9,997 |
|
|
19.11.2019, 04:28 |
7 |
|
Для дробных Дробные — это числа вида ½, ⅓ и т.д. (Оно и в понятии „через дробь“ ;–)
1 |
Автор оригинала: Team Python Pool.
Python-это особый язык, который позволяет очень хорошо обрабатывать ошибки и исключения. Имея тысячи известных исключений и возможность обрабатывать каждое из них, все ошибки легко устраняются из кода. Имея это в виду, мы обсудим ошибку Invalid literal for int() with base 10 (недопустимый литерал для int()) в python.
Ошибка Invalid literal for int() with base 10 возникает при попытке преобразовать недопустимый объект в целое число. В Python функция int() принимает объект, а затем преобразует его в целое число при условии, что он находится в удобочитаемом формате. Поэтому, когда вы пытаетесь преобразовать строку без целых чисел, функция выдаёт ошибку. Эта ошибка относится к категории ValueError, так как значение параметра недопустимо.
ValueError в Python происходит, когда мы передаем неподходящий тип аргумента. Iнедопустимый литерал для int() с базой 10 ошибка вызвана передачей неверного аргумента функции int (). ValueError возникает, когда мы передаем любое строковое представление, отличное от int.
ValueError в Python возникает, когда мы передаем неподходящий тип аргумента. Ошибка недопустимого литерала вызвана передачей неверного аргумента функции int(). Если мы передаем любое строковое представление, отличное от представления int, то генерируется ValueError.
Давайте разберемся в этом подробнее!
ValueError: invalid literal for int() with base 10
Это сообщение об ошибке говорит, что существует недопустимый литерал для целого числа по основанию 10. Эта ошибка означает, что переданное значение не может быть преобразовано.
Рассмотрим пример:
Выход
Может случиться так, что мы можем подумать,что при выполнении приведенного выше кода десятичная часть, то есть “.9”, будет усечена, давая выход 1. Однако этого не происходит, поскольку функция int( ) использует десятичную систему счисления в качестве основы для преобразования. Это означает, что база по умолчанию для преобразования равна 10. В десятичной системе счисления мы имеем числа от 0 до 9. Таким образом, int() with может преобразовывать только строковое представление int, а не поплавки или символы.
Может показаться, что при выполнении вышеуказанного кода десятичная часть, т.е. «.9», будет усечена, давая на выходе 1. Однако этого не происходит, поскольку функция int() использует десятичную систему счисления в качестве основы для преобразования. Это означает, что основание для преобразования по умолчанию равна 10. В десятичной системе счисления мы имеем числа от 0 до 9. Таким образом, int() с основанием = 10 может преобразовывать только строковое представление целых чисел (int), а не дробных (float) или символы (char).
Давайте рассмотрим несколько примеров, где эта ошибка может возникнуть:
Пример 1:
В этом примере значение “python pool” – это строковое значение, передаваемое функции int(), которое приводит к ошибке.
Пример 2:
Поскольку значение, которое мы использовали здесь, является float внутри строки, это приводит к ошибке недопустимого литерала для int().
Пример 3:
В этом примере мы получаем ошибку, так как использовали список внутри строки.
Пример 4:
Ошибка invalid literal для int() возникает из-за того, что мы использовали кортеж внутри строки.
Пример 5:
Здесь мы использовали словарь внутри строки, который приводит к ошибке.
Пример 6:
Ошибка возникает в этом коде, так как мы использовали пустую строку в функции int().
Разрешение ошибки: invalid literal for int() with base 10:
Использование float() для преобразования десятичных чисел:
Здесь мы сначала преобразовали строковое представление в float с помощью функции float(). Затем мы использовали функцию int() для преобразования его в целое число.
Использование try-catch для разрешения invalid literal for int() with base 10
try:
("12.1")
except:
print("Error in converting to string")
Здесь мы использовали конструкцию try-catch, чтобы избавиться от ошибки invalid literal for int() with base 10. Если ошибка возникает внутри блока try, она перехватывается в блоке catch, тем самым предотвращая ошибку.
Использование isdigit():
x="12"
if x.isdigit():
x=int(x)
print(type(x))
<class 'int'>
В этом примере мы сначала убеждаемся, что содержимое внутри строки является целочисленным, используя метод isdigit(). В результате ошибка не возникает.
Использование isnumeric():
x="12"
if x.isnumeric():
x=int(x)
print(type(x))
<class 'int'>
isnumeric() это метод строки который возвращает логическое значение, указывающее, является ли строка числом. Если строка содержит число, то мы преобразуем его в int, иначе нет.
Вывод:
На этом мы заканчиваем нашу статью. Это был простой способ избавиться от ValueError в Python. Если вышеприведенный метод не работает, то необходимо проверить строку и убедиться, что она не содержит ни одной буквы.
Однако, если у вас есть какие-либо сомнения или вопросы, дайте мне знать в разделе комментариев ниже. Я постараюсь помочь вам как можно скорее.
Счастливого кодирования!
| description | Locale | ms.date | no-loc | online version | schema | title |
|---|---|---|---|---|---|---|
|
Both integer and real numeric literals can have type and multiplier suffixes. |
en-US |
03/01/2023 |
482gb |
https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_numeric_literals?view=powershell-7.4&WT.mc_id=ps-gethelp |
2.0.0 |
about Numeric Literals |
Short description
This article describes the syntax and usage of numeric values in PowerShell.
Long description
There are two kinds of numeric literals: integer and real. Both can have type
and multiplier suffixes.
Integer literals
Integer literals can be written in decimal, hexadecimal, or binary notation.
Hexadecimal literals are prefixed with 0x and binary literals are prefixed
with 0b to distinguish them from decimal numbers.
Integer literals can have a type suffix and a multiplier suffix.
| Suffix | Meaning | Note |
|---|---|---|
y |
signed byte data type | Added in PowerShell 6.2 |
uy |
unsigned byte data type | Added in PowerShell 6.2 |
s |
short data type | Added in PowerShell 6.2 |
us |
unsigned short data type | Added in PowerShell 6.2 |
l |
long data type | |
u |
unsigned int or long data type | Added in PowerShell 6.2 |
ul |
unsigned long data type | Added in PowerShell 6.2 |
n |
BigInteger data type | Added in PowerShell 7.0 |
kb |
kilobyte multiplier | |
mb |
megabyte multiplier | |
gb |
gigabyte multiplier | |
tb |
terabyte multiplier | |
pb |
petabyte multiplier |
The type of an integer literal is determined by its value, the type suffix, and
the numeric multiplier suffix.
For an integer literal with no type suffix:
- If the value can be represented by type
[int], that is its type. - Otherwise, if the value can be represented by type
[long], that is its
type. - Otherwise, if the value can be represented by type
[decimal], that is its
type. - Otherwise, it is represented by type
[double].
For an integer literal with a type suffix:
- If the type suffix is
uand the value can be represented by type[uint]
then its type is[uint]. - If the type suffix is
uand the value can be represented by type[ulong]
then its type is[ulong]. - If its value can be represented by type specified then that is its type.
- Otherwise, that literal is malformed.
Real literals
Real literals can only be written in decimal notation. This notation can
include fractional values following a decimal point and scientific notation
using an exponential part.
The exponential part includes an ‘e’ followed by an optional sign (+/-) and a
number representing the exponent. For example, the literal value 1e2 equals
the numeric value 100.
Real literals can have a type suffix and a multiplier suffix.
| Suffix | Meaning |
|---|---|
d |
decimal data type |
kb |
kilobyte multiplier |
mb |
megabyte multiplier |
gb |
gigabyte multiplier |
tb |
terabyte multiplier |
pb |
petabyte multiplier |
There are two kinds of real literal: double and decimal. These are indicated by
the absence or presence, respectively, of decimal-type suffix. PowerShell does
not support a literal representation of a [float] value. A double real
literal has type [double]. A decimal real literal has type [decimal].
Trailing zeros in the fraction part of a decimal real literal are significant.
If the value of exponent-part’s digits in a [double] real literal is less
than the minimum supported, the value of that [double] real literal is 0. If
the value of exponent-part’s digits in a [decimal] real literal is less than
the minimum supported, that literal is malformed. If the value of
exponent-part’s digits in a [double] or [decimal] real literal is greater
than the maximum supported, that literal is malformed.
[!NOTE]
The syntax permits a double real literal to have a long-type suffix.
PowerShell treats this case as an integer literal whose value is represented
by type[long]. This feature has been retained for backwards compatibility
with earlier versions of PowerShell. However, programmers are discouraged
from using integer literals of this form as they can easily obscure the
literal’s actual value. For example,1.2Lhas value 1,1.2345e1Lhas
value 12, and1.2345e-5Lhas value 0, none of which are immediately
obvious.
Numeric multipliers
For convenience, integer and real literals can contain a numeric multiplier,
which indicates one of a set of commonly used powers of 2. The numeric
multiplier can be written in any combination of upper or lowercase letters.
The multiplier suffixes can be used in combination with any type suffixes, but
must be present after the type suffix. For example, the literal 100gbL is
malformed, but the literal 100Lgb is valid.
If a multiplier creates a value that exceeds the possible values for the
numeric type that the suffix specifies, the literal is malformed. For example,
the literal 1usgb is malformed, because the value 1gb is larger than what
is permitted for the [ushort] type specified by the us suffix.
Multiplier examples
PS> 1kb
1024
PS> 1.30Dmb
1363148.80
PS> 0x10Gb
17179869184
PS> 1.4e23tb
1.5393162788864E+35
PS> 0x12Lpb
20266198323167232
Numeric type accelerators
PowerShell supports the following type accelerators:
| Accelerator | Note | Description |
|---|---|---|
[byte] |
Byte (unsigned) | |
[sbyte] |
Byte (signed) | |
[Int16] |
16-bit integer | |
[short] |
alias for [int16] |
16-bit integer |
[UInt16] |
16-bit integer (unsigned) | |
[ushort] |
alias for [uint16] |
16-bit integer (unsigned) |
[Int32] |
32-bit integer | |
[int] |
alias for [int32] |
32-bit integer |
[UInt32] |
32-bit integer (unsigned) | |
[uint] |
alias for [uint32] |
32-bit integer (unsigned) |
[Int64] |
64-bit integer | |
[long] |
alias for [int64] |
64-bit integer |
[UInt64] |
64-bit integer (unsigned) | |
[ulong] |
alias for [uint64] |
64-bit integer (unsigned) |
[bigint] |
See BigInteger Struct | |
[single] |
Single precision floating point | |
[float] |
alias for [single] |
Single precision floating point |
[double] |
Double precision floating point | |
[decimal] |
128-bit floating point |
[!NOTE]
The following type accelerators were added in PowerShell 6.2:[short],
[ushort],[uint],[ulong].
Examples
The following table contains several examples of numeric literals and lists
their type and value:
| Number | Type | Value |
|---|---|---|
| 100 | Int32 | 100 |
| 100u | UInt32 | 100 |
| 100D | Decimal | 100 |
| 100l | Int64 | 100 |
| 100uL | UInt64 | 100 |
| 100us | UInt16 | 100 |
| 100uy | Byte | 100 |
| 100y | SByte | 100 |
| 1e2 | Double | 100 |
| 1.e2 | Double | 100 |
| 0x1e2 | Int32 | 482 |
| 0x1e2L | Int64 | 482 |
| 0x1e2D | Int32 | 7725 |
| 482D | Decimal | 482 |
| 482gb | Int64 | 517543559168 |
| 482ngb | BigInteger | 517543559168 |
| 0x1e2lgb | Int64 | 517543559168 |
| 0b1011011 | Int32 | 91 |
| 0xFFFFs | Int16 | -1 |
| 0xFFFFFFFF | Int32 | -1 |
| -0xFFFFFFFF | Int32 | 1 |
| 0xFFFFFFFFu | UInt32 | 4294967295 |
Working with binary or hexadecimal numbers
Overly large binary or hexadecimal literals can return as [bigint] rather
than failing the parse, if and only if the n suffix is specified. Sign bits
are still respected above even [decimal] ranges, however:
- If a binary string is some multiple of 8 bits long, the highest bit is
treated as the sign bit. - If a hex string, which has a length that is a multiple of 8, has the first
digit with 8 or higher, the numeral is treated as negative.
Specifying an unsigned suffix on binary and hex literals ignores sign bits. For
example, 0xFFFFFFFF returns -1, but 0xFFFFFFFFu returns the
[uint]::MaxValue of 4294967295.
In PowerShell 7.1, using a type suffix on a hex literal now returns a signed
value of that type. For example, in PowerShell 7.0 the expression 0xFFFFs
returns an error because the positive value is too large for an [int16] type.
PowerShell 7.1 interprets this as -1 that is an [int16] type.
Prefixing the literal with a 0 will bypass this and be treated as unsigned.
For example: 0b011111111. This can be necessary when working with literals
in the [bigint] range, as the u and n suffixes cannot be combined.
You can also negate binary and hex literals using the - prefix. This can
result in a positive number since sign bits are permitted.
Sign bits are accepted for BigInteger-suffixed numerals:
- BigInteger-suffixed hex treats the high bit of any literal with a length
multiple of 8 characters as the sign bit. The length does not include the
0xprefix or any suffixes. - BigInteger-suffixed binary accepts sign bits at 96 and 128 characters, and at
every 8 characters after.
Numeric type conversion
When strings are converted to numbers, additional hexadecimal format indicators
are supported. Those additional formats are not recognized as literals.
[int] '0xF' -eq 0xF [int] '&hF' -eq 0xF [int] '#F' -eq 0xF [int] '0b1111' -eq 0b1111 [int] '0b1111' -eq 15
Commands that look like numeric literals
Any command that looks like a valid numeric literal must be executed using the
call operator (&), otherwise it is interpreted as a number. Malformed
literals with valid syntax like 1usgb will result in the following error:
PS> 1usgb
At line:1 char:6
+ 1usgb
+ ~
The numeric constant 1usgb is not valid.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : BadNumericConstant
However, malformed literals with invalid syntax like 1gbus will be
interpreted as a standard bare string, and can be interpreted as a valid
command name in contexts where commands may be called.
Access properties and methods of numeric objects
To access a member of a numeric literal, there are cases when you need to
enclose the literal in parentheses.
- The literal does not have a decimal point
- The literal does not have any digits following the decimal point
- The literal does not have a suffix
For example, the following example fails:
PS> 2.GetType().Name
At line:1 char:11
+ 2.GetType().Name
+ ~
An expression was expected after '('.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ExpectedExpression
The following examples work:
PS> 2uL.GetType().Name
UInt64
PS> 1.234.GetType().Name
Double
PS> (2).GetType().Name
Int32
The first two examples work without enclosing the literal value in parentheses
because the PowerShell parser can determine where the numeric literal ends and
the GetType method starts.
How PowerShell parses numeric literals
PowerShell v7.0 changed the way numeric literals are parsed to enable the new
features.
Parsing real numeric literals
If the literal contains a decimal point or the e-notation, the literal string
is parsed as a real number.
- If the decimal-suffix is present then directly into
[decimal]. - Else, parse as
[Double]and apply multiplier to the value. Then check the
type suffixes and attempt to cast into appropriate type. - If the string has no type suffix, then parse as
[Double].
Parsing integer numeric literals
Integer type literals are parsed using the following steps:
- Determine the radix format
- For binary formats, parse into
[BigInteger]. - For hexidecimal formats, parse into
[BigInteger]using special casies to
retain original behaviors when the value is in the[int]or[long]
range. - If neither binary nor hex, parse normally as a
[BigInteger].
- For binary formats, parse into
- Apply the multiplier value before attempting any casts to ensure type bounds
can be appropriately checked without overflows. - Check type suffixes.
- Check type bounds and attempt to parse into that type.
- If no suffix is used, then the value is bounds-checked in the following
order, resulting in the first successful test determining the type of the
number.[int][long][decimal](base-10 literals only)[double](base-10 literals only)
- If the value is outside the
[long]range for hex and binary numbers, the
parse fails. - If the value is outside the
[double]range for base 10 number, the parse
fails. - Higher values must be explicitly written using the
nsuffix to parse the
literal as aBigInteger.
Parsing large value literals
Previously, higher integer values were parsed as double before being cast to
any other type. This results in a loss of precision in the higher ranges. For
example:
PS> [bigint]111111111111111111111111111111111111111111111111111111
111111111111111100905595216014112456735339620444667904
To avoid this problem you had to write values as strings and then convert them:
PS> [bigint]'111111111111111111111111111111111111111111111111111111'
111111111111111111111111111111111111111111111111111111
In PowerShell 7.0 you must use the N suffix.
PS> 111111111111111111111111111111111111111111111111111111n
111111111111111111111111111111111111111111111111111111
Also values between [ulong]::MaxValue and [decimal]::MaxValue should be
denoted using the decimal-suffix D to maintain accuracy. Without the suffix,
these values are parsed as [Double] using the real-parsing mode.
На чтение 7 мин Просмотров 60.9к. Опубликовано 17.06.2021
В этой статье мы рассмотрим из-за чего возникает ошибка ValueError: Invalid Literal For int() With Base 10 и как ее исправить в Python.
Содержание
- Введение
- Описание ошибки ValueError
- Использование функции int()
- Причины возникновения ошибки
- Случай №1
- Случай №2
- Случай №3
- Как избежать ошибки?
- Заключение
Введение
ValueError: invalid literal for int() with base 10 — это исключение, которое может возникнуть, когда мы пытаемся преобразовать строковый литерал в целое число с помощью метода int(), а строковый литерал содержит символы, отличные от цифр. В этой статье мы попытаемся понять причины этого исключения и рассмотрим различные методы, позволяющие избежать его в наших программах.
Описание ошибки ValueError
ValueError — это исключение в Python, которое возникает, когда в метод или функцию передается аргумент с правильным типом, но неправильным значением. Первая часть сообщения, т.е. «ValueError», говорит нам о том, что возникло исключение, поскольку в качестве аргумента функции int() передано неправильное значение. Вторая часть сообщения «invalid literal for int() with base 10» говорит нам о том, что мы пытались преобразовать входные данные в целое число, но входные данные содержат символы, отличные от цифр в десятичной системе счисления.
Использование функции int()
Функция int() в Python принимает строку или число в качестве первого аргумента и необязательный аргумент base, обозначающий формат числа. По умолчанию base имеет значение 10, которое используется для десятичных чисел, но мы можем передать другое значение base, например 2 для двоичных чисел или 16 для шестнадцатеричных. В этой статье мы будем использовать функцию int() только с первым аргументом, и значение по умолчанию для base всегда будет равно нулю. Это можно увидеть в следующих примерах.
Мы можем преобразовать число с плавающей точкой в целое число, как показано в следующем примере. Когда мы преобразуем число с плавающей точкой в целое число с помощью функции int(), цифры после десятичной дроби отбрасываются из числа на выходе.
num = 22.03
print(f"Число с плавающей точкой: {num}")
num = int(num)
print(f"Целое число: {num}")
Вывод программы:
Число с плавающей точкой: 22.03 Целое число: 22
Мы можем преобразовать строку, состоящую из цифр, в целое число, как показано в следующем примере. Здесь входные данные состоят только из цифр, поэтому они будут преобразованы в целое число.
num = "22"
print(f"Строка: {num}")
num = int(num)
print(f"Целое число: {num}")
Вывод программы
Строка: 22 Целое число: 22
Два типа входных данных, показанные в двух вышеприведенных примерах, являются единственными типами входных данных, для которых функция int() работает правильно. При передаче в качестве аргументов функции int() других типов входных данных будет сгенерирован ValueError с сообщением «invalid literal for int() with base 10». Теперь мы рассмотрим различные типы входных данных, для которых в функции int() может быть сгенерирован ValueError.
Причины возникновения ошибки
Как говорилось выше, «ValueError: invalid literal for int()» может возникнуть, когда в функцию int() передается ввод с несоответствующим значением. Это может произойти в следующих случаях.
Случай №1
Python ValueError: invalid literal for int() with base 10 возникает, когда входные данные для метода int() являются буквенно-цифровыми, а не числовыми, и поэтому входные данные не могут быть преобразованы в целое число. Это можно понять на следующем примере.
В этом примере мы передаем в функцию int() строку, содержащую буквенно-цифровые символы, из-за чего возникает ValueError, выводящий на экран сообщение «ValueError: invalid literal for int() with base 10».
num = "22я"
print(f"Строка: {num}")
num = int(num)
print(f"Целое число: {num}")
Вывод программы
Строка: 22я
Traceback (most recent call last):
File "/Users/krnlnx/Projects/Test/num.py", line 3, in <module>
num = int(num)
ValueError: invalid literal for int() with base 10: '22я'
Случай №2
Python ValueError: invalid literal for int() with base 10 возникает, когда входные данные функции int() содержат пробельные символы, и поэтому входные данные не могут быть преобразованы в целое число. Это можно понять на следующем примере.
В этом примере мы передаем в функцию int() строку, содержащую пробел, из-за чего возникает ValueError, выводящий на экран сообщение «ValueError: invalid literal for int() with base 10».
num = "22 11"
print(f"Строка: {num}")
num = int(num)
print(f"Целое число: {num}")
Вывод программы
Строка: 22 11
Traceback (most recent call last):
File "/Users/krnlnx/Projects/Test/num.py", line 3, in <module>
num = int(num)
ValueError: invalid literal for int() with base 10: '22 11'
Случай №3
Python ValueError: invalid literal for int() with base 10 возникает, когда вход в функцию int() содержит какие-либо знаки препинания, такие как точка «.» или запятая «,». Поэтому входные данные не могут быть преобразованы в целое число. Это можно понять на следующем примере.
В этом примере мы передаем в функцию int() строку, содержащую символ точки «.», из-за чего возникает ValueError, выводящий сообщение «ValueError: invalid literal for int() with base 10».
num = "22.11"
print(f"Строка: {num}")
num = int(num)
print(f"Целое число: {num}")
Вывод программы
Строка: 22.11
Traceback (most recent call last):
File "/Users/krnlnx/Projects/Test/num.py", line 3, in <module>
num = int(num)
ValueError: invalid literal for int() with base 10: '22.11'
Как избежать ошибки?
Мы можем избежать исключения ValueError: invalid literal for int() with base 10, используя упреждающие меры для проверки того, состоит ли входной сигнал, передаваемый функции int(), только из цифр или нет. Для проверки того, состоит ли входной сигнал, передаваемый функции int(), только из цифр, можно использовать следующие способы.
- Мы можем использовать регулярные выражения, чтобы проверить, состоит ли входной сигнал, передаваемый функции int(), только из цифр или нет. Если входные данные содержат символы, отличные от цифр, мы можем сообщить пользователю, что входные данные не могут быть преобразованы в целое число. В противном случае мы можем продолжить работу в обычном режиме.
- Мы также можем использовать метод isdigit(), чтобы проверить, состоит ли входная строка только из цифр или нет. Метод isdigit() принимает на вход строку и возвращает True, если входная строка, переданная ему в качестве аргумента, состоит только из цифр в десятичной системе. В противном случае он возвращает False. После проверки того, состоит ли входная строка только из цифр или нет, мы можем преобразовать входные данные в целые числа.
- Возможна ситуация, когда входная строка содержит число с плавающей точкой и имеет символ точки «.» между цифрами. Для преобразования таких входных данных в целые числа с помощью функции int() сначала проверим, содержит ли входная строка число с плавающей точкой, т.е. имеет ли она только один символ точки между цифрами или нет, используя регулярные выражения. Если да, то сначала преобразуем входные данные в число с плавающей точкой, которое можно передать функции int(), а затем выведем результат. В противном случае будет сообщено, что входные данные не могут быть преобразованы в целое число.
- Мы также можем использовать обработку исключений, используя try except для обработки ValueError при возникновении ошибки. В блоке try мы обычно выполняем код. Когда произойдет ошибка ValueError, она будет поднята в блоке try и обработана блоком except, а пользователю будет показано соответствующее сообщение.
Заключение
В этой статье мы рассмотрели, почему в Python возникает ошибка «ValueError: invalid literal for int() with base 10», разобрались в причинах и механизме ее возникновения. Мы также увидели, что этой ошибки можно избежать, предварительно проверив, состоит ли вход в функцию int() только из цифр или нет, используя различные методы, такие как регулярные выражения и встроенные функции.
I will attempt to summarise here the primary points of discussion that have ensued in #7993 as it has spiraled into many threads, and I suspect a bullet-point summary of questions to be answered will be significantly easier on the committee.
Regarding Binary & Hex Parsing
As part of the refactor & introduction of binary parsing, methodology of hex parsing has also been altered a bit. Parsing currently results in the same as it currently works, with the caveat that literals with values above Int64.MaxValue are also now acceptable.
Parse as C# Literals
With that in mind, @mklement brought up the point that we may want to simply change how hex and binary parsing work. That is, mimic C#’s behaviour of these literals in source, which would mean parsing all hexadecimal literals as strictly positive (no more 0xFFFFFFFF -eq -1 — instead, 0xFFFFFFFF -eq UInt32.MaxValue) and having such literals smoothly convert up to UInt values.
With that in mind, the code patterns for hex or binary literals would seek out the lowest available parsed value type (when no type is specified) in the following order: Int32, UInt32, Int64, UInt64, Decimal, and possibly finally BigInteger.
Other Options
Hex & BigInteger
If we elect to keep current hex behaviour, we need to consider how it would behave in ranges higher than Decimal. BigInteger‘s default parser for hex numerals will simply assume the highest bit of a byte is indicative of the sign. As a result any numeral treated as signed that begins with 0x8 or higher will be considered the negative two’s complement representation when we enter ranges that can only be parsed as BigInteger. This could be overridden easily, if this behaviour is considered to be undesirable.
Binary Parsing with Sign Bits
Then we face the issue of what to do about binary parsing. I doubt most folks working with binary directly will be working in ranges above 32-bit numbers, but I could be very wrong on that. They are, however, easier to work with in the byte, short, and int value ranges (8, 16, 32-length literals), and behaviour of a sign bit in this case is also entirely up to the parser here due to the custom implementation of binary parsing for speed concerns.
Should binary sign bits only be accepted at 32-bit lengths and up for consistency with hex parsing? Or should they be accepted at similar lengths of literal (8 binary bits, 8 hex char literal) to match up visually with hex literals? This would place a sign bit at all of the 8, 16, and 32-char lengths of a binary literal, so 0b11111111 -eq -1 and so forth, which looks similar in behaviour to hex’s 0xFFFFFFFF -eq -1, despite the obvious difference in actual bit length of the literals.
Parse Numeric Literals with Underscores
E.g., 1_000_000, 0b0101_1010, 0xF_FFF_F_FFF and so forth. Should this be allowed? C# already does this with literals in source code. Are there culture-sensitive concerns around this? This is a relatively simple addition.
Experimental Feature Possibilities
If this is the best option, I am not at all against hiding alternate parse methods behind experimental flags if need be. But for that to be possible, I need a «standard» acceptable behaviour to be defined clearly so that I can lay it out for the hex and binary parse methods.
Original post is below. PR #7901 added byte literals (suffix y or uy), so that portion of this issue is completed.
See the discussion in #7509.
Emerging from the interesting dust of modifying the tokenizer are two further points:
- The tokenizer should be able to parse binary literals.
- The tokenizer should support
bytetype literals.
The trouble here is that both of these suggestions could arguably use a b suffix for numeric literals.
My opinion is that the b suffix should be used for byte literals, in keeping with the current convention that suffixes alter the numeric data type rather than simply base representation.
So what about binary? Well, jcotton in the PowerShell Slack channel / irc / discord #bridge channel mentioned that just like common hex representations use 0xAAFF057, we could also follow the common convention of binary being similar: 0b01001011
From my brief poking about, it looks like we may have to alter System.Globalization.NumberStyles in order to add Binary as a flag value — if we follow the current implementation of hexadecimal numerals. We don’t necessarily have to.
TryGetNumberValue in the tokenizer.cs file would also have to be modified to accept possibly some kind of enum for number formats as well; currently it only accepts a bool for hex specification. ScanNumberHelper would also have to be modified for this.
The suffix approach is simpler, especially with the changes already in #7509 which make adding suffixes a good deal easier. However, given that we may want to reserve the b suffix for 123b byte literals, we may need to consider adding a case for 0b0010101 syntax.
What do you guys think?
Other suggested suffixes for byte literals:
ub(sborbfor signed bytes)uy( F# style) withyfor signed bytes


