0% found this document useful (0 votes)
10 views40 pages

Python Notes

The document provides an introduction to Python programming, covering its definition, history, and evolution through various versions. It explains the Python interpreter's functioning, including lexing, parsing, byte code creation, and execution. Additionally, it highlights Python's features, applications, and data types, emphasizing its versatility and relevance in modern programming.

Uploaded by

nickneha4340
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)
10 views40 pages

Python Notes

The document provides an introduction to Python programming, covering its definition, history, and evolution through various versions. It explains the Python interpreter's functioning, including lexing, parsing, byte code creation, and execution. Additionally, it highlights Python's features, applications, and data types, emphasizing its versatility and relevance in modern programming.

Uploaded by

nickneha4340
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

CA212 Python Programming

UNIT 1 - Introduction to python


Chapter-1
Program
A program is a set of instructions instructing a computer to do a specific task.

Software

Software is a generic term used to describe computer programs to perform a specific task .

What is Python?
Python is an interpreted, high-level, general-purpose programming language. Python is an open
source and cross-platform programming language that has become increasingly popular over the
years. It was created by Guido van Rossum and first released in 1991.

Python is a multi-purpose programming language, examples are scientific computing and


calculations, simulations, web development (using, e.g., the Django Web framework), etc.

The programming language is maintained and available from Python Software Foundation:
[Link] Here you can download the basic Python features in one package,
which includes the Python programming language interpreter, and a basic code editor, or an
integrated development environment, called IDLE.

The python interpreter is a very basic editor, and the minimum needed to create basic Python
programs. To solve complex tasks we need to install and use separate Python packages created
by third parties like Anaconda.

Interpreted vs. Compiled


Programming languages generally fall into one of two categories: Compiled or Interpreted. Both
the languages have their own advantages and disadvantages.

A compiled language is a programming language that is converted into machine code so that the
processor can execute it. The overhead for the translation is incurred just once, when the source
is compiled; thereafter, it need only be loaded and executed. It is faster than interpreted language.
Compiled languages are better for permanent applications where speed is in [Link] compiled
languages are usually compiled, not interpreted. For example – COBOL, C, C++, C#, etc.
An interpreted language is also a programming language that is commonly interpreted.
Interpreted language must be parsed, interpreted, and executed each time the program is run. . It
is reduced to machine instructions at run-time. For this reason interpreted programs are less
efficient than compile programs. An interpreted language is generally more suited for doing ‖ad
hoc‖ calculations or simulations. For example: Python, BASIC, JavaScript, Perl, etc.

What is an Python Interpreter?


The Python interpreter works as a computer converter that converts high-level language to low-
level machine language, which is essential for the computer to understand the code written by a
programmer. Python codes are executed by an interpreter called CPython, which is written in C
language and executes instructions in a block of code one line after another.

Steps used

1. Lexing
2. Parsing
3. Creation of byte code
4. Conversion to machine-executable code
5. Returning output

Step 1: Lexing

Analyzing a code block in Python starts with Lexing, wherein the single line of code being
executed by the interpreter and converted into smaller parts. Each of these parts is called a token,
and these tokens are generated by the lexer, which is a part of the Python interpreter. Essentially,
Here the interpreter breaks down the user instruction into small pieces, to process it piecewise.

Step 2: Parsing

Another component of the Python interpreter called the Parser performs the process of Parsing.
Parsing is a process in which the tokens generated in the Lexing stage into a structure
called Abstract Syntax Tree. This tree shows the relationship between the tokens generated from
a particular line of code and checks for syntax errors, and if an error is found, the interpreter
stops translating code and shows an error message.
Step 3: Creation of Byte Code

The compiler(a part of interpreter) converts the Abstract Syntax Tree into an intermediate
language code, called bytecode . This is a compiled version of the original code which is a low-
level, platform independent representation. This byte code is stored in a file with the same name
as the original source file, but with a ‗.pyc‘ extension instead of ‗.py‘. This is a step completely
hidden from the developer which happens internally, and is performed as executing byte code is
much faster than original code statements.

Step 4: Conversion to Machine-executable Code

The PVM(Python Virtual Machine ) is the actual runtime engine of Python, and can be
summarized as a big loop which iterates through the byte code instructions stored in the file with
.pyc extension statement wise. Then it converts the statements into machine code, that is binary
(0s and 1s). It also integrates and loads the inputs and libraries involved in the program, so that
the required instructions can be carried out successfully. The PVM is the part of the interpreter
that truly executes Python scripts.

Step 5: Returning Output

After the code is converted to binary, it is executed by the interpreter. If there is an error, it
displays the message and exits. Such an error is called a runtime error. If there is no runtime
error during program execution, then the interpreter prints the output and exits successfully.

