0% found this document useful (0 votes)
2 views27 pages

Python 1 Unit

In Python, an identifier is a name for variables, functions, or classes, which must start with a letter or underscore, be unique within its scope, and cannot be a reserved keyword. Python has 35 reserved keywords that cannot be used as identifiers, and variables can be declared without specifying their type. The document also covers expressions and operators in Python, detailing various types of expressions, operator precedence, and the different categories of operators available.

Uploaded by

sumi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
2 views27 pages

Python 1 Unit

In Python, an identifier is a name for variables, functions, or classes, which must start with a letter or underscore, be unique within its scope, and cannot be a reserved keyword. Python has 35 reserved keywords that cannot be used as identifiers, and variables can be declared without specifying their type. The document also covers expressions and operators in Python, detailing various types of expressions, operator precedence, and the different categories of operators available.

Uploaded by

sumi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 27

Identifier in Python?

In Python, an identifier is the name assigned to a variable, function, class, or other object. It is
used to refer to the object in the program and is a way to give the object a human-readable
name. In Python, an identifier must follow certain rules to be valid.

An identifier in Python must, by default, start with a letter or an underscore ( )

The identifier cannot begin with a number or any other special character.

The remaining characters in the identifier can be letters, numbers, or underscores. This means
that an identifier can contain letters, numbers, and underscores but cannot contain any other
special characters.

The second rule for an identifier in Python is that it must be unique within the scope in which it is
used. This means you cannot have two variables with the same name in the same scope or two
functions with the same name in the same module. Attempting to do so will result in a Name
Error.

The third rule for an identifier in Python is that it cannot be a reserved word. Python has a set of
reserved words that cannot be used as identifiers. These include keywords like if, else, for, while,
and so on. A Syntax Error will be returned if you attempt to use a reserved term as an identifier.

Python Keywords
Python keywords are unique words reserved with defined meanings and functions that we can
only apply for those functions. You'll never need to import any keyword into your program
because they're permanently present.

Python's built-in methods and classes are not the same as the keywords. Built-in methods and
classes are constantly present; however, they are not as limited in their application as keywords.

Python contains thirty-five keywords in the most recent version, i.e., Python 3.8. Here we have
shown a complete list of Python keywords for the reader's reference.

False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

async elif if or yield


Python Variables
Variable is a name that is used to refer to memory location. Python variable is also known as an
identifier and used to hold value.

In Python, we don't need to specify the type of variable because Python is a infer language and
smart enough to get variable type.

Variable names can be a group of both the letters and digits, but they have to begin with a letter
or an underscore.

It is recommended to use lowercase letters for the variable name. Rahul and rahul both are two
different variables.

Declaring Variable and Assigning Values


Python does not bind us to declare a variable before using it in the application. It allows us to
create a variable at the required time.

We don't need to declare explicitly variable in Python. When we assign any value to the variable,
that variable is declared automatically.

The equal (=) operator is used to assign value to a variable.

example:

a = 50

In the above image, the variable a refers to an integer object.

Expressions in Python

An expression is a combination of operators and operands that is interpreted to produce


some other value.

In any programming language, an expression is evaluated as per the precedence of its


operators. So that if there is more than one operator in an expression, their precedence
decides which operation will be performed first. We have many different types of
expressions in Python.
1. Constant Expressions: These are the expressions that have constant values only.
Example:
 Python3

# Constant Expressions

x = 15 + 1.3

print(x)

Output

16.3
2. Arithmetic Expressions: An arithmetic expression is a combination of numeric
values, operators, and sometimes parenthesis. The result of this type of expression is
also a numeric value. The operators used in these expressions are arithmetic operators
like addition, subtraction, etc. Here are some arithmetic operators in Python:

Synta
Operators Functioning
x

+ x+y Addition

– x–y Subtraction

* x*y Multiplication

/ x/y Division

// x // y Quotient

% x%y Remainder
** x ** y Exponentiation

Example:

# Arithmetic Expressions

x = 40

y = 12

add = x + y

sub = x - y

