Type casting error python

Преобразование и приведение типов в Python В данной статье вы узнаете об использовании преобразования и приведения типов. Прежде чем изучать преобразование типов, советуем изучить типы данных в Python. Преобразование типов Процесс преобразования значения одного типа данных (целые числа, строки, числа с плавающей точкой и т. д.) в другой называется преобразованием типа. В Python есть […]

Содержание

  1. Преобразование и приведение типов в Python
  2. Преобразование типов
  3. Неявное преобразование типов
  4. Явное приведение типов
  5. 8. Errors and Exceptions¶
  6. 8.1. Syntax Errors¶
  7. 8.2. Exceptions¶
  8. 8.3. Handling Exceptions¶
  9. 8.4. Raising Exceptions¶
  10. 8.5. Exception Chaining¶
  11. 8.6. User-defined Exceptions¶
  12. 8.7. Defining Clean-up Actions¶
  13. 8.8. Predefined Clean-up Actions¶
  14. 8.9. Raising and Handling Multiple Unrelated Exceptions¶
  15. 8.10. Enriching Exceptions with Notes¶

Преобразование и приведение типов в Python

В данной статье вы узнаете об использовании преобразования и приведения типов. Прежде чем изучать преобразование типов, советуем изучить типы данных в Python.

Преобразование типов

Процесс преобразования значения одного типа данных (целые числа, строки, числа с плавающей точкой и т. д.) в другой называется преобразованием типа. В Python есть два вида преобразования:

  1. Неявное преобразование типов.
  2. Явное приведение типов.

Неявное преобразование типов

При неявном преобразовании типов Python автоматически преобразует один тип данных в другой. Этот процесс не требует участия пользователя.

Давайте рассмотрим пример, в котором Python, чтобы избежать потери данных, производит преобразование типа данных с низким диапазоном (целое число) в тип с более высоким диапазоном (число с плавающей запятой).

Вывод:

В программе выше:

  • мы сложили две переменные num_int и num_float , сохранили значение в num_new .
  • мы вывели на экран типы данных всех трех объектов соответственно;
  • в выводе мы видим, что тип данных num_int — целое число, а тип данных num_float — вещественное число.
  • кроме того, мы видим, что num_new имеет тип данных с плавающей запятой, потому что Python всегда преобразует меньший по диапазону тип в больший, чтобы избежать потери данных.

Теперь давайте попробуем сложить строку и целое число и посмотрим, как Python с этим справится.

Вывод:

В программе выше:

  • мы сложили две переменные num_int и num_str.
  • как видно из вывода, мы получили TypeError — Python не может использовать неявное преобразование в таких случаях.

Однако в Python есть решение для таких ситуаций — это явное приведение.

Явное приведение типов

В явном преобразовании программист сам заменяет текущий тип данных объекта на требуемый. Для этого используются встроенные функции, такие как int () , float () , str () и т. д., чтобы выполнить явное преобразование типов.

Этот тип преобразования также называется приведением типов, поскольку пользователь приводит (изменяет) тип данных объекта.

Синтаксис

Приведение типов можно выполнить, если присвоить выражению значение функции, соответствующее нужному типу данных.

Вывод:

В программе выше:

  • мы сложили переменные num_str и num_int ;
  • для выполнения сложения мы преобразовали num_str из строкового типа в целочисленный, используя функцию int () ;
  • после преобразования num_str в целочисленное значение Python уже может сложить эти две переменные;
  • мы получили значение num_sum , его тип данных — целое число.

Источник

8. Errors and Exceptions¶

Until now error messages haven’t been more than mentioned, but if you have tried out the examples you have probably seen some. There are (at least) two distinguishable kinds of errors: syntax errors and exceptions.

8.1. Syntax Errors¶

Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python:

The parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest point in the line where the error was detected. The error is caused by (or at least detected at) the token preceding the arrow: in the example, the error is detected at the function print() , since a colon ( ‘:’ ) is missing before it. File name and line number are printed so you know where to look in case the input came from a script.

8.2. Exceptions¶

Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in Python programs. Most exceptions are not handled by programs, however, and result in error messages as shown here:

The last line of the error message indicates what happened. Exceptions come in different types, and the type is printed as part of the message: the types in the example are ZeroDivisionError , NameError and TypeError . The string printed as the exception type is the name of the built-in exception that occurred. This is true for all built-in exceptions, but need not be true for user-defined exceptions (although it is a useful convention). Standard exception names are built-in identifiers (not reserved keywords).

The rest of the line provides detail based on the type of exception and what caused it.

