0% found this document useful (0 votes)
8 views32 pages

I Unit

The document provides a comprehensive overview of Python programming, covering its history, features, data types, control statements, functions, and file handling. It highlights Python's ease of learning, interpreter-based nature, and extensive standard library, making it a popular choice among developers. Additionally, it discusses various literals, constants, and variables in Python, along with examples and best practices for their usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views32 pages

I Unit

The document provides a comprehensive overview of Python programming, covering its history, features, data types, control statements, functions, and file handling. It highlights Python's ease of learning, interpreter-based nature, and extensive standard library, making it a popular choice among developers. Additionally, it discusses various literals, constants, and variables in Python, along with examples and best practices for their usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

UNIT – I

Basics of Python Programming: History of Python-Features of Python - Literal-


Constants-Variables - Identifiers–Keywords-Built-in Data TypesOutput Statements –
Input Statements-Comments – Indentation- OperatorsExpressions-Type conversions.
Python Arrays: Defining and Processing Arrays – Array methods.

UNIT – II

Control Statements: Selection/Conditional Branching statements: if, if-else, nested if


and if-elif-else statements. Iterative Statements: while loop, for loop, else suite in loop
and nested loops. Jump Statements: break, continue and pass statements.

UNIT – III

Functions: Function Definition – Function Call – Variable Scope and its Lifetime-
Return Statement. Function Arguments: Required Arguments, Keyword Arguments,
Default Arguments and Variable Length ArgumentsRecursion. Python Strings: String
operations- Immutable Strings - Built-in String Methods and Functions - String
Comparison. Modules: import statementThe Python module – dir() function –
Modules and Namespace – Defining our own modules.

UNIT – IV

Lists: Creating a list -Access values in List-Updating values in Lists-Nested lists -Basic
list operations-List Methods. Tuples: Creating, Accessing, Updating and Deleting
Elements in a tuple – Nested tuples– Difference between lists and tuples. Dictionaries:
Creating, Accessing, Updating and Deleting Elements in a Dictionary – Dictionary
Functions and Methods - Difference between Lists and Dictionaries.

UNIT – V

Python File Handling: Types of files in Python - Opening and Closing filesReading and
Writing files: write() and writelines() methods- append() method – read() and
readlines() methods – with keyword – Splitting words – File methods - File Positions-
Renaming and deleting files.
UNIT – I

Basics of Python Programming: History of Python-Features of PythonLiteral-


Constants-Variables - Identifiers–Keywords-Built-in Data TypesOutput
Statements – Input Statements-Comments – Indentation-
OperatorsExpressions-Type conversions. Python Arrays: Defining and
Processing Arrays – Array methods.

Basics of Python Programming:

Python is a high-level, interpreted, interactive and object-oriented scripting


language. Python is designed to be highly readable.

Python is an open-source and cross-platform programming language. It is


available for use under Python Software Foundation License (compatible to GNU
General Public License) on all the major operating system platforms Linux, Windows
and Mac OS.

History of Python

Python was developed by Guido van Rossum in the late eighties and early nineties
at the National Research Institute for Mathematics and Computer Science in the
Netherlands.

Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages.

Python is copyrighted. Like Perl, Python source code is now available under the
GNU General Public License (GPL).

For many uninitiated people, the word Python is related to a species of snake.
Rossum though attributes the choice of the name Python to a popular comedy
series Monty Python's Flying Circus on BBC.

Being the principal architect of Python, the developer community conferred upon
him the title of Benevolent Dictator for Life (BDFL). However, in 2018, Rossum
relinquished the title. Thereafter, the development and distribution of the reference
implementation of Python is handled by a nonprofit organization Python Software
Foundation.

Who Invented Python?

Python was invented by a Dutch Programmer Guido Van Rossum in the late
1980s. And, Python's first version (0.9.0) was released in 1991.

Evolution of Python – The Major Python Releases

Following are the important stages in the history of Python −


Python 0.9.0

Python's first published version is 0.9. It was released in February 1991. It


consisted of support for core object-oriented programming principles.

Python 1.0

In January 1994, version 1.0 was released, armed with functional programming
tools, features like support for complex numbers etc.

Python 2.0

Next major version − Python 2.0 was launched in October 2000. Many new
features such as list comprehension, garbage collection and Unicode support were
included with it.

Python 3.0

Python 3.0, a completely revamped version of Python was released in December


2008. The primary objective of this revamp was to remove a lot of discrepancies that
had crept in Python 2.x versions. Python 3 was backported to Python 2.6. It also
included a utility named as python2to3 to facilitate automatic translation of Python 2
code to Python 3.

Current Version of Python

Meanwhile, more and more features have been incorporated into Python's 3.x
branch. As of date, Python 3.11.2 is the current stable version, released in February
2023.

Features of Python