pro = x * y

div = x / y

print(add)

print(sub)

print(pro)

print(div)

Output

52
28
480
3.3333333333333335
3. Integral Expressions: These are the kind of expressions that produce only integer
results after all computations and type conversions.
Example:
 Python3
# Integral Expressions

a = 13

b = 12.0

c = a + int(b)

print(c)

Output

25
4. Floating Expressions: These are the kind of expressions which produce floating
point numbers as result after all computations and type conversions.
Example:
 Python3

# Floating Expressions

a = 13

b =5

c =a /b

print(c)

Output

2.6
5. Relational Expressions: In these types of expressions, arithmetic expressions are
written on both sides of relational operator (> , < , >= , <=). Those arithmetic
expressions are evaluated first, and then compared as per relational operator and
produce a boolean output in the end. These expressions are also called Boolean
expressions.
Example:
 Python3

# Relational Expressions

a = 21

b = 13

c = 40

d = 37

p = (a + b) >= (c - d)

print(p)

Output

True
6. Logical Expressions: These are kinds of expressions that result in
either True or False. It basically specifies one or more conditions. For example, (10 ==
9) is a condition if 10 is equal to 9. As we know it is not correct, so it will return False.
Studying logical expressions, we also come across some logical operators which can be
seen in logical expressions most often. Here are some logical operators in Python:

Operator Syntax Functioning

and P and Q It returns true if both P and Q are true otherwise returns false

or P or Q It returns true if at least one of P and Q is true

not not P It returns true if condition P is false

Example:
Let’s have a look at an exemplar code :

 Python3
P = (10 == 9)

Q = (7 > 5)

# Logical Expressions

R = P and Q

S = P or Q

T = not P

print(R)

print(S)

print(T)

Output

False
True
True
7. Bitwise Expressions: These are the kind of expressions in which computations are
performed at bit level.
Example:
 Python3

# Bitwise Expressions

a = 12

x = a >> 2
y = a << 1

print(x, y)

Output

3 24
8. Combinational Expressions: We can also use different types of expressions in a
single expression, and that will be termed as combinational expressions.
Example:
 Python3

# Combinational Expressions

a = 16

b = 12

c = a + (b >> 1)

print(c)

Output

22
But when we combine different types of expressions or use multiple operators in a
single expression, operator precedence comes into play.

Multiple operators in expression (Operator Precedence)

It’s a quite simple process to get the result of an expression if there is only one operator
in an expression. But if there is more than one operator in an expression, it may give
different results on basis of the order of operators executed. To sort out these
confusions, the operator precedence is defined. Operator Precedence simply defines the
priority of operators that which operator is to be executed first. Here we see the
operator precedence in Python, where the operator higher in the list has more
precedence or priority:
Precedenc
e Name Operator

1 Parenthesis ()[]{}

2 Exponentiation **

3 Unary plus or minus, complement -a , +a , ~a

4 Multiply, Divide, Modulo / * // %

5 Addition & Subtraction + –

6 Shift Operators >> <<

7 Bitwise AND &

8 Bitwise XOR ^

9 Bitwise OR |

10 Comparison Operators >= <= > <

11 Equality Operators == !=

12 Assignment Operators = += -= /= *=

13 Identity and membership operators is, is not, in, not in


Precedenc
e Name Operator

14 Logical Operators and, or, not

 So, if we have more than one operator in an expression, it is evaluated as per operator
precedence. For example, if we have the expression “10 + 3 * 4”. Going without
precedence it could have given two different outputs 22 or 52.

# Multi-operator expression

a = 10 + 3 * 4

print(a)

b = (10 + 3) * 4

print(b)

c = 10 + (3 * 4)

print(c)

Output

22
52
22
Hence, operator precedence plays an important role in the evaluation of a Python
expression.

Python Operators
The operator is a symbol that performs a certain operation between two operands, according to
one definition. In a particular programming language, operators serve as the foundation upon
which logic is constructed in a programme. The different operators that Python offers are listed
here.

o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
o Arithmetic Operators