History of Python
Python was developed by Dutch programmer Guido van Rossum in the late 1980s and He began
working on Python in December 1989 as a hobby project while working at the Centrum
Wiskunde & Informatica (CWI) in the Netherlands. Python's first version (0.9.0) was released in
1991.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,
SmallTalk, and Unix shell and other scripting languages. Guido van Rossum wanted Python to
be a high-level language that was powerful yet readable and easy to use.

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

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.
Evaluation of python

Python 0.9.0

Python's first published version is 0.9. It was released in February 1991. It consisted of features
such as classes with inheritance, exception handling, and core data types like lists and
dictionaries..

Python 1.0

In January 1994, version 1.0 was released, armed with functional programming tools, features
like support for complex numbers etc and module system which allows a better code
organization and reuse.

Python 2.0

The 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. Throughout
the 2000s, Python 2.x became the dominant version, gaining traction in industries ranging from
web development to scientific research. Various useful libraries like NumPy, SciPy, and Django
were also developed.

Python 3.0

Python 3.0, a completely renewed 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 back ported to Python 2.6. It also included a utility named as python
2to3 to facilitate automatic translation of Python 2 code to Python 3. Python 3 provided new
syntax, unicode support and Improved integer division.

EOL(End of Line) for Python 2.x

Even after the release of Python 3, Python Software Foundation continued to support the Python
2 branch with incremental micro versions till 2019. However, it decided to discontinue the
support by the end of 2020, at which time Python 2.7.17 was the last version in the branch.

Current Version of Python

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

Python 3.13 is the latest stable release of the Python programming language, with a mix of
changes to the language, the implementation and the standard library. The biggest changes
include a new interactive interpreter, experimental support for running in a free-threaded
mode (PEP 703), and a Just-In-Time compiler (PEP 744). Error messages continue to improve,
with tracebacks now highlighted in color by default. The library changes contain removal of
deprecated APIs and modules, as well as the usual improvements in user-friendliness and
correctness.

Python in the Future

Python is evolving everyday where Python 3.x receives regular updates. Python's developers
community is focusing on performance improvements making it more efficient while retaining
its ease of use.

Python is being heavily used for machine learning, AI, and data science, so for sure its future
remains bright. It's role in these rapidly growing fields ensures that Python will stay relevant for
years.

Python is also increasingly becoming the first programming language taught in schools and
universities worldwide, solidifying its place in the tech landscape.

Why Python?

● Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
● Python has a simple syntax similar to the English language.
● Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
● Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
● Python can be treated in a procedural way, an object-oriented way or a functional way.\

Features of python
Here are the top features of Python that make it a standout programming language:

1. GUI Programming Support

Python supports GUI programming through libraries such as Tkinter, PyQt, and Kivy, making it
easy to create user-friendly desktop applications. These libraries provide tools and widgets to
build interactive, cross-platform graphical user interfaces.

2. Object-Oriented Programming

Python is fully object-oriented, enabling developers to create classes and objects to model real-
world entities. Features like inheritance, encapsulation, and polymorphism are supported, making
it easier to build complex applications using reusable and organized code.
3. Dynamic Language

Python is dynamically typed, meaning that variable types are determined at runtime. This allows
for more flexibility in coding since developers do not need to declare variable types explicitly,
speeding up development process.

4. Easy to Code

Python's simple and readable syntax makes it one of the most beginner-friendly programming
languages. It emphasizes readability and reduces code complexity, enabling quick development
and accessible learning for newcomers.

5. Free and Open-Source

Python is free to download, use, and distribute, as it is open-source under the Python Software
Foundation License. This makes it accessible to everyone, fostering innovation and collaborative
improvements within the community.

6. High-level Programming Language

As a high-level programming language, Python abstracts complex tasks, allowing developers to


focus more on problem-solving rather than low-level details like memory management or
hardware architecture.

7. Interpreted Language

Python is an interpreted language, meaning code is executed line by line at runtime without
requiring prior compilation. This simplifies debugging and testing, enhancing the development
workflow.

8. Standard Library

This is one of the key features of Python. Python has a vast standard library that provides built-in
modules and functions for tasks such as file I/O, web development, data manipulation, regular
expressions, and more. This reduces the need for external dependencies and speeds up
development.

9. Community Support

Python boasts a large and active community of developers. This means extensive documentation,
tutorials, forums, and open-source libraries are readily available, making it easier for developers
to find support and contribute to the language.
10. Portable Language

Python code can run on various operating systems like Windows, Linux, macOS, and more
without modification. This cross-platform portability enables developers to create software that
can be executed in multiple environments seamlessly.

11. Databases