The preceding part of the error message shows the context where the exception occurred, in the form of a stack traceback. In general it contains a stack traceback listing source lines; however, it will not display lines read from standard input.

Built-in Exceptions lists the built-in exceptions and their meanings.

8.3. Handling Exceptions¶

It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using Control — C or whatever the operating system supports); note that a user-generated interruption is signalled by raising the KeyboardInterrupt exception.

The try statement works as follows.

First, the try clause (the statement(s) between the try and except keywords) is executed.

If no exception occurs, the except clause is skipped and execution of the try statement is finished.

If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then, if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try/except block.

If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.

A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example:

A class in an except clause is compatible with an exception if it is the same class or a base class thereof (but not the other way around — an except clause listing a derived class is not compatible with a base class). For example, the following code will print B, C, D in that order:

Note that if the except clauses were reversed (with except B first), it would have printed B, B, B — the first matching except clause is triggered.

When an exception occurs, it may have associated values, also known as the exception’s arguments. The presence and types of the arguments depend on the exception type.

The except clause may specify a variable after the exception name. The variable is bound to the exception instance which typically has an args attribute that stores the arguments. For convenience, builtin exception types define __str__() to print all the arguments without explicitly accessing .args .

The exception’s __str__() output is printed as the last part (‘detail’) of the message for unhandled exceptions.

BaseException is the common base class of all exceptions. One of its subclasses, Exception , is the base class of all the non-fatal exceptions. Exceptions which are not subclasses of Exception are not typically handled, because they are used to indicate that the program should terminate. They include SystemExit which is raised by sys.exit() and KeyboardInterrupt which is raised when a user wishes to interrupt the program.

Exception can be used as a wildcard that catches (almost) everything. However, it is good practice to be as specific as possible with the types of exceptions that we intend to handle, and to allow any unexpected exceptions to propagate on.

The most common pattern for handling Exception is to print or log the exception and then re-raise it (allowing a caller to handle the exception as well):

The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:

The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement.

Exception handlers do not handle only exceptions that occur immediately in the try clause, but also those that occur inside functions that are called (even indirectly) in the try clause. For example:

8.4. Raising Exceptions¶

The raise statement allows the programmer to force a specified exception to occur. For example:

The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from BaseException , such as Exception or one of its subclasses). If an exception class is passed, it will be implicitly instantiated by calling its constructor with no arguments:

If you need to determine whether an exception was raised but don’t intend to handle it, a simpler form of the raise statement allows you to re-raise the exception:

8.5. Exception Chaining¶

If an unhandled exception occurs inside an except section, it will have the exception being handled attached to it and included in the error message:

To indicate that an exception is a direct consequence of another, the raise statement allows an optional from clause:

This can be useful when you are transforming exceptions. For example:

It also allows disabling automatic exception chaining using the from None idiom:

For more information about chaining mechanics, see Built-in Exceptions .

8.6. User-defined Exceptions¶

Programs may name their own exceptions by creating a new exception class (see Classes for more about Python classes). Exceptions should typically be derived from the Exception class, either directly or indirectly.

Exception classes can be defined which do anything any other class can do, but are usually kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers for the exception.

Most exceptions are defined with names that end in “Error”, similar to the naming of the standard exceptions.

Many standard modules define their own exceptions to report errors that may occur in functions they define.

8.7. Defining Clean-up Actions¶

The try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. For example:

If a finally clause is present, the finally clause will execute as the last task before the try statement completes. The finally clause runs whether or not the try statement produces an exception. The following points discuss more complex cases when an exception occurs:

If an exception occurs during execution of the try clause, the exception may be handled by an except clause. If the exception is not handled by an except clause, the exception is re-raised after the finally clause has been executed.

An exception could occur during execution of an except or else clause. Again, the exception is re-raised after the finally clause has been executed.

If the finally clause executes a break , continue or return statement, exceptions are not re-raised.

If the try statement reaches a break , continue or return statement, the finally clause will execute just prior to the break , continue or return statement’s execution.

If a finally clause includes a return statement, the returned value will be the one from the finally clause’s return statement, not the value from the try clause’s return statement.

A more complicated example:

As you can see, the finally clause is executed in any event. The TypeError raised by dividing two strings is not handled by the except clause and therefore re-raised after the finally clause has been executed.

In real world applications, the finally clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.

8.8. Predefined Clean-up Actions¶

Some objects define standard clean-up actions to be undertaken when the object is no longer needed, regardless of whether or not the operation using the object succeeded or failed. Look at the following example, which tries to open a file and print its contents to the screen.