Arithmetic Operators
Arithmetic operations between two operands are carried out using arithmetic operators. It
includes the exponent (**) operator as well as the + (addition), - (subtraction), * (multiplication), /
(divide), % (reminder), and // (floor division) operators.

Consider the following table for a detailed explanation of arithmetic operators.

Operator Description

+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b =
20

- It is used to subtract the second operand from the first operand. If the
(Subtraction) first operand is less than the second operand, the value results negative.
For example, if a = 20, b = 5 => a - b = 15

/ (divide) It returns the quotient after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a/b = 2.0

* It is used to multiply one operand with the other. For example, if a = 20, b
(Multiplicatio = 4 => a * b = 80
n)

% (reminder) It returns the reminder after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a%b = 0

** (Exponent) As it calculates the first operand's power to the second operand, it is an


exponent operator.

// (Floor It provides the quotient's floor value, which is obtained by dividing the
division) two operands.

Comparison operator
Comparison operators compare the values of the two operands and return a true or false Boolean
value in accordance. The following table lists the comparison operators.

Play Video

Operator Description

== If the value of two operands is equal, then the condition becomes true.

!= If the value of two operands is not equal, then the condition becomes true.

<= The condition is met if the first operand is smaller than or equal to the second
operand.

>= The condition is met if the first operand is greater than or equal to the second
operand.

> If the first operand is greater than the second operand, then the condition
becomes true.

< If the first operand is less than the second operand, then the condition
becomes true.

Assignment Operators
The right expression's value is assigned to the left operand using the assignment operators. The
following table provides a description of the assignment operators.

Operator Description

= It assigns the value of the right expression to the left operand.

+= By multiplying the value of the right operand by the value of the left operand,
the left operand receives a changed value. For example, if a = 10, b = 20 =>
a+ = b will be equal to a = a+ b and therefore, a = 30.

-= It decreases the value of the left operand by the value of the right operand and
assigns the modified value back to left operand. For example, if a = 20, b = 10
=> a- = b will be equal to a = a- b and therefore, a = 10.

*= It multiplies the value of the left operand by the value of the right operand and
assigns the modified value back to then the left operand. For example, if a =
10, b = 20 => a* = b will be equal to a = a* b and therefore, a = 200.

%= It divides the value of the left operand by the value of the right operand and
assigns the reminder back to the left operand. For example, if a = 20, b = 10
=> a % = b will be equal to a = a % b and therefore, a = 0.

**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign
4**2 = 16 to a.

//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign
4//3 = 1 to a.

Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. Consider the case
below.

For example,

1. if a = 7
2. b=6
3. then, binary (a) = 0111
4. binary (b) = 0110
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000

Operator Description

& (binary A 1 is copied to the result if both bits in two operands at the same location
and) are 1. If not, 0 is copied.

| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting
bit will be 1.

^ (binary If the two bits are different, the outcome bit will be 1, else it will be 0.
xor)

~ The operand's bits are calculated as their negations, so if one bit is 0, the
(negation) next bit will be 1, and vice versa.

<< (left The number of bits in the right operand is multiplied by the leftward shift of
shift) the value of the left operand.

>> (right The left operand is moved right by the number of bits present in the right
shift) operand.

Logical Operators
The assessment of expressions to make decisions typically makes use of the logical operators.
The following logical operators are supported by Python.

Operator Description

and The condition will also be true if the expression is true. If the two expressions a
and b are the same, then a and b must both be true.

or The condition will be true if one of the phrases is true. If a and b are the two
expressions, then an or b must be true if and is true and b is false.

not If an expression a is true, then not (a) will be false and vice versa.

Membership Operators
The membership of a value inside a Python data structure can be verified using Python
membership operators. The result is true if the value is in the data structure; otherwise, it returns
false.

Operator Description
in If the first operand cannot be found in the second operand, it is evaluated to be
true (list, tuple, or dictionary).

not in If the first operand is not present in the second operand, the evaluation is true
(list, tuple, or dictionary).

Identity Operators
Operator Description