Python offers excellent support for database connectivity. Libraries like SQLite3, SQLAlchemy,
and PyMySQL allow developers to interact with databases, execute queries, and manage data
efficiently, making Python suitable for building database-driven applications.

12. Extensible

Python can be extended with code written in languages like C or C++. This allows for enhanced
performance and the ability to use existing libraries and modules from other ecosystems within
Python programs.

13. Cross Platform

Python is cross-platform, allowing the same codebase to be run on different operating systems
without modification. This is essential for developing software that needs to be compatible
across various devices and platforms.

14. Enhancements to Python Types

Python supports enhancements and type hints through tools like typing and type checkers such as
mypy. This allows developers to specify types for variables, function parameters, and return
values, leading to better readability and fewer runtime errors.

15. Frontend and Backend Development

While primarily used for backend development in frameworks like Django and Flask, Python can
also be used in the front end through frameworks like Brython or Pyodide. This flexibility makes
Python a versatile choice for full-stack development
Applications of Python
Here is a list of popular applications of Python:
1. Web Development: Using frameworks like Django, Flask, and FastAPI.
2. Data Science and Analytics: For data manipulation and visualization with libraries like
Pandas, NumPy, and Matplotlib.
3. Machine Learning and AI: With powerful libraries like TensorFlow, PyTorch, and scikit-
learn.
4. Game Development: Utilizing libraries like Pygame.
5. Desktop GUI Applications: Using Tkinter, PyQt, and Kivy.
6. Web Scraping: Through tools like Beautiful Soup and Scrapy.
7. Automation/Scripting: Writing scripts for task automation and system administration.
8. Network Programming: This is used to build networked applications using libraries such as
Socket and Twisted.
9. Cybersecurity and Penetration Testing: Employed to write security tools and scripts.
10. Robotics and Embedded Systems: Using frameworks like MicroPython.
11. Finance and Fintech: For quantitative analysis, financial modeling, and algorithmic trading.
12. Blockchain Development: Creating smart contracts and blockchain solutions.
13. Education: Widely used as a teaching tool in computer science courses due to its simplicity.
14. Cloud Computing: Employed in cloud environments for automation, serverless
applications, and more.
15. Audio and Video Processing: With libraries like OpenCV and PyDub.
16. Scientific Computing: Using libraries like SciPy for complex mathematical and scientific
tasks.
17. Chatbots and Conversational Interfaces: Using libraries like ChatterBot.
18. E-commerce Solutions: Backend development for online stores and inventory management
systems.
19. Business Applications: Developing enterprise software, ERP systems, and other business
solutions.
20. IoT (Internet of Things): Integrating with hardware and IoT platforms for smart
applications
Chapter 2
Standard Data types
What is a Data Type in Python?

Python data types are referred to as the classification of different data items. It represents
different types of variables that inform what operations a user can perform on specific data items.
Since everything in the Python programming language is identified as an object, data types are
classified as classes and variables as objects of the same classes.
A variable holding a value will always have a data type. With Python being a dynamic type of
programming language, there is no need for the users to specify the variable type while declaring
it. It is the interpreter who implicitly binds the value of the variable with the data type. Moreover,
Python provides the type () function to determine a particular variable‘s data type.
For example –
a=6
The variable in the given example holds an integer value of six, and the data type is not defined.
Python interpreter will implicitly interpret the variable ‗a‘ as an integer type.

Built-in Python Data Types


● Numeric
● Sequence Type
● Boolean
● Set
● None
● Dictionary

Mutable Data Type in Python


The mutable data types are those data types whose values can be changed after creating them.
The following are the mutable data types in Python:
● Lists
● Dictionary
● Sets

Immutable Data Type


The immutable data types are those data sets whose values can‘t be changed after creating them.
The following are the immutable data types in Python:
● Numeric
● Strings
● Tuples
 Numeric Data Type
The numeric data types represent or store the data having numeric values. Python numeric data
type can be in the form of an integer, floating values, or complex numbers. Python uses int, float,
and complex classes to define these values.

It supports the following listed numeric data types:

Integers (int)
The numeric data type represented by the int class, integers, includes positive and negative whole
numbers, excluding fractions and decimals. In Python, there is no limitation on the length of the
integer value. For example, 5, 13, 87, -65, -47, -98, etc.

Floating Numbers (float)


The numeric data type is represented by the float class, the floating numbers contain real,
floating-point numbers. For example, 1.6, 6.65, 43.8, etc. This specific class can store floating-
point numeric values up to 15 decimal points.

Complex Numbers (complex)


The numeric data type represented by the complex class, the complex numbers, contain an
ordered pair- x + by [(real part + imaginary part)j]. For example, 3 + 6j, 7 + 5j, etc.

 Sequence Data Type


The sequence data type represents the ordered collection of similar or different data types. With
the help of sequence data type, users can store several values in an organized and efficient way.