The problem with this code is that it leaves the file open for an indeterminate amount of time after this part of the code has finished executing. This is not an issue in simple scripts, but can be a problem for larger applications. The with statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly.

After the statement is executed, the file f is always closed, even if a problem was encountered while processing the lines. Objects which, like files, provide predefined clean-up actions will indicate this in their documentation.

There are situations where it is necessary to report several exceptions that have occurred. This is often the case in concurrency frameworks, when several tasks may have failed in parallel, but there are also other use cases where it is desirable to continue execution and collect multiple errors rather than raise the first exception.

The builtin ExceptionGroup wraps a list of exception instances so that they can be raised together. It is an exception itself, so it can be caught like any other exception.

By using except* instead of except , we can selectively handle only the exceptions in the group that match a certain type. In the following example, which shows a nested exception group, each except* clause extracts from the group exceptions of a certain type while letting all other exceptions propagate to other clauses and eventually to be reraised.

Note that the exceptions nested in an exception group must be instances, not types. This is because in practice the exceptions would typically be ones that have already been raised and caught by the program, along the following pattern:

8.10. Enriching Exceptions with Notes¶

When an exception is created in order to be raised, it is usually initialized with information that describes the error that has occurred. There are cases where it is useful to add information after the exception was caught. For this purpose, exceptions have a method add_note(note) that accepts a string and adds it to the exception’s notes list. The standard traceback rendering includes all notes, in the order they were added, after the exception.

For example, when collecting exceptions into an exception group, we may want to add context information for the individual errors. In the following each exception in the group has a note indicating when this error has occurred.

Источник

Prerequisites: Python Data Types

Type Casting is the method to convert the variable data type into a certain data type in order to the operation required to be performed by users. In this article, we will see the various technique for typecasting.

There can be two types of Type Casting in Python –

  • Implicit Type Casting
  • Explicit Type Casting

Implicit Type Conversion

In this,  methods, Python converts data type into another data type automatically. In this process, users don’t have to involve in this process. 

Python3

a = 7

print(type(a))

b = 3.0

print(type(b))

c = a + b

print(c)

print(type(c))

d = a * b

print(d)

print(type(d))

Output:

<class 'int'>
<class 'float'>
10.0
<class 'float'>
21.0
<class 'float'>

Explicit Type Casting

In this method, Python need user involvement to convert the variable data type into certain data type in order to the operation required.

Mainly in type casting can be done with these data type function:

  • Int() : Int() function take float or string as an argument and return int type object.
  • float() : float() function take int or string as an argument and return float type object.
  • str() : str() function take float or int as an argument and return string type object.

Let’s see some example of type casting:

Type Casting int to float:

Here, we are casting integer object to float object with float() function.

Python3

a = 5

n = float(a)

print(n)

print(type(n))

Output:

5.0
<class 'float'>

Type Casting float to int:

Here, we are casting float data type into integer data type with int() function.

Python3

a = 5.9

n = int(a)

print(n)

print(type(n))

Output:

5
<class 'int'>

Type casting int to string:

Here, we are casting int data type into string data type with str() function.

Python3

a = 5

n = str(a)

print(n)

print(type(n))

Output:

5
<class 'str'>

Type Casting string to int:

Here, we are casting string data type into integer data type with int() function.

Python3

a = "5"

n = int(a)

print(n)

print(type(n))

Output:

5
<class 'int'>

Type Casting String to float:

Here, we are casting string data type into float data type with float() function.

Python3

a = "5.9"

n = float(a)

print(n)

print(type(n))

Output:

5.9
<class 'float'>

Introduction

A significant part of programming involves playing around with data. While performing some tasks, situations might arise where the data type has to be changed from one type to another.

For example, if the variable is of type string, that has to be converted to int in order to perform arithmetic operations. In such a condition, the concept of type conversion and type casting comes into play.

Before learning Type Conversion and Type Casting in Python, you should be familiar with Python Data Types. So check out the blog Python Data Types for Beginners to get a better understanding.

In type conversion, the Python interpreter automatically converts one data type to another. Since Python handles the implicit data type conversion, the programmer does not have to convert the data type into another type explicitly. 

The data type to which the conversion happens is called the destination data type, and the data type from which the conversion happens is called the source data type.

In type conversion, the destination data of a smaller size is converted to the source data type of larger size. This avoids the loss of data and makes the conversion safe to use.

In type conversion, the source data type with a smaller size is converted into the destination data type with a larger size.