is If the references on both sides point to the same object, it is determined to be


true.

is not If the references on both sides do not point at the same object, it is determined
to be true.

Operator Precedence
The order in which the operators are examined is crucial to understand since it tells us which
operator needs to be considered first. Below is a list of the Python operators' precedence tables.

Operator Description

** Overall other operators employed in the expression, the exponent


operator is given precedence.

~+- the minus, unary plus, and negation.

* / % // the division of the floor, the modules, the division, and the multiplication.

+- Binary plus, and minus

>> << Left shift. and right shift

& Binary and.

^| Binary xor, and or

<= < > >= Comparison operators (less than, less than equal to, greater than,
greater then equal to).

<> == != Equality operators.

= %= /= //= -= Assignment operators


+=
*= **=

is is not Identity operators

in not in Membership operators

not or and Logical operators

Types of Comments in Python


In Python, there are 3 types of comments. They are described below:

Single-Line Comments

Single-line remarks in Python have shown to be effective for providing quick descriptions for
parameters, function definitions, and expressions. A single-line comment of Python is the one
that has a hashtag # at the beginning of it and continues until the finish of the line. If the
comment continues to the next line, add a hashtag to the subsequent line and resume the
conversation. Consider the accompanying code snippet, which shows how to use a single line
comment:

Code

1. # This code is to show an example of a single-line comment


2. print( 'This statement does not have a hashtag before it' )

Output:

This statement does not have a hashtag before it

The following is the comment:

1. # This code is to show an example of a single-line comment

The Python compiler ignores this line.

Everything following the # is omitted. As a result, we may put the program mentioned above in
one line as follows:

Code
1. print( 'This is not a comment' ) # this code is to show an example of a single-line comment

Output:

This is not a comment

This program's output will be identical to the example above. The computer overlooks all content
following #.

Multi-Line Comments

Python does not provide the facility for multi-line comments. However, there are indeed many
ways to create multi-line comments.