Python supports the following listed sequence data types:

String
In Python, strings are a sequence of bytes that represents Unicode characters. A string is
typically a collection of one or more characters that a user can put in a single, double, or triple
quote. The ‗str‘ class represents the string data type in Python. Python provides built-in functions
and operators for performing operations in the string.

Example: str1= ‗python programming‘

List
The list data type is similar to the arrays – an ordered collection of data. This data type is
relatively flexible since there is no need for the items in the list to be of the same type. You can
create lists in Python simply by putting the items inside the square brackets []. Subsequently, to
separate the items stored in the lists, you can use a comma (,).

Example: ages = [19, 26, 29]


Tuple
Similar to the list data type, the tuple data type in Python is also an ordered collection of items of
different types. One single difference between these two data types is that tuples are immutable
and thus, you can‘t modify them after creating the same. The class ‗tuple‘ represents the tuple
data type. You can create a tuple in Python simply by putting the items inside the parentheses ().
Subsequently, to separate the items stored in the tuple, you can use a comma (,).

Example: tup1=('a','b','c')

Boolean Data Type

The boolean data type provides two built-in values, which are ‗True‘ and ‗False‘. These two
values help in determining if the given statement is true or false. Boolean objects that are true are
referred to as truthy (true), and false Boolean objects are referred to as falsy (false).

However, Python allows evaluating the non-Boolean objects in the Boolean context and
determining whether they are true or false. The class ‗bool‘ represents the Boolean data type. A
non-zero value or ―T‖ represents the True values, and zero or ―F‖ represents the False values.

Set Data Type

The set data type is an unordered collection of iterable, mutable, and unique data values.
Although the set contains various elements, the order of the elements remains unidentified. You
can create the set by using a built-in function set () in Python. A sequence of elements is
enclosed in the curly brackets {}, and the comma (,) is used to separate the elements. The set can
consist of various types of values.

Example: set1 = {1, 2, 3, 4}

 None Data type


None is used to define a null value or Null object in Python. It is not the same as an empty string,
a False, or a zero. It is a data type of the class NoneType object. If a function does not return
anything, it returns None in Python.

Declaring a variable as None.


var = None
# checking it's value
if var is None:
print("var has a value of None")
else:
print("var has a value")
var has a value of None
 Dictionary Data Type
A dictionary data type is an unsorted set of key-value pairs. Informational values can be stored
using this data type. The dictionary data type is more efficient because it works like an
associative array or a hash table, where each key also stores a value. A colon (:) is used to
separate each key-value pair in the Dictionary, and a comma (,) is used to separate each key.

Example: d = {1: 'Aditi', 2: 'Priya', 3: 'Kavita'}

 Type conversion Function


Type Conversion, also known as typecasting, is an important feature in Python that allows
developers to convert a variable of one type into another. In Python 3, type conversion can be
done both explicitly (manual conversion) and implicitly (automatic conversion by Python).

Types of Data Type Conversion


1) Implicit Type Conversion

In Python, implicit conversion happens automatically during operations when the interpreter can
safely transform one data type into another without losing information.

# Implicit Conversion
x=5 # Integer
y = 2.0 # Float
# Adding integer and float results in float
result = x + y
print(result)
print(type(result))
Output: 7.0
<class 'float'>

Here, Python converts the integer x into a float to perform the addition, ensuring that the result
(7.0) is a float.

2) Explicit Type Conversion

Explicit conversion or typecasting requires the developer to manually convert a variable from
one data type to another using Python's built-in functions. This is especially useful when implicit
conversion isn‘t possible or when precision is necessary.
a = "42"
b = int(a)
print(type(b))

Output
<class 'int'>
In this case, the string "42" is explicitly converted to an integer using the int() function.

Common Built-In Functions for Type Conversion


Python offers a range of built-in functions for converting data types. Below are the most
commonly used functions along with their examples:

Function Description Example


int() Converts to an integer int("42") -> 42
float() Converts to a floating-point number float("3.14") -> 3.14
str() Converts to a string str(42) -> "42"
bool() Converts to a boolean bool(1) -> True
list() Converts to a list list("abc") -> ['a', 'b', 'c']
tuple() Converts to a tuple tuple([1, 2, 3]) -> (1, 2, 3)
set() Converts to a set set([1, 2, 2]) -> {1, 2}
dict() Converts to a dictionary (from iterable dict([(1, 'a'), (2, 'b')]) -> {1: 'a', 2:
of key-value pairs) 'b'}
complex() The complex() function is used to create real_part = 3
a complex number from real and imaginary_part = 5
imaginary parts. complex_number =
complex(real_part,
imaginary_part)—>(3+5j)
Oct() the oct() function converts an integer to 64 —> 00100
an octal string.
hex() The hex() function converts an integer 255—> 0xff
to a hexadecimal string.
ord() The ord() function converts a character A—--> 65
into its corresponding Unicode code
point.
[Link]
Chapter 3
Operators in python
Python has different types of operators for different operations. They are as follows:

