Python Programming

Python Programming

Introduction Part II

Type Conversion

? One data type > another data type ? Example: int > float, int > string. ? >>> a = 5.5 ? >>> b = int(a) ? >>> print(b)

5 >>>> print(a)

5.5 Conversion from int to float and stored at b but original value does not change.

Types of Conversion

q Implicit Type Conversion q Explicit Type Conversion ? Implicit Type conversion or automatic type conversion

? Automatically converts one data type to another type num_int = 123 num_float = 2.35 new_num = num_int + num_float print(new_num) output: 125.35 print(type(new_num)) < class `float' >

Explicit conversion

Example: num_int = 234 num_str = '100' print(num_int + num_str) output: TypeError: unsupported operand type(s) for +: `int' and

`str' This is because python can not do implicit conversion in such condition.

Explicit conversion

? User converts the data type of an object to required data type using predefined data types.

? This process is called typecasting

? Syntax: ? Required_datatype (Expression) ? Example: ? num_int = 234 ? num_str = `100' ? num_str = int(num_str) ? print(num_int + num_str) ? Output:

334

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download