With Multiple Hashtags (#)

In Python, we may use hashtags (#) multiple times to construct multiple lines of comments.
Every line with a (#) before it will be regarded as a single-line comment.

Code

1. # it is a
2. # comment
3. # extending to multiple lines

In this case, each line is considered a comment, and they are all omitted.

Using String Literals

Because Python overlooks string expressions that aren't allocated to a variable, we can utilize
them as comments.

Code

1. 'it is a comment extending to multiple lines'

We can observe that on running this code, there will be no output; thus, we utilize the strings
inside triple quotes(""") as multi-line comments.

Python Docstring

The strings enclosed in triple quotes that come immediately after the defined function are called
Python docstring. It's designed to link documentation developed for Python modules, methods,
classes, and functions together. It's placed just beneath the function, module, or class to explain
what they perform. The docstring is then readily accessible in Python using the __doc__ attribute.

Code

1. # Code to show how we use docstrings in Python


2.
3. def add(x, y):
4. """This function adds the values of x and y"""
5. return x + y
6.
7. # Displaying the docstring of the add function
8. print( add.__doc__ )

Output:

This function adds the values of x and y

Python Data Types


Variables can hold values, and every value has a data-type. Python is a dynamically typed
language; hence we do not need to define the type of the variable while declaring it. The
interpreter implicitly binds the value with its type.

1. a = 5

The variable a holds integer value five and we did not define its type. Python interpreter will
automatically interpret variables a as an integer type.

Python enables us to check the type of the variable used in the program. Python provides us
the type() function, which returns the type of the variable passed.

Consider the following example to define the values of different data types and checking its type.

Play Video

1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))

Output:

<type 'int'>
<type 'str'>
<type 'float'>

Standard data types


A variable can hold different types of values. For example, a person's name must be stored as a
string whereas its id must be stored as an integer.
Python provides various standard data types that define the storage method on each of them.
The data types defined in Python are given below.

1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary

In this section of the tutorial, we will give a brief introduction of the above data-types. We will
discuss each one of them in detail later in this tutorial.

Numbers

Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type. Python provides the type() function to know the data-type of the variable.
Similarly, the isinstance() function is used to check an object belongs to a particular class.

Python creates Number objects when a number is assigned to a variable. For example;

1. a = 5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
9. print(" c is a complex number", isinstance(1+3j,complex))

Output:

The type of a <class 'int'>


The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True

Python supports three types of numeric data.

1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has
no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.

Sequence Type

String

The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string.

String handling in Python is a straightforward task since Python provides built-in functions and
operators to perform operations in the string.

In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".

The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python
Python'.

The following example illustrates the string in Python.

Example - 1

1. str = "string using double quotes"


2. print(str)
3. s = '''''A multiline
4. string'''
5. print(s)

Output:

string using double quotes


A multiline
string

Consider the following example of string handling.

Example - 2

1. str1 = 'hello javatpoint' #string str1


2. str2 = ' how are you' #string str2
3. print (str1[0:2]) #printing first two character using slice operator
4. print (str1[4]) #printing 4th character of the string
5. print (str1*2) #printing the string twice
6. print (str1 + str2) #printing the concatenation of str1 and str2

Output:

he
o
hello javatpointhello javatpoint
hello javatpoint how are you

List

Python Lists are similar to arrays in C. However, the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets [].

We can use slice [:] operators to access the data of the list. The concatenation operator (+) and
repetition operator (*) works with the list in the same way as they were working with the strings.

Consider the following example.

1. list1 = [1, "hi", "Python", 2]


2. #Checking type of given list
3. print(type(list1))
4.
5. #Printing the list1
6. print (list1)
7.
8. # List slicing
9. print (list1[3:])
10.
11. # List slicing
12. print (list1[0:2])
13.
14. # List Concatenation using + operator
15. print (list1 + list1)
16.
17. # List repetation using * operator
18. print (list1 * 3)

Output:

[1, 'hi', 'Python', 2]


[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

Tuple

A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the items
of different data types. The items of the tuple are separated with a comma (,) and enclosed in
parentheses ().

A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.

Let's see a simple example of the tuple.

1. tup = ("hi", "Python", 2)


2. # Checking type of tup
3. print (type(tup))
4.
5. #Printing the tuple
6. print (tup)
7.
8. # Tuple slicing
9. print (tup[1:])
10. print (tup[0:1])
11.
12. # Tuple concatenation using + operator
13. print (tup + tup)
14.
15. # Tuple repatation using * operator
16. print (tup * 3)
17.
18. # Adding value to tup. It will throw an error.
19. t[2] = "hi"

Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Traceback (most recent call last):


File "main.py", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

Dictionary

Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a hash
table where each key stores a specific value. Key can hold any primitive data type, whereas
value is an arbitrary Python object.

The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.

Consider the following example.

1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}


2.
3. # Printing dictionary
4. print (d)
5.
6. # Accesing value using keys
7. print("1st name is "+d[1])
8. print("2nd name is "+ d[4])
9.
10. print (d.keys())
11. print (d.values())

Output:

1st name is Jimmy


2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])

Boolean

Boolean type provides two built-in values, True and False. These values are used to determine
the given statement true or false. It denotes by the class bool. True can be represented by any
non-zero value or 'T' whereas false can be represented by the 0 or 'F'. Consider the following
example.

1. # Python program to check the boolean type


2. print(type(True))
3. print(type(False))
4. print(false)

Output:

<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

Set

Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after
creation), and has unique elements. In set, the order of the elements is undefined; it may return
the changed sequence of the element. The set is created by using a built-in function set(), or a
sequence of elements is passed in the curly braces and separated by the comma. It can contain
various types of values. Consider the following example.

1. # Creating Empty set


2. set1 = set()
3.
4. set2 = {'James', 2, 3,'Python'}
5.
6. #Printing Set value
7. print(set2)
8.
9. # Adding element to the set
10.
11. set2.add(10)
12. print(set2)
13.
14. #Removing element from the set
15. set2.remove(2)
16. print(set2)

Output:

{3, 'Python', 'James', 2}


{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}

Type Conversion in Python


Type conversion is the transformation of a Py type of data into another type of data. Implicit type
translation and explicit type converter are the two basic categories of type conversion
procedures in Python.
Python has type conversion routines that allow for the direct translation of one data type to
another. This is helpful for both routine programming and competitive programming. This page
aims to enlighten readers about specific conversion functions.

In Python, there are two kinds of type conversion:

o Explicit Type Conversion-The programmer must perform this task manually.


o Implicit Type Conversion-By the Python program automatically.

Implicit Type Conversion

Implicit character data conversion is the term used in Python when a data type conversion occurs
whether during compilation or even during runtime. We do not need to manually change the file
format into some other type of data because Python performs the implicit character data
conversion. Throughout the tutorial, we have seen numerous examples of this type of data type
conversion.

Without user input, the Programming language automatically changes one data type to another
in implicit shift of data types.

1. x = 20
2. print("x type:",type(x)
3. y = 0.6
4. print("y type:",type(y))
5. a = x + y
6. print(a)
7. print("z type:",type(z))

Output:

x type: <class 'int'>


y type: <class 'float' >20.6
a type: <class 'float'>

As we can see, while one variable, x, is only of integer type and the other, y, is of float type, the
data type of "z" was automatically transformed to the "float" type. Due to type promotion, which
enables operations by transforming raw data it in to a wider-sized type of data without any
information loss, the float value is instead not turned into an integer. This is a straightforward
instance of Python's Implicit type conversion.

The result variable was changed into to the float dataset rather than the int data type since doing
so would have required the compiler to eliminate the fractional element, which would have
resulting in data loss. To prevent data loss, Python always translates smaller data types into
larger data types.

We may lose the decimal portion of the report if the variable percentage's data type is integer.
Python automatically converts percentage data to float type, which can store decimal values, to
prevent this data loss.
Explicit Type Conversion:

Let us say we want to change a number from a higher data type to a lower data type. Implicit
type conversion is ineffective in this situation, as we observed in the previous section. Explicit
type conversion, commonly referred to as type casting, now steps in to save the day. Using built-
in Language functions like str() to convert to string form and int() to convert to integer type, a
programmer can explicitly change the data form of an object by changing it manually.

The user can explicitly alter the data type in Python's Explicit Type Conversion according to their
needs. Since we are compelled to change an expression into a certain data type when doing
express type conversion, there is chance of data loss. Here are several examples of explicit type
conversion.

o The function int(a, base) transforms any data type to an integer. If the type of data is a
string, "Base" defines the base wherein string is.
o float(): You can turn any data type into a floating-point number with this function.

1. # Python code to show type conversion


2. # Initializing string with int() and float()
3. a = "10010"
4. # # outputting string to int base 2 conversion.
5. b = int(a,2)
6. print ("following the conversion to integer base 2: ", end="")
7. print (r)
8. # printing a float after converting a string
9. d = float(a)
10. print ("After converting to float : ", end="")
11. print (d)

Output:

following the conversion to integer base 2: 18


After converting to float : 1010.0

3. The ord() method turns a character into an integer.

4. The hex() method turns an integer into a hexadecimal string.

5. The oct() method turns an integer into an octal string.

1. # Python code to show type conversion


2. # initialising integer
3. # using ord(), hex(), and oct()
4. a = '4'
5. # printing and converting a character to an integer
6. b = ord(a)
7. print ("After converting character into integer : ",end="")
8. print (b)
9. # printing integer converting to hexadecimal string
10. b = hex(56)
11. print ("After converting 56 to hexadecimal string : ",end="")
12. print (b)
13. # printing the integer converting into octal string
14. b = oct(56)
15. print ("After converting 56 into octal string : ",end="")
16. print (b)

Output:

After converting the character into integer : 52


After converting the 56 to hexadecimal string : 0x38
After converting the 56 into octal string : 0o70

6. The tuple() method is used to transform data into a tuple.

7. The set() function, which converts a type to a set, returns the set.

8. The list() function transforms any data type into a list type.

You might also like