Let's highlight some of the important features of Python that make it widely
popular. Apart from these 10 features where are number of other interesting features
which make Python most of the developer's first choice.
The following are the features of Python programming language –

1. Easy to Learn

This is one of the most important reasons for the popularity of Python. Python
has a limited set of keywords. Its features such as simple syntax, usage of indentation
to avoid clutter of curly brackets and dynamic typing that doesn't necessitate prior
declaration of variable help a beginner to learn Python quickly and easily.

2. Interpreter Based

Instructions in any programming languages must be translated into machine


code for the processor to execute them. Programming languages are either compiler
based or interpreter based.

In case of a compiler, a machine language version of the entire source program is


generated. The conversion fails even if there is a single erroneous statement. Hence,
the development process is tedious for the beginners. The C family languages
(including C, C++, Java, C# etc) are compiler based.

Python is an interpreter based language. The interpreter takes one instruction


from the source code at a time, translates it into machine code and executes it.
Instructions before the first occurrence of error are executed. With this feature, it is
easier to debug the program and thus proves useful for the beginner level programmer
to gain confidence gradually. Python therefore is a beginner-friendly language.

3. Interactive

Standard Python distribution comes with an interactive shell that works on the
principle of REPL (Read – Evaluate – Print – Loop). The shell presents a Python prompt
>>>. You can type any valid Python expression and press Enter. Python interpreter
immediately returns the response and the prompt comes back to read the next
expression.

>>> 2*3+1
7
>>> print ("Hello World")
Hello World

The interactive mode is especially useful to get familiar with a library and test out its
functionality. You can try out small code snippets in interactive mode before writing a
program.

4. MultiParadigm

Python is a completely object-oriented language. Everything in a Python program


is an object. However, Python conveniently encapsulates its object orientation to be
used as an imperative or procedural language – such as C. Python also provides certain
functionality that resembles functional programming. Moreover, certain third-party
tools have been developed to support other programming paradigms such as aspect-
oriented and logic programming.

5. Standard Library

Even though it has a very few keywords (only Thirty Five), Python software is
distributed with a standard library made of large number of modules and packages.
Thus Python has out of box support for programming needs such as serialization, data
compression, internet data handling, and many more. Python is known for its batteries
included approach.

6.Open Source and Cross Platform

Python's standard distribution can be downloaded


from https://www.python.org/downloads/ without any restrictions. You can
download pre-compiled binaries for various operating system platforms. In addition,
the source code is also freely available, which is why it comes under open source
category.

Python software (along with the documentation) is distributed under Python


Software Foundation License. It is a BSD style permissive software license and
compatible to GNU GPL (General Public License).

Python is a cross-platform language. Pre-compiled binaries are available for use


on various operating system platforms such as Windows, Linux, Mac OS, Android OS.
The reference implementation of Python is called CPython and is written in C. You can
download the source code and compile it for your OS platform.

A Python program is first compiled to an intermediate platform independent byte


code. The virtual machine inside the interpreter then executes the byte code. This
behaviour makes Python a cross-platform language, and thus a Python program can be
easily ported from one OS platform to other.

7. GUI Applications

Python's standard distribution has an excellent graphics library called TKinter. It


is a Python port for the vastly popular GUI toolkit called TCL/Tk. You can build
attractive user-friendly GUI applications in Python. GUI toolkits are generally written
in C/C++. Many of them have been ported to Python. Examples
are PyQt, WxWidgets, PySimpleGUI etc.

8. Database Connectivity

Almost any type of database can be used as a backend with the Python
application. DB-API is a set of specifications for database driver software to let Python
communicate with a relational database. With many third party libraries, Python can
also work with NoSQL databases such as MongoDB.
9. Extensible

The term extensibility implies the ability to add new features or modify existing
features. As stated earlier, CPython (which is Python's reference implementation) is
written in C. Hence one can easily write modules/libraries in C and incorporate them
in the standard library. There are other implementations of Python such as Jython
(written in Java) and IPython (written in C#). Hence, it is possible to write and merge
new functionality in these implementations with Java and C# respectively.

10. Active Developer Community

As a result of Python's popularity and open-source nature, a large number of


Python developers often interact with online forums and conferences. Python Software
Foundation also has a significant member base, involved in the organization's mission
to "Promote, Protect, and Advance the Python Programming Language"

Python also enjoys a significant institutional support. Major IT companies Google,


Microsoft, and Meta contribute immensely by preparing documentation and other
resources.

More Features of Python

Apart from the above-mentioned features, Python has another big list of good features,
few are listed below −

• It supports functional and structured programming methods as well as OOP.


• It can be used as a scripting language or can be compiled to byte-code for
building large applications.
• It provides very high-level dynamic data types and supports dynamic type
checking.
• It supports automatic garbage collection.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Literals in Python
A literal in Python is a syntax that is used to completely express a fixed value of a
specific data type. Literals are constants that are self-explanatory and don’t need to
be computed or evaluated. They are used to provide variable values or to directly
utilize them in expressions. Generally, literals are a notation for representing a fixed
value in source code. They can also be defined as raw values or data given in variables
or constants. In this article, we will explore the different types of literals in Python,
along with examples to demonstrate their usage.
Types of Literals in Python
Python supports various types of literals, such as numeric literals, string literals,
Boolean literals, and more. Let’s explore different types of literals in Python with
examples:
1. String literals
2. Character literal
3. Numeric literals
4. Boolean literals
5. Literal Collections
6. Special literals
Python String Literals
A string is literal and can be created by writing a text(a group of Characters )
surrounded by a single(”), double(“), or triple quotes. We can write multi-line strings
or display them in the desired way by using triple quotes.
Python Character literal
It is also a type of Python string literal where a single character is surrounded
by single or double quotes.
Python Numeric literal
They are immutable and there are three types of numeric literal:
• Integer
• Float
• Complex
Integer
Both positive and negative numbers including 0. There should not be any
fractional part. In this example, We assigned integer literals (0b10100, 50, 0o320,
0x12b) into different variables. Here, ‘a‘ is a binary literal, ‘b’ is a decimal literal, ‘c‘ is
an octal literal, and ‘d‘ is a hexadecimal literal. But on using the print function to
display a value or to get the output they were converted into decimal.
Float
These are real numbers having both integer and fractional parts. In this
example, 24.8 and 45.0 are floating-point literals because both 24.8 and 45.0 are
floating-point numbers.
Complex
The numerals will be in the form of a + bj, where ‘a’ is the real part and ‘b‘ is the
complex part. Numeric literal [ Complex ]
Python Boolean literal
There are only two Boolean literals in Python. They are true and false. In
Python, True represents the value as 1, and False represents the value as 0. In this
example ‘a‘ is True and ‘b‘ is False because 1 is equal to True.
Python literal collections
Python provides four different types of literal collections:
1. List literals
2. Tuple literals
3. Dict literals
4. Set literals
List literal
The list contains items of different data types. The values stored in the List are
separated by a comma (,) and enclosed within square brackets([]). We can store
different types of data in a List. Lists are mutable.
Tuple literal
A tuple is a collection of different data-type. It is enclosed by the parentheses
‘()‘ and each element is separated by the comma(,). It is immutable.
Dictionary literal
The dictionary stores the data in the key-value pair. It is enclosed by curly
braces ‘{}‘ and each pair is separated by the commas(,). We can store different types
of data in a dictionary. Dictionaries are mutable.
Set literal
Set is the collection of the unordered data set. It is enclosed by the {} and each
element is separated by the comma(,).
Python Special literal
Python contains one special literal (None). ‘None’ is used to define a null
variable. If ‘None’ is compared with anything else other than a ‘None’, it will
return false.
Python Constants
• A Python Constant is a variable whose value cannot be changed throughout the
program.
Certain values are fixed and are universally proven to be true. These values cannot be
changed over time. Such types of values are called as Constants.
Rules to be followed while declaring a Constant
1. Python Constants and variable names should contain a combination of lowercase
(a-z) or capital (A-Z) characters, numbers (0-9), or an underscore ( ).
2. When using a Constant name, always use UPPERCASE, For example, CONSTANT
= 50.
3. The Constant names should not begin with digits.
4. Except for underscore(_), no additional special character (!, #, ^, @, $) is utilized
when declaring a constant.
5. We should come up with a catchy name for the python constants. VALUE, for
example, makes more sense than V. It simplifies the coding process.
Assigning Values to Constants
Constants are typically declared and assigned in a module in Python. In this case,
the module is a new file containing variables, functions, and so on that is imported into
the main file. Constants are written in all capital letters with underscores separating the
words within the module.
We create a separate file for declaring constants. We then use this file to import the
constant module in the main.py file from the other file.
Example
Assigning Values to Constants
Constants are typically declared and assigned in a module in Python. In this case,
the module is a new file containing variables, functions, and so on that is imported into
the main file. Constants are written in all capital letters with underscores separating the
words within the module.
We create a separate file for declaring constants. We then use this file to import the
constant module in the main.py file from the other file.
Example
# create a separate constant.py file
PI = 3.14
GRAVITY = 9.8
# main.py file
import constant as const
print('Value of PI:', cons.PI)
print('Value of Gravitational force:', cons.GRAVITY)
Output
Value of PI: 3.14
Value of Gravitational force: 9.8

Python Variables
• A Variable is a location that is named in order to store data while the program is
being run.
• In a programming language, Variables are words that are used to store values of
any data type.
In simple words, when you create a variable, it takes up some memory space based on the
value and the type you set to it. The Python interpreter allocates RAM to the variable
based on its data type. The variables’ values can be altered at any time during the
program.
An Identifier is a term used in programming language in order to denote unique name
given to these variables.
Syntax
variable_name = data values
where, variable_name = combination of letters, numbers and an underscore
Rules to be followed while declaring a Variable name
1. A Variable’s name cannot begin with a number. Either an alphabet or the
underscore character should be used as the first character.
2. Variable names are case-sensitive and can include alphanumeric letters as well
as the underscore character.
3. Variable names cannot contain reserved terms.
4. The equal to sign ‘=’, followed by the variable’s value, is used to assign variables
in Python.
Assigning values to Variables in Python
There are few different methods to assign data elements to a Variable. The most common
ones are described below –
1. Simple declaration and assignment of a value to the Variable
In this type, the data values are directly assigned to the Variables in the declaration
statement.
Example
num = 10
numlist = [1, 3, 5, 7, 9]
str = 'Hello World'

print(num)
print(numlist)
print(str)
Output
10
[1, 3, 5, 7, 9]
Hello World
Here, we have created 3 variables named as ‘num’, ‘numlist’, and ‘str’. We have
assigned all the 3 variables an int value 10, a list of integers, and a string of characters
respectively.
Keywords in Python
Python Keywords are some predefined and reserved words in Python that
have special meanings. Keywords are used to define the syntax of the coding. The
keyword cannot be used as an identifier, function, or variable name. All the keywords
in Python are written in lowercase except True and False. There are 35 keywords in
Python 3.11.
In Python, there is an inbuilt keyword module that provides an iskeyword()
function that can be used to check whether a given string is a valid keyword or not.
Furthermore, we can check the name of the keywords in Python by using the kwlist
attribute of the keyword module.
Rules for Keywords in Python
• Python keywords cannot be used as identifiers.
• All the keywords in Python should be in lowercase except True and False.
List of Python Keywords
Keywords Description

This is a logical operator which returns true if both the operands are
and
true else returns false.

This is also a logical operator which returns true if anyone operand


or
is true else returns false.

This is again a logical operator it returns True if the operand is false


not
else returns false.

if This is used to make a conditional statement.

Elif is a condition statement used with an if statement. The elif


elif
statement is executed if the previous conditions were not true.

Else is used with if and elif conditional statements. The else block is
else
executed if the given condition is not true.

for This is used to create a loop.

while This keyword is used to create a while loop.


Keywords Description

break This is used to terminate the loop.

as This is used to create an alternative.

def It helps us to define functions.

lambda It is used to define the anonymous function.

pass This is a null statement which means it will do nothing.

return It will return a value and exit the function.

True This is a boolean value.

False This is also a boolean value.

try It makes a try-except statement.

with The with keyword is used to simplify exception handling.

This function is used for debugging purposes. Usually used to check


assert
the correctness of code

class It helps us to define a class.

continue It continues to the next iteration of a loop

del It deletes a reference to an object.

except Used with exceptions, what to do when an exception occurs

Finally is used with exceptions, a block of code that will be executed


finally
no matter if there is an exception or not.

from It is used to import specific parts of any module.

global This declares a global variable.


Keywords Description

import This is used to import a module.

It’s used to check whether a value is present in a list, range, tuple,


in
etc.

is This is used to check if the two variables are equal or not.

This is a special constant used to denote a null value or avoid. It’s


none important to remember, 0, any empty container(e.g empty list) do
not compute to None

nonlocal It’s declared a non-local variable.

raise This raises an exception.

yield It ends a function and returns a generator.

async It is used to create asynchronous coroutine.

await It releases the flow of control back to the event loop.

Identifiers in Python
Identifier is a user-defined name given to a variable, function, class, module,
etc. The identifier is a combination of character digits and an underscore. They are
case-sensitive i.e., ‘num’ and ‘Num’ and ‘NUM’ are three different identifiers in python.
It is a good programming practice to give meaningful names to identifiers to make
the code understandable.
We can also use the Python string isidentifier() method to check whether a
string is a valid identifier or not.
Rules for Naming Python Identifiers
• It cannot be a reserved python keyword.
• It should not contain white space.
• It can be a combination of A-Z, a-z, 0-9, or underscore.
• It should start with an alphabet character or an underscore ( _ ).
• It should not contain any special character other than an underscore ( _ ).
Examples of Python Identifiers
Valid identifiers:
• var1
• _var1
• _1_var
• var_1
Invalid Identifiers
• !var1
• 1var
• 1_var
• var#1
• var 1
Built-in Data Types
• In programming, data type is an important concept.
• Variables can store data of different types, and different types can do different
things.
• Python has the following data types built-in by default, in these categories:

Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType

Getting the Data Type


You can get the data type of any object by using the type() function:
Example
Print the data type of the variable x:
x=5
print(type(x))
Setting the Data Type
In Python, the data type is set when you assign a value to a variable:

Example Data Type

x = "Hello World" str


x = 20 int

x = 20.5 float

x = 1j complex

x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

x = range(6) range

x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = frozenset({"apple", "banana", "cherry"}) frozenset

x = True bool

x = b"Hello" bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview

x = None NoneType

Output Statements

The Python print() function is often used to output variables.

Example
x = "Python is awesome"
print(x)
OUTPUT

Python is awesome

In the print() function, you output multiple variables, separated by a comma:

x = "Python"
y = "is"
z = "awesome"
print(x, y, z)

OUTPUT

Python is awesome

You can also use the + operator to output multiple variables:

x = "Python "
y = "is "
z = "awesome"
print(x + y + z)

OUTPUT

Python is awesome

For numbers, the + character works as a mathematical operator:

x=5
y = 10
print(x + y)

OUTPUT

15

Input Statements
Example
Python input() function is used to get input from the user. It prompts for the user input
and reads a line. After reading data, it converts it into a string and returns that. It throws
an error EOFError if EOF is read.
print('Enter your name:')
x = input()
print('Hello, ' + x)
OUTPUT
Enter your name: computer
Hello computer
Definition and Usage
The input() function allows user input.
Syntax
input(prompt)
Parameter Values
Prompt → A String, representing a default message before the input.
Example
Use the prompt parameter to write a message before the input:
x = input('Enter your name:')
print('Hello, ' + x)
Comments

• Comments can be used to explain Python code.

• Comments can be used to make the code more readable.

• Comments can be used to prevent execution when testing code.

Creating a Comment
Comments starts with a #, and Python will ignore them:
#This is a comment
print("Hello, World!")
OUTPUT
Hello, World!
Comments can be placed at the end of a line, and Python will ignore the rest of the
line:
print("Hello, World!") #This is a comment
Multiline Comments
• Python does not really have a syntax for multiline comments.
• To add a multiline comment you could insert a # for each line:
Python Indentation

• Indentation refers to the spaces at the beginning of a code line.


• Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.

• Python uses indentation to indicate a block of code.

Example

if 5 > 2:

print("Five is greater than two!")

OUTPUT

Five is greater than two!

Python will give you an error if you skip the indentation:

Example

Syntax Error:

if 5 > 2:
print("Five is greater than two!")

Python Operators
Python operators are special symbols (sometimes called keywords) that are
used to perform certain most commonly required operations on one or more
operands (value, variables, or expressions).
Types of Operators in Python
Python language supports the following types of operators −
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Python Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations such
as addition, subtraction, multiplication, etc.
Assume variable a holds 10 and variable b holds 20, then

Operator Name Example

+ Addition a + b = 30
- Subtraction a – b = -10

* Multiplication a * b = 200

/ Division b/a=2

% Modulus b%a=0

** Exponent a**b =10**20

// Floor Division 9//2 = 4


Python Comparison Operators
Comparison operators compare the values on either side of them and decide the
relation among them. They are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then

Operator Name Example

== Equal (a == b) is not true.

!= Not equal (a != b) is true.

> Greater than (a > b) is not true.

< Less than (a < b) is true.

>= Greater than or equal to (a >= b) is not true.

<= Less than or equal to (a <= b) is true.


Python Assignment Operators
Assignment operators are used to assign values to variables. Following is a table
which shows all Python assignment operators.

Operator Example Same As

= a = 10 a = 10

+= a += 30 a = a + 30

-= a -= 15 a = a - 15

*= a *= 10 a = a * 10

/= a /= 5 a=a/5
%= a %= 5 a=a%5

**= a **= 4 a = a ** 4

//= a //= 5 a = a // 5

&= a &= 5 a=a&5

|= a |= 5 a=a|5

^= a ^= 5 a=a^5

>>= a >>= 5 a = a >> 5

<<= a <<= 5 a = a << 5

Python Bitwise Operators


Bitwise operator works on bits and performs bit by bit operation. These
operators are used to compare binary numbers.
There are following Bitwise operators supported by Python language

Operator Name Example

& AND a&b

| OR a|b

^ XOR a^b

~ NOT ~a

<< Zero fill left shift a << 3

>> Signed right shift a >> 3

Python Logical Operators


Python logical operators are used to combile two or more conditions and check
the final result. There are following logical operators supported by Python language.
Assume variable a holds 10 and variable b holds 20 then

Operator Name Example

and AND a and b

or OR a or b
not NOT not(a)
Python Membership Operators
Python's membership operators test for membership in a sequence, such as
strings, lists, or tuples. There are two membership operators as explained below −

Operator Description Example

in Returns True if it finds a variable in the a in b


specified sequence, false otherwise.
not in returns True if it does not finds a variable in a not in b
the specified sequence and false otherwise.
Python Identity Operators
Identity operators compare the memory locations of two objects. There are two
Identity operators explained below −

Operator Description Example

is Returns True if both variables are the same a is b


object and false otherwise.
is not Returns True if both variables are not the same a is not b
object and false otherwise.
Python Operators Precedence
The following table lists all operators from highest precedence to lowest.

Sr.No. Operator & Description

1 **
Exponentiation (raise to the power)

2 ~+-
Complement, unary plus and minus (method names for the last
two are +@ and -@)

3 * / % //
Multiply, divide, modulo and floor division

4 +-
Addition and subtraction

5 >> <<
Right and left bitwise shift

6 &
Bitwise 'AND'
7 ^|
Bitwise exclusive `OR' and regular `OR'

8 <= < > >=


Comparison operators

9 <> == !=
Equality operators

10 = %= /= //= -= += *= **=
Assignment operators

11 is is not
Identity operators

12 in not in
Membership operators

13 not or and
Logical operators
Type Conversion in Python
Python defines type conversion functions to directly convert one data type to
another which is useful in day-to-day and competitive programming. This article is
aimed at providing information about certain conversion functions.
There are two types of Type Conversion in Python:
1. Python Implicit Type Conversion
2. Python Explicit Type Conversion
Type Conversion in Python
The act of changing an object’s data type is known as type conversion. The
Python interpreter automatically performs Implicit Type Conversion. Python
prevents Implicit Type Conversion from losing data.
The user converts the data types of objects using specified functions in explicit
type conversion, sometimes referred to as type casting. When type casting, data loss
could happen if the object is forced to conform to a particular data type.
Implicit Type Conversion in Python
In Implicit type conversion of data types in Python, the Python interpreter
automatically converts one data type to another without any user involvement.
Example
As we can see the data type of ‘z’ got automatically changed to the “float” type
while one variable x is of integer type while the other variable y is of float type. The
reason for the float value not being converted into an integer instead is due to type
promotion that allows performing operations by converting data into a wider-sized
data type without any loss of information. This is a simple case of Implicit type
conversion in Python.
x = 10
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
z=x+y
print(z)
print("z is of type:",type(z))
Output
x is of type: <class 'int'>
y is of type: <class 'float'>20.6
z is of type: <class 'float'>
Explicit Type Conversion in Python
In Explicit Type Conversion in Python, the data type is manually changed by the
user as per their requirement. With explicit type conversion, there is a risk of data
loss since we are forcing an expression to be changed in some specific data
type. Various forms of explicit type conversion are explained below:
Converting integer to float
int(a, base): This function converts any data type to an integer. ‘Base’
specifies the base in which the string is if the data type is a string.
float(): This function is used to convert any data type to a floating-
point number.

# initializing string
s = "10010"
# printing string converting to int base 2
c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)

# printing string converting to float


e = float(s)
print ("After converting to float : ", end="")
print (e)
Output:
After converting to integer base 2 : 18
After converting to float : 10010.0
Python Type conversion using ord(), hex(), oct()
• ord(): This function is used to convert a character to an integer.
• hex(): This function is to convert an integer to a hexadecimal string.
• oct(): This function is to convert an integer to an octal string.
# initializing integer
s = '4'
# printing character converting to integer
c = ord(s)
print ("After converting character to integer : ",end="")
print (c)
# printing integer converting to hexadecimal string
c = hex(56)
print ("After converting 56 to hexadecimal string : ",end="")
print (c)
# printing integer converting to octal string
c = oct(56)
print ("After converting 56 to octal string : ",end="")
print (c)
Output:
After converting character to integer : 52
After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70
Python Type conversion using tuple(), set(), list()
• tuple(): This function is used to convert to a tuple.
• set(): This function returns the type after converting to set.
• list(): This function is used to convert any data type to a list type.

# initializing string
s = 'geeks'

# printing string converting to tuple


c = tuple(s)
print ("After converting string to tuple : ",end="")
print (c)

# printing string converting to set


c = set(s)
print ("After converting string to set : ",end="")
print (c)

# printing string converting to list


c = list(s)
print ("After converting string to list : ",end="")
print (c)
Output:
After converting string to tuple : ('g', 'e', 'e', 'k', 's')
After converting string to set : {'k', 'e', 's', 'g'}
After converting string to list : ['g', 'e', 'e', 'k', 's']
Python code to demonstrate Type conversion using dict(), complex(), str()
dict(): This function is used to convert a tuple of order (key, value) into a dictionary.
str(): Used to convert an integer into a string.
complex(real,imag) : This function converts real numbers to complex(real,imag)
number.

# initializing integers

a=1

b=2
# initializing tuple

tup = (('a', 1) ,('f', 2), ('g', 3))

# printing integer converting to complex number

c = complex(1,2)

print ("After converting integer to complex number : ",end="")

print (c)

# printing integer converting to string

c = str(a)

print ("After converting integer to string : ",end="")

print (c)

# printing tuple converting to expression dictionary

c = dict(tup)

print ("After converting tuple to dictionary : ",end="")

print (c)

Output:
After converting integer to complex number : (1+2j)
After converting integer to string : 1
After converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3}
What Is an Array?
An array is a data structure that lets us hold multiple values of the same data type.
Think of it as a container that holds a fixed number of the same kind of object. Python
makes coding easier for programmers.
Why Use an Array in Python?
An array is used to store more than one value at a time. It can hold multiple values in a
single variable, and also helps you reduce the overall size of the code. Arrays save time.
Syntax to Create an Array in Python
You can declare an array in Python while initializing it using the following syntax.
arrayName = array.array(type code for data type, [array,items])
The following image explains the syntax.
Array Syntax
1. Identifier: specify a name like usually, you do for variables
2. Module: Python has a special module for creating array in Python, called “array”
– you must import it before using it
3. Method: the array module has a method for initializing the array. It takes two
arguments, type code, and elements.
4. Type Code: specify the data type using the type codes available (see list below)
5. Elements: specify the array elements within the square brackets, for example
[130,450,103]
How to create arrays in Python?
In Python, we use following syntax to create arrays:
Class array.array(type code[,initializer])
For Example
import array as myarray
abc = myarray.array('d', [2.5, 4.9, 6.7])
The above code creates an array having integer type. The letter ‘d’ is a type code.
Following tables show the type codes:

Type code Python type C Type Min size(bytes)

‘u’ Unicode character Py_UNICODE 2

‘b’ Int Signed char 1

‘B’ Int Unsigned char 1

‘h’ Int Signed short 2

‘l’ Int Signed long 4

‘L’ Int Unsigned long 4

‘q’ Int Signed long long 8

‘Q’ Int Unsigned long long 8

‘H’ Int Unsigned short 2

‘f’ Float Float 4


Type code Python type C Type Min size(bytes)

‘d’ Float Double 8

‘i’ Int Signed int 2

‘I’ Int Unsigned int 2

How to access array elements?


You can access any array item by using its index.
The syntax is
arrayName[indexNum]
For example,
import array
balance = array.array('i', [300,200,100])
print(balance[1])
Output:
200
The following image illustrates the basic concept of accessing arrays items by their
index.

Accessing Array Item


Here, we have accessed the second value of the array using its index, which is 1. The
output of this will be 200, which is basically the second value of the balanced array.
The array index starts with 0. You can also access the last element of an array using the
-1 index.
Example:
import array as myarray
abc = myarray.array('d', [2.5, 4.9, 6.7])
print("Array first element is:",abc[0])
print("Array last element is:",abc[-1])
Output:
Array first element is: 2.5
Array last element is: 6.7
You can also access elements by using the ‘:’ operator as shown in below Python arrays
examples.
Example:
import array as myarray
abc= myarray.array('q',[3,9,6,5,20,13,19,22,30,25])
print(abc[1:4])
print(abc[7:10])
Output:
array('q', [9, 6, 5])
array('q', [22, 30, 25])
This operation is called a slicing operation.
Array Methods
Python has a set of built-in methods that you can use on lists/arrays.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the
current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value


reverse() Reverses the order of the list

sort() Sorts the list

The Append() method


If you want to add an item to the end of a list, you can utilize the append method.
Example:
fruits = ['apple', 'banana', 'cherry']
fruits.append('orange')
print(fruits)
# Output: ['apple', 'banana', 'cherry', 'orange']
The append() method is used to add elements to the end of a list. In this case, 'orange'
is appended to the fruits list, resulting in the list containing four elements: 'apple',
'banana', 'cherry', and 'orange'.
The Clear() method
The clear() method removes all the elements from the list, just as the name implies.
Example:
Below is an example using the clear() method:
cars = ["Lexus", "Toyota", "Mercedez"]
cars.clear()
print(cars)
Output:
Based on the explanation of the clear() method above, the result of this expression will
be [] empty because we have cleared the entire list.
The Copy() method
This function creates and returns an identical copy of the original list.
Example:
fruits = ["apple", "banana", "cherry"]
fruits_copy = fruits.copy()
print(fruits_copy)

# Output: ['apple', 'banana', 'cherry']


In the above example, the copy() method creates a new array called fruits_copy, which
is a shallow copy of the fruits array. Modifying the fruits_copy array will not affect the
original fruits array.
Here's another example using the copy() method:
cars = ["Lexus", "Toyota", "Mercedez"]
x = cars.copy()
print(x)

# Output of the above using the copy () method will be:


["Lexus", "Toyota", "Mercedez"]
The Count() method
This method returns the number of elements with the specified value.
Example:
fruits = ["apple", "banana", "cherry", "banana"]
count = fruits.count("banana")
print(count)

# Output: 2
The code above creates a list called fruits with four elements: 'apple', 'banana',
'cherry', and another 'banana'. The count() method is then used on the fruits list to
count the number of occurrences of the element 'banana'. It returns the count, which
in this case is 2, as 'banana' appears twice in the list.
Finally, the count value is printed to the console, resulting in the output: 2.
Here's another example of using the count() method:
# Return the number of times the value "Lexus" appears in the car list.

cars = ["Lexus", "Toyota", "Mercedez", "Lexus"]


x = cars.count("Lexus")
print(x)
Output of this would return int "2" as the result because "Lexus" appears twice in the
cars list.
The Extend() method
With this method, you can add the elements of a list (or any iterable) to the end of the
current list.
Example:
fruits = ["apple", "banana", "cherry"]
additional_fruits = ["orange", "grape"]
fruits.extend(additional_fruits)
print(fruits)

# Output: ['apple', 'banana', 'cherry', 'orange', 'grape']


In the example above, the extend() method is used to add the elements from
the additional_fruits list to the fruits array. The resulting array contains all the
elements from both arrays.
Note that the extend() method modifies the original array in place and does not return
a new array.
The index() method
This method returns the index of the first element with the specified value.
fruits = ["apple", "banana", "cherry"]
index = fruits.index("banana")
print(index)

# Output: 1
This code above creates a list of fruits containing 'apple', 'banana', and 'cherry'. It then
finds the index position of 'banana' in the list and assigns it to the variable 'index'.
Finally, it prints the value of 'index', which in this case would be 1.
The insert() method
This array method adds an element at the specified position.
numbers = [1, 2, 3, 5, 6]
numbers.insert(3, 4)
print(numbers)

# Output: [1, 2, 3, 4, 5, 6]
From the code above, we have an array numbers with elements [1, 2, 3, 5, 6]. We want
to insert the number 4 at index 3 (which is the fourth position in the array, as Python
is 0-indexed). By calling insert(3, 4), we insert the element 4 at the specified index, and
the existing elements are shifted to the right to make room for the new element. The
resulting array is [1, 2, 3, 4, 5, 6].
The pop() method
This method removes the element at the specified position.
Example:
# To delete an item from an array/list, you can utilize the pop() method.
# Delete the second element of the car array:
cars = ["Lexus", "Toyota", "Mercedez"]
cars.pop(2)
print(cars)
And here's the output:
['Lexus', 'Toyota']
This code above deletes the second element from the 'cars' array using the 'pop()'
method and then prints the updated array.
Here's another example using the pop() method:
# To delete an item from an array/list, you can utilize the pop() method.
# Delete the second element of the car array:
cars = ["Lexus", "Toyota", "Mercedez"]
cars.pop(2)
print(cars)

Output:

['Lexus', 'Toyota']
The code deletes the second element from the `cars` array using the `pop()` method
and then prints the modified array. The resulting array will contain only the first and
third elements: ['Lexus', 'Toyota'].
The remove() method
This method removes the first item with the specified value.
Example:
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)

# Output Below:

["apple", "cherry"]
The code above creates a list called fruits with three elements: 'apple', 'banana', and
'cherry'. The remove() method is then used to remove the element 'banana' from the
list.
After removing 'banana', the updated list is printed using the print() function. The
output will be ['apple', 'cherry'], as 'banana' is no longer present in the list.
Here's another example using the remove() method:
cars = ["Lexus", "Toyota", "Mercedez"]

cars.remove("Toyota")

print(cars)
The remove() function may also be used to remove an element from an array, but it
should be noted that it only removes the first instance of the specified value from a list.
The reverse() method
This method reverses the order of the list.
Example:
fruits = ["apple", "banana", "cherry"]
fruits.reverse()
print(fruits)

# Output: ['cherry', 'banana', 'apple']


The code above creates a list called fruits with three elements: 'apple', 'banana', and
'cherry'. Then, the reverse() method is called on the fruits list which reverses the order
of its elements. Finally, the reversed list is printed using the print() function, resulting
in the output ['cherry', 'banana', 'apple']. This means that the original order of the fruits
list has been reversed.
The sort() method
This method sorts the list, just as the name implies.
Example:
numbers = [4, 2, 1, 3]
numbers.sort()
print(numbers)

# Output: [1, 2, 3, 4]
The code above creates a list called numbers with the elements [4, 2, 1, 3].
The sort() method is then called on the numbers list, which sorts the elements in
ascending order. After sorting, the numbers list becomes [1, 2, 3, 4]. Finally, the sorted
list is printed to the console using print(numbers), which outputs [1, 2, 3, 4].
the sort() method in Python sorts the elements of a list in ascending order by default.
If you want to sort the list in descending order, you can pass the
parameter reverse=True to the sort() method.
Here's an example of how to sort the numbers list in descending order:
numbers = [4, 2, 1, 3]
numbers.sort(reverse=True)
print(numbers)

# Output

[4, 3, 2, 1]
By passing reverse=True as an argument to the sort() method, the list is sorted in
descending order.

You might also like