Arithmetic operators:
Arithmetic operators are used to perform arithmetic/mathematical operations.

Name Operator Example


Addition + a+b
Subtraction - a-b
Multiplication * a*b
Division / a/b
Exponential ** a**b
Modulus % a%b
Floor Division // a//b

Assignment operators:
These operators are used to assign values to variables.

Name Evaluated As
= a=b
+= a+=b or a=a+b
-= a-=b or a=a-b
*= a*=b or a=a*b
**= a**=b or a=a**b
/= a/=b or a=a/b
//= a//=b or a=a//b
%= a%=b or a=a%b
&= a&=b or a=a&b
** =**
^= a^=b or a=a^b
>>= a>>=b or a=a>>b
<<= a<<=b or a=a<<b

Bitwise operators:
Bitwise operators are used to deal with binary operations.
Name Operator Example
Bitwise AND & a&b
Bitwise OR | a|b
Bitwise NOT ~ ~a
Bitwise XOR ^ a^b
Bitwise right shift >> a>>
Bitwise left shift << b<<

Comparison operators:
These operators are used to compare values.
Name Operator Example
Equal == a==b
Not Equal != a!=b
Less Than < a<b
Greater Than > a>b
Less Than or Equal to <= a<=b
Greater Than or Equal to >= a>=b

Identity operators:
Name Example Evaluated As
is a is b Returns True if a and b are same
is not a is not b Returns True if a and b are not same

Logical operators:
These operators are used to deal with logical operations.
Name Operator Example
AND and a=2 and b=3
OR or a=2 or b=3
NOT not Not(a=2 or b=3)

Membership operators:
Name Example Evaluated As
in a in b Returns True if a is present in given sequence or
collection
not in a not in b Returns True if a is not present in given sequence or
collection

Operator Precedence in Python:


Name Operator
Parenthesis ()
Exponential **
Complement, unary plus, unary minus ~ , +, -
Multiply, divide, modulus, floor division *, /, %, //
Addition, subtraction +, -
Left shift and right shift operators <<, >>
Bitwise and &
Bitwise or and xor ^, |
Comparison operators <, >, >=, <=
Equality operators ==, !=
Assignment operators =, %=, /=, //=, -=, +=, *= , **=
Identity operators is, is not
Membership operators in, not in
Logical operators and, or, not
[Link]
Chapter 4
Fundamental of python Programming
 Python Identifier
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

 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.
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 true
and
else returns false.
This is also a logical operator which returns true if anyone operand is true
or
else returns false.
This is again a logical operator it returns True if the operand is false else
not
returns false.
if This is used to make a conditional statement.
Elif is a condition statement used with an if statement. The elif statement is
elif
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.
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 the
assert
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 no
finally
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.
import This is used to import a module.
in It's used to check whether a value is present in a list, range, tuple, 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 important
none 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 co routine.
await It releases the flow of control back to the event loop.

 Python Variables
Variables are used to store data that can be referenced and manipulated during program
execution. A variable is essentially a name that is assigned to a value. Unlike many other
programming languages, Python variables do not require explicit declaration of type. The type of
the variable is inferred based on the value assigned. Variables act as placeholders for data. They
allow us to store and reuse values in our program.

Example

# Variable 'x' stores the integer value 10

x=5

# Variable 'name' stores the string "Akshay"


name = " Akshay "
#printing the value of variables
print(x)
print(name)
Output -
5
Samantha

Rules for Naming Variables


To use variables effectively, we must follow Python‘s naming rules:

 Variable names can only contain letters, digits and underscores ( _ ).


 A variable name cannot start with a digit.
 Variable names are case-sensitive (myVar and myvar are different).
 Avoid using Python keywords (e.g., if, else, for) as variable names.

Valid Examples
age = 21
_colour = "lilac"
total_score = 90
Invalid Examples
1name = "Error" # Starts with a digit
class = 10 # 'class' is a reserved keyword
user-name = "Doe" # Contains a hyphen

 Assigning Values to Variables

Basic Assignment
Variables in Python are assigned values using ― = ‖ operator.
x=5
y = 3.14
z = "Hi"

Dynamic Typing
Python variables are dynamically typed, meaning the same variable can hold different types of
values during execution.
x = 10
x = "Now a string"
Multiple Assignments
Python allows multiple variables to be assigned values in a single line.

Assigning the Same Value