Let’s see an example to understand type conversion in Python.

intType = 20
floatType = 0.8
 
# intType is converted from int to float
result = intType + floatType
 
# intType is of type int
print("datatype of intType:", type(intType))
 
# floatType is of type float
print("datatype of floatType:", type(floatType))
 
print("intType + floatType = ", result)
# result is of type float
print("result: ", type(result))

Output:

datatype of intType: <class 'int'>
datatype of floatType: <class 'float'>
intType + floatType =  20.8
result:  <class 'float'>

Let’s now try to add a string of larger size and int of smaller size.

blog banner 1

intType = 20
strType = "0.8"
 
# add an integer and string
result = intType + strType
 
print("Data type of the listType :",type(intType))
print("Data type of the listType :",type(strType))
 
print("result: "+result)
print("Data type of the listType :",type(result))

Output:

As you might have guessed, we encountered a TypeError while running the above code. Python does not do the implicit conversion in this case. However, this error can be resolved using type casting, which will be discussed next.

Type Casting

In type casting, the programmer has to change the data type as per their requirement manually. In this, the programmer explicitly converts the data type using predefined functions like int(), float(), str(), etc. There is a chance of data loss in this case if a particular data type is converted to another data type of a smaller size.

The in-built Python functions used for the conversion are given below, along with their descriptions:

Function Description
int(x, base)  converts any data type x to an integer with the mentioned base
float(x) converts x data type to a floating-point number
complex(real,imag) converts a real number to a complex number
str(x) converts x data type to a string
tuple(x) converts x data type to a tuple
list(x) converts x data type to a list
set(x) converts x data type to a set
dict(x) creates a dictionary and x data type should be a sequence of (key,value) tuples
ord(x) converts a character x into an integer
hex(x) converts an integer x to a hexadecimal string
oct(x) converts an integer x to an octal string
chr(x) converts a number x to its corresponding ASCII(American Standard Code for Information Interchange) character

Now let’s see an example to understand type casting in Python.

strType = "CodingNinjas"
 
# printing string converting to tuple
tupleType = tuple(strType)
print("After converting string to tuple : ")
print(tupleType)
print("Data type of the tupleType :",type(tupleType))
 
# printing string converting to set
setType = set(strType)
print("After converting string to set : ")
print(setType)
print("Data type of the setType :",type(setType))
 
# printing string converting to list
listType = list(strType)
print("After converting string to list : ")
print(listType)
print("Data type of the listType :",type(listType))

Output:

After converting string to tuple :
('C', 'o', 'd', 'i', 'n', 'g', 'N', 'i', 'n', 'j', 'a', 's')
Data type of the tupleType : <class 'tuple'>
After converting string to set :
{'g', 'N', 'n', 'C', 's', 'o', 'j', 'd', 'a', 'i'}
Data type of the setType : <class 'set'>
After converting string to list :
['C', 'o', 'd', 'i', 'n', 'g', 'N', 'i', 'n', 'j', 'a', 's']
Data type of the listType : <class 'list'>

Frequently Asked Questions

What is meant by type conversion and type casting in Python?

In type conversion, the Python interpreter automatically converts one data type to another. In type casting, the programmer converts the data type as per their requirement manually.

What are the common methods used to change data types in Python?

Type Conversion and Type Casting in Python enable converting one data type into another.

Differentiate between type conversion and type casting in Python based on data loss.

There is a chance of data loss in type casting while the data is safe in type conversion.

How does data conversion take place in type casting in Python?

In explicit type casting, the data types are converted manually by the programmer using in-built functions.

Is it possible to convert a string to an integer in Python?

No, it is not possible to convert a string to an integer even by using the in-built int() method.

Key Takeaways

That was all about Type Conversion and Type Casting in Python. This blog covered various concepts, examples, and frequently asked questions relating to this topic were covered in detail. 

Now that you know what Type Conversion and Type Casting are, go ahead and attempt some questions on our CodeStudio Platform!

Don’t stop here. Check out our Python guided path to learn Python from Scratch. You can also check out the blog Difference between Type Casting and Type Conversion to better understand Type Conversion and Type Casting in Python.

We hope you found this blog useful. Feel free to let us know your thoughts in the comments section. 

By Hari Sapna Nair

Понравилась статья? Поделить с друзьями:
  • Txd workshop unknown error 0x0b46
  • Tx pr42u30 коды ошибок
  • Tx checksum error vag eeprom
  • Twrp zip treble compatibility error что делать
  • Twrp recovery error 255