Python allows assigning the same value to multiple variables in a single line, which can be useful
for initializing variables with the same value.
a = b = c = 100
print(a, b, c)

Output
100 100 100

Assigning Different Values


We can assign different values to multiple variables simultaneously, making the code concise
and easier to read.
x, y, z = 1, 2.5, "Python"
print(x, y, z)

Output
1 2.5 Python

 Type Casting a Variable


Type casting refers to the process of converting the value of one data type into another. Python
provides several built-in functions to facilitate casting, including int(), float() and str() among
others.

Basic Casting Functions


int() - Converts compatible values to an integer.
float() - Transforms values into floating-point numbers.
str() - Converts any data type into a string.
 Python Comments
Comments in Python are the lines in the code that are ignored by the interpreter during the
execution of the program.

 Comments enhance the readability of the code.


 Comment can be used to identify functionality or structure the code-base.
 Comment can help understanding unusual or tricky scenarios handled by the code to
prevent accidental removal or changes.
 Comments can be used to prevent executing any specific part of your code, while making
changes or testing.

Example- # I am single line comment

""" Multi-line comment used


print("Python Comments") """

Single line comments starts with hash tag symbol ―#”.


# sample comment
name = "geeksforgeeks"
print(name)

Multi-Line Comments
Python does not provide the option for multiline comments. However, there are different ways
through which we can write multiline comments.
Multiline comments using multiple hashtags (#)

# Python program to demonstrate


# multiline comments
print("Multiline comments")

Using String Literals as Comment


Python ignores the string literals that are not assigned to a variable. So, we can use these string
literals as Python Comments.
'Single-line comments using string literals'

""" Python program to demonstrate


multiline comments"""
print("Multiline comments")
Chapter 5
Expressions in Python
An expression is a combination of operators and operands that is interpreted to produce
some other value. 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.

1. Constant Expressions: These are the expressions that have constant values only.
# 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:

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: Expressions that produce only integer results after all
computations and type conversions.
Example: # Integral Expressions
a = 13
b = 12.0
c = a + int(b)
print(c)
Output
25
4. Floating Expressions: Expressions which produce floating point numbers as result after
all computations and type conversions.
Example: # 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: # Relational Expressions
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Output
True
6. Logical Expressions: 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. Here are some logical operators in Python:
Example:- 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:
# Bitwise Expressions
a = 12
x = a >> 2
y = a << 1
print(x, y)
Output
3 24

 Statements in Python:
A statement in Python is an instruction that performs a specific action. It is the smallest
unit of code the Python interpreter can execute, usually written on a single line. Python includes
different types of statements like simple, conditional, looping, and assignment. Each statement
typically ends with a NEWLINE.

Types of Statements in Python


1. Python Simple Statements
2. Python Multi-Line Statements
3. Python Conditional and Loop Statements
 Python If
 Python if-else Statement
 Python if-elif-else Statement
 Python Nested If Statement
 Python for loop
 Python while loop
 Python try-except
 Python with statement
4. Python Expression statements
 Python return statement
 Python pass statement
 Python break statement
 Python continue statement
 Python del statement
 Python import statement
Python Simple Statements
Simple statements in Python are the smallest unit of execution that do not contain any
logical or conditional expressions. They are simple standalone statements that include a single
line of code and perform a basic action, such as calling functions, assigning values to variables,
and printing out values.
Example: print("Hello, Python!")
Output:
Hello, Python!

Python Multi-Line Statements


In Python, we use multi-line statements when a single logical line of code is too long.
Python allows us to break long code lines using backslashes (\) or by wrapping them in brackets
(), [], or {}.

1. Using Backslash (\) - Explicit line continuation

We use a backslash to split one logical statement into multiple lines manually.
Example: # Multi-line addition using backslash
total = 10 + 20 + \
30 + 40
print("Total:", total)
Output:
Total: 100

2. Using Parentheses - Implicit line continuation

We use the implicit line continuation to split a long statement using brackets [], parentheses (),
and braces {}.
Example: # Multi-line addition using parentheses
total = (10 + 20 +
30 + 40)
print("Total:", total)
Output:
Total: 100
Chapter 6

 Python Conditional Statements

1. Python If Statement
if is a conditional statement in Python used to decide whether a given code or block of code will
be executed or not. It is the simplest decision-making statement in Python and executes a code
only when a certain condition is true.
Syntax:
if condition:
# code to run if condition is true
Flowchart of an if Statement

Example: x = 10
if x > 5:
print("x is greater than 5")
Output:
x is greater than 5

2. Python if-else Statement


The if statement in Python executes a block of code only if the given condition is true. If the
condition is false, it doesn‘t execute the code.
If the given condition in the if statement is evaluated to be true, it will execute the statement and
skip the else condition. However, when the if statement is evaluated as false, it will execute the
else condition and skip the if statement.
Syntax:
if condition:
# code to run if condition is true
else:
# code to run if condition is false
Flowchart of If-else Statement

Example: age = 18
if age >= 18:
print("You can vote")
else:
print("You cannot vote")
Output:
You can vote

3. Python if-elif-else Statement


The if-elif-else statement lets us check multiple conditions one by one. When one condition is
true, its block runs, and the rest are skipped. This avoids writing multiple separate if statements.
We use the elif statement in Python when we need to test more than two possibilities in a
decision-making process.
Syntax:

if condition1:
# code if condition1 is true
elif condition2:
# code if condition2 is true
else:
# code if none of the above conditions are true

Flowchart of elif Statement in Python

Example: marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 70:
print("Grade B")
else:
print("Grade C")
Output:
Grade B

4. Python Nested If Statement


A nested if statement means using one if statement inside another. It helps us check multiple
conditions in steps, where a new condition is only checked if the first one is true.
We use the nested if statement in Python when one decision depends on another condition being
true.
Syntax:
if condition1:
if condition2:
# code runs if both condition1 and condition2 are true
Flowchart of Python Nested if Statement

Example: bug_count = 5
tests_passed = True
if bug_count == 0:
if tests_passed:
print("Ready for deployment")
else:
print("Fix test issues before deployment")
else:
if bug_count < 10:
print("Minor bugs – fix before release")
else:
print("Too many bugs – not ready for release")
Output:
Minor bugs – fix before release

Chapter 7

Python for loop


The for loop in Python is a special loop statement used for sequential traversal. We use this loop
to iterate over an iterable, such as a tuple, set, string, dictionary, or list. The for loop statement in
Python supports collection-based iteration, allowing us to access each item one by one.
Syntax:
for variable in iterable:
# code to run for each item
Flowchart of Python For Loop
Example:
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5

Iterating Over Different Data Types Using a for Loop in Python

In Python, we use the for loop to iterate over various types like lists, tuples, sets, strings, and
dictionaries.
1. Iterating over a List
Example: fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
2. Iterating over a Tuple
Example: numbers = (1, 2, 3)
for number in numbers:
print(number)
Output:
1
2
3
3. Iterating over a Set
Example: colors = {"red", "green", "blue"}
for color in colors:
print(color)
Output (order may vary):
red
green
blue
4. Iterating over a String
Example: word = "hello"
for letter in word:
print(letter)
Output: h
e
l
l
o
5. Iterating over a Dictionary
Example: person = {"name": "Alex", "age": 30, "city": "New York"}
for key, value in [Link]():
print(key, ":", value)
Output:
name : Alex
age : 30
city : New York

6. Python while loop


The while statement in Python executes a block of code or statement repeatedly until a certain
condition is met. If the condition is evaluated as false, the program will execute the line
immediately after the loop.
Syntax:
while condition:
# code to run
Flowchart of Python While Loop

Example: count = 1
while count <= 3:
print("Count is:", count)
count += 1
Output:
Count is: 1
Count is: 2
Count is: 3

7. Python try-except
We use the try-except statement in Python to manage errors within the code. The try block
checks the code for any errors and executes the program if there are no errors in the code given
inside the try block. However, if the program finds an error in the try block, it executes the code
inside the except block.
Syntax:
try:
# code that may raise an error
except:
# code to handle the error
Example: num = int("abc")
print("Conversion successful")

This code will raise an error. Let‘s fix it using try-except:


try:
num = int("abc")
print("Conversion successful")
except:
print("An error occurred")
Output:
An error occurred

8. Python with Statement


The with statement in Python is used when we work with files or other resources. It
automatically handles opening and closing, so we don‘t need to close them manually. This helps
us write cleaner and safer code.
Example:
with open("[Link]", "w") as file:
[Link]("Welcome to Python!")
Output:
(Contents written to [Link])
Note: This code writes "Hello, Python!" into a file named [Link]. No need to manually
close the file — with does it for us.
Python Expression Statements

In Python, expression statements are lines of code that evaluate and return a value. They can
assign values to variables, call functions, or perform calculations to produce results during
execution.

1. Python return Statement


The return statement in Python is used to stop the execution of a function call and return the
output to the caller. The program doesn‘t execute the statement after the return statement.
However, if the return statement doesn‘t have any expression, it returns None.
Basically, we use the return statement to invoke a function and execute the pass statements. We
can‘t use the return statement outside the function.
Syntax:
def function_name():
return value

Example:
def add(a, b):
return a + b
result = add(5, 3)
print(result)
Output:
8

2. Python pass Statement


Sometimes, users don‘t want to write code or don‘t know what code to write. In such cases, they
can use a pass statement in Python. They can place a pass in the line where empty code is not
allowed, such as function definitions, loops, class definitions, and if statements. Pass is a null
statement and helps users avoid any error when using an empty code.
Syntax:
pass

Example: def future_function():


pass # we'll add code later

for i in range(3):
pass # loop does nothing for now

The program does not show any output, and the code runs without error.
3. Python break Statement
The break statement in Python terminates the loop in which it is placed. After breaking, control
passes to the first statement following the loop. If used inside a nested loop, it only breaks the
innermost loop where the break occurs.
Syntax:
for/while item in iterable:
if condition:
break
Example:
for i in range(5):
if i == 3:
break
print(i)
Output:
0
1
2

4. Python continue Statement


Like the break statement, continue is also a loop control Python statement. However,
the continue statement is the opposite of the break statement. It doesn‘t terminate the loop but
forces the loop to execute the next iteration of that loop.
As we execute the continue statement in Python, it skips the code written inside the loop
following the continue statement and starts the next iteration of the loop.
Syntax: for/while item in iterable:
if condition:
continue
# remaining code
Example:
for i in range(5):
if i == 2:
continue
print(i)
Output:
0
1
3
4
5. Python del Statement
In Python, the del statement is used to delete objects. As everything is treated as an object in
Python, we use del to delete a dictionary, list, variable, etc.
Syntax:
del object_name
Example:
x = [10, 20, 30]
del x[1]
print(x)
Output:
[10, 30]

6. Python import Statement


The import statement is used to bring external Python modules into our code. It allows us to
access functions, variables, and classes from standard libraries or custom files.
Among the various Python statements, import helps us reuse code and keep our programs
organized and efficient.
Syntax:
import module_name
Example:
import math
print([Link](16))
Output:
4.0

Input and Output in Python


Input and output operations are fundamental in Python programming. With the print() function,
we can display output in various formats, while the input() function enables interaction with
users by gathering input during program execution.

Taking input in Python

Python's input() function is used to take user input. By default, it returns the user input in form of
a string.
Example: name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")
Output
Enter your name: Priya
Hello, Priya! Welcome!
The code prompts the user to input their name, stores it in the variable "name" and then prints a
greeting message addressing the user by their entered name.

Printing Output using print() in Python

Printing output in Python is straightforward using print() function. This function allows us to
display text, variables and expressions on the console.
In this example, "Hello, World!" is a string literal enclosed within double quotes. When
executed, this statement will output the text to the console.
print("Hello, World!")
Output
Hello, World!

Printing Variables

We can use the print() function to print single and multiple variables. We can print multiple
variables by separating them with commas. Example:
# Single variable
s = "Bob"
print(s)

# Multiple Variables
s = "Alice"
age = 25
city = "New York"
print(s, age, city)

Output
Bob

Alice 25 New York

Take Multiple Input in Python

We are taking multiple input from the user in a single line, splitting the values entered by the
user into separate variables for each value using the split() method. Then, it prints the values with
corresponding labels, either two or three, based on the number of inputs provided by the user.

# taking two inputs at a time


x, y = input("Enter two values: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)
# taking three inputs at a time
x, y, z = input("Enter three values: ").split()
print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)
Output
Enter two values: 5 10
Number of boys: 5
Number of girls: 10
Enter three values: 5 10 15
Total number of students: 5
Number of boys is : 10
Number of girls is : 15

Output Formatting
Output formatting in Python with various techniques including the format() method,
manipulation of the sep and end parameters, f-strings and the versatile % operator. These
methods enable precise control over how data is displayed, enhancing the readability and
effectiveness of your Python programs.

Example 1: Using Format()

amount = 150.75
print("Amount: ${:.2f}".format(amount))
Output
Amount: $150.75

Example 2: Using sep and end parameter

# end Parameter with '@'


print("Python", end='@')
print("Priya")

# Seprating with Comma


print('S', 'T', 'M', sep='')

# for formatting a date


print('09', '12', '2016', sep='-')

# another example
print('pratik', ‗AGM Ltd.‘, sep='@')
Output
Python@Priya
STM
09-12-2016
pratik@ AGM Ltd.

Example 3: Using f-string

name = 'Tushar'
age = 23
print(f"Hello, My name is {name} and I'm {age} years old.")

Example 4: Using % Operator

We can use '%' operator. % values are replaced with zero or more value of elements. The
formatting using % is similar to that of ‗printf‘ in the C programming language.

%d –integer
%f – float
%s – string
%x –hexadecimal
%o – octal

# Taking input from the user


num = int(input("Enter a value: "))
add = num + 5
# Output
print("The sum is %d" %add)
Output
Enter a value: 50The sum is 55

You might also like