Unit 1 - Python - Btech Second Year
Unit 1 - Python - Btech Second Year
This document contains valuable confidential and proprietary information of ABESEC. Such confidential and
proprietary information includes, amongst others, proprietary intellectual property which can be legally protected and
commercialized. Such information is furnished herein for training purposes only. Except with the express prior
written permission of ABESEC, this document and the information contained herein may not be published,
disclosed, or used for any other purpose.
2
Copyright © 2021, ABES Engineering College
Topics Covered
Day 5 Day 6
4
Copyright © 2021, ABES Engineering College
Session Plan - Day 1
5
Copyright © 2021, ABES Engineering College
Introduction
Python is a Popular
Programming language
?
https://www.wordclouds.com/
6
Copyright © 2021, ABES Engineering College
Some Areas where it is Popular
Application Development
Web Development
Artificial Intelligence
Data Science
7
Copyright © 2021, ABES Engineering College
Why choose Python : Lets Discuss More
8
Copyright © 2021, ABES Engineering College
Scope of Python
Python Language provides promising and rewarding career in the IT industry
Various Job roles advanced in Python with high paying jobs:
Research Analyst
DevOps Engineer
Python Developer
Data Analyst
Software Developer
Game Developer
Web Scrapper
9
Copyright © 2021, ABES Engineering College
Python History
Python was written in the late 1980s by Guido van Rossum at Centrum
Wiskunde & Informatica (CWI)
10
Copyright © 2021, ABES Engineering College
Python Features
11
Copyright © 2021, ABES Engineering College
Review Questions
12
Copyright © 2021, ABES Engineering College
Review Questions
13
Copyright © 2021, ABES Engineering College
Session Plan - Day 2
14
Copyright © 2021, ABES Engineering College
Advantages of Python
15
Copyright © 2021, ABES Engineering College
Contd..
}
}
16
Copyright © 2021, ABES Engineering College
Contd..
In Python
17
Copyright © 2021, ABES Engineering College
Disadvantages of Python
Python code is executed line by line since Python is interpreted as slower
in runtime than other programming languages like C++, Java, and PHP.
Python takes a lot of memory due to the flexibility of the data types, so it
is not a desirable choice for memory-intensive tasks.
Although Python serves as an excellent server-side programming
language, it is less commonly used to build intelligent phone-based
Applications.
Python is rarely used in Enterprise development because Python has
some limitations with Database Access compared to primarily other used
technologies like JDBC (Java Database Connectivity and ODBC (Open
Database Connectivity) as Python Language Database layers are
underdeveloped.
18
Copyright © 2021, ABES Engineering College
Your Future….!!!
20
Copyright © 2021, ABES Engineering College
Different Flavors of Python
Cpython
Jpython
Active Python
Anaconda Python
PyPy
Win Python
Python Portable
21
Copyright © 2021, ABES Engineering College
Different Python Frameworks
Full-Stack Frameworks
Non-Full Stack Frameworks
Asynchronous Frameworks
22
Copyright © 2021, ABES Engineering College
Review Questions
How to output the string “May the odds favor you” in Python?
print(“May the odds favor you”)
echo(“May the odds favor you”)
System.out(“May the odds favor you”)
printf(“May the odds favor you”)
23
Copyright © 2021, ABES Engineering College
Review Questions
24
Copyright © 2021, ABES Engineering College
Quality Content for Outcome based Learning
26
Copyright © 2021, ABES Engineering College
1.2 Python Installation Guide
27
Copyright © 2021, ABES Engineering College
Contd..
For the installation process, go to the official website of Python, i.e.,
www.python.org. Refer to the current stable version 3.9.4 as of date 13 April
2021.You will get the installer for Python 3.7 or Python 3.9. (at the time of
writing). You may even have it with a 32-bit or 64-bit processor versions.
28
Copyright © 2021, ABES Engineering College
1.2.1 Introduction to python IDE – IDLE
If you have recently installed Python on your computer, you might have seen a
new IDLE program.
"What is this software doing on my computer?" you might be curious. I did not
download that!"
Though you might not have downloaded IDLE on your own, it is included with
any Python installation. It is there to help you get acquainted with the language
right away.
29
Copyright © 2021, ABES Engineering College
Contd..
30
Copyright © 2021, ABES Engineering College
Contd..
Alternate way: You can also open a terminal window and run the interpreter
from the command line.
It is known as Command Prompt in Windows. It can be renamed terminal in
macOS or Linux.
You can type Windows key+ R and type cmd to open Command Prompt.
Then, type python to execute python programs.
31
Copyright © 2021, ABES Engineering College
Contd..
Start working with Python shell.
To print () to display the string "ABES Engineering College" on your computer.
Enter the command one at a time, and Python returns the results of each
command.
32
Copyright © 2021, ABES Engineering College
Contd..
From this menu bar, you can restart the shell. It will behave as if you had
launched a new instance of Python IDLE. The shell will forget anything from its
former state.
If you want to exit the interpreter, then type exit () and press Enter.
33
Copyright © 2021, ABES Engineering College
Python IDLE Editor
Python IDLE includes a full-featured file editor, allowing you to write and run
Python programs. The built-in file editor also supplies many tools to speed up
your coding workflows, such as code completion and automated indentation.
Select File “New File” from the menu bar to begin a new Python file
34
Copyright © 2021, ABES Engineering College
Contd..
When you are ready to work on a file, click the Edit button. You can save the file
as Demo-Python.py (.py is an extension to save python scripts files) in the
specified default location "C:\Users\Aatif\AppData\Local\Programs\Python."
35
Copyright © 2021, ABES Engineering College
Contd..
When you want to run a file, you must first ensure that it has been saved,
remember to check for asterisks * around the filename at the top of the file
editor window to see whether the file was correctly saved.
But do not panic if you forget! When you want to run an unsaved file in Python
IDLE, it will prompt you to save it.
Click the F5 key on your keyboard to run a file in IDLE. You can also use the
menu bar to choose Run Module
36
Copyright © 2021, ABES Engineering College
1.2.2 Setting Up Your Environment
The route(path that lists the directories in which the OS (Operating System)
looks for executables) is saved in an environment variable called a string.This
variable holds knowledge that the command shell and other programs can use.
37
Copyright © 2021, ABES Engineering College
Contd..
So, navigate to
Control Panel –> System
–> Advanced System
Settings–> Environment
Variables and choose
the PATH variable
38
Copyright © 2021, ABES Engineering College
Contd..
Add the Python path to the end of the string, this is where the package
management software, unit testing tools, and other command line-accessible
Python programs can live.
C:\Users\Aatif\AppData\Local\Programs\Python\Python37-32\Scripts\
39
Copyright © 2021, ABES Engineering College
1.2.3 Installation of Anaconda Navigator
Anaconda Navigator is a desktop graphical user interface that comes with
Anaconda, which allows you to open programs and control conda packages,
environments, and networks without needing to use a command-line interface.
40
Copyright © 2021, ABES Engineering College
Contd..
Click on install and Choose destination folder for installation.
41
Copyright © 2021, ABES Engineering College
1.2.4 Quick Tour of Jupyter Notebook
In an earlier topic, we have seen the installation of the Anaconda package.
Jupyter comes by default with this package
42
Copyright © 2021, ABES Engineering College
Contd..
Alternate way: If you type 'Jupyter notebook' into your command prompt, it will
open the Jupyter dashboard for you
43
Copyright © 2021, ABES Engineering College
Contd..
You might have found that the URL for the dashboard is
https://localhost:8888/tree while Jupyter Notebook is open in your window. The
term "localhost" does not refer to a website, but to the fact that the content is
served from your own devices.
44
Copyright © 2021, ABES Engineering College
Contd..
If you want to create your first file, then you must click on new and then python3.
When you return to the dashboard, you can see the new file Untitled18.ipynb
with green boundary in cell.
A cell is a container for the text that will be viewed in the notebook or code that
the notebook's kernel will execute.
45
Copyright © 2021, ABES Engineering College
Contd..
Every ipynb file stands for a single notebook, which means that each time you
create a new notebook, a new.ipynb file is generated .You should be aware of
kernel that are unfamiliar to you.
A kernel is a kind of "computational engine" that runs the code in a notebook
paper.
46
Copyright © 2021, ABES Engineering College
Contd..
Shift + Enter is the shortcut command to run your cell.
The green boundary over the cell shows the editable mode, and the Blue
boundary over the cell shows the command mode.
47
Copyright © 2021, ABES Engineering College
1.2.5 Python vs. IPython
IPython's interactive shell is known as Ipython.
IPython is a Python graphical command-line terminal founded by Fernando
Perez in 2001. IPython supplies an improved read-eval-print loop (REPL)
environment that is particularly well suited to scientific computing.
48
Copyright © 2021, ABES Engineering College
Contd..
IPython is interactive, and it gives some relaxation to the eyes of coders by
introducing some colors. Some useful commands are not present with the
existing Python idle.
The following are the valuable commands:
• %pwd
• %ls
• %History
49
Copyright © 2021, ABES Engineering College
Contd..
We can also check methods associated with data structures by pressing the tab
over the keyboard.
50
Copyright © 2021, ABES Engineering College
1.2.6 Online compilation support
Assume your machine lacks the necessary resources to install, but you need to
learn Python or run code to try something.
You will need a browser, which you already have. Using online IDEs saves yor
time in the configuration process.
51
Copyright © 2021, ABES Engineering College
Contd..
w3schools(https://www.w3schools.com/python/python_compiler.asp)
52
Copyright © 2021, ABES Engineering College
Contd..
Onlinegdb (https://www.onlinegdb.com/online_python_compiler)
53
Copyright © 2021, ABES Engineering College
Contd..
54
Copyright © 2021, ABES Engineering College
Review Questions
55
Copyright © 2021, ABES Engineering College
Review Questions
56
Copyright © 2021, ABES Engineering College
Session Plan - Day 4
57
Copyright © 2021, ABES Engineering College
Python keywords
Python keywords are special reserved words that have specific meanings
and purposes.
function name
variable name
identifiers
58
Copyright © 2021, ABES Engineering College
Contd..
59
Copyright © 2021, ABES Engineering College
Python Statement and Comments
Python Statement –
In Python Programming, any executable instruction, that tell the computer to perform a specification
action is refer to as statements.
input-output statements,
arithmetic statements,
control statements,
60
Copyright © 2021, ABES Engineering College
Python Literals
Literals are the type of data that is used to store in a variable or constant.
61
Copyright © 2021, ABES Engineering College
String literals
When set of character are enclosed in quotes ( single quotes or double quotes)
then it formed a string literals.
'abes' 'rate_of_interest' '123', '12.5'
Example -
"ABESEC" "Simple_interest" "A1" "456 "
Example -
'ABES Engineering College \ "ABES Engineering College \
NH-24 Delhi Hapur Bypass \ NH-24 Delhi Hapur Bypass \
Near Crossing Republic' Near Crossing Republic"
62
Copyright © 2021, ABES Engineering College
Numeric Literals
Numeric literals are of multiple types based on the number type. The types
of numeric literals are integer, float (decimal numbers), and complex
numbers.
Float Literals - These are basically real numbers that consist of both integer
as well as fractional parts.
63
Copyright © 2021, ABES Engineering College
Numeric Literals
Example -
10j , 1 + 0j , 10 + 2J, 12 – 5j
64
Copyright © 2021, ABES Engineering College
Boolean Literals , Special literals
Boolean Literals - True or False are the values to be used as the Boolean
values.
In Python, True represents the Non-zero value and False represents the
value as Zero.
65
Copyright © 2021, ABES Engineering College
Literal Collections
List Literals – List is a set of values of different types. The values are
separated by comma (,) and enclosed within square brackets( [ ]).
Tuple literals – A tuple is a set of values of different types. The values are
separated by comma(,) and enclosed within parentheses “ ( ) “. It is
immutable.
Example -
( 1, 23, 23.4, 100 )
Set literals – Set is a collection of values of different types. The values are
separated by comma (,) and enclosed within curly-braces “{ }”. It is
unordered and contains only unique value.
Example – a = 23
Here ‘a’, ‘name’ and ‘Marks’ are variable which
name = 'Ram'
refer an integer value 23, a string ‘Ram’ and float
Value 23.5.
Marks = 23.5
68
Copyright © 2021, ABES Engineering College
Variables
Rules for variable name –
Variables can be named with an alpha-numeric combination, started with
an alphabet or underscore.
Variable name can’t start with digit.
Multi- word space separated name can’t be used as a variable name.
The reserved words(keywords) cannot be used naming the variable.
69
Copyright © 2021, ABES Engineering College
Can you answer these questions?
1) age
2) _age
3) -age
4) age_*
5) Item-Number-1
70
Copyright © 2021, ABES Engineering College
type() command
type () command helps in finding the type of the specific declared variable
or a value.
Example –
71
Copyright © 2021, ABES Engineering College
id() command
id () command gives the unique id for a given objects / variable / values.
Note - The unique id is the memory address and will be different each time
when you run for variable or values.
Example –
Unique Identity
72
Copyright © 2021, ABES Engineering College
dir() command
dir () command is a vital function that returns all the properties and
methods associated with given objects.
Example –
73
Copyright © 2021, ABES Engineering College
Session Plan - Day 5
74
Copyright © 2021, ABES Engineering College
Type conversion
The process of converting the value of one data type (e.g. integer, string,
float, etc.) to another data type is called type conversion.
Example -
12.5 12 ( float to integer )
'123' 123 ( string to integer )
12 12.0 ( integer to float )
75
Copyright © 2021, ABES Engineering College
Type conversion : Implicit Type Conversion
Example –
Note - Python promotes the conversion of the lower data type (integer) to
the higher data type (float) to avoid data loss.
76
Copyright © 2021, ABES Engineering College
Type conversion : Explicit Type Conversion
Explicit Type Conversion – In this, user converts the data type of variable
of value to needed data type.
Example –
77
Copyright © 2021, ABES Engineering College
Can you answer these questions?
a) 12 (20+0j) 123.45
b) 12 20 123.45
c) Error
78
Copyright © 2021, ABES Engineering College
Basic I/O Operations
79
Copyright © 2021, ABES Engineering College
Basic I/O Operations : input()
Syntax –
input(prompt='')
Prompt - A String, representing a default message
before the input.
Example –
80
Copyright © 2021, ABES Engineering College
Basic I/O Operations : input()
Syntax –
input(prompt='')
Prompt - A String, representing a default message
before the input.
Example –
81
Copyright © 2021, ABES Engineering College
Basic I/O Operations : input()
When we take input using input() function, it return value in string data type.
Example –
82
Copyright © 2021, ABES Engineering College
Basic I/O Operations : print()
print () is a built-in standard function used to print the output to the console.
sep - (optional), Specify how to separate the values, if there is more than
one. Default is ' '.
83
Copyright © 2021, ABES Engineering College
Basic I/O Operations : print()
Example –
84
Copyright © 2021, ABES Engineering College
Basic I/O Operations : print()
Example – Write a Python program that takes two integer as input from
user and print sum of both.
85
Copyright © 2021, ABES Engineering College
Session Plan - Day 6
86
Copyright © 2021, ABES Engineering College
Operators
Operators are symbol, used to perform mathematical and logical
operation.
87
Copyright © 2021, ABES Engineering College
Arithmetic operators
There are seven arithmetic operators, and these are of:
Operator Meaning Example
Add two operands or x+y
+ unary plus +2
Subtract right operand from the left or x-y
- unary minus -2
* Multiply two operands x*y
Divide left operand by the right one (always results into
/ float)
x/y
Modulus - remainder of the division of left operand by the
% right
x % y (remainder of x/y)
Floor division - division that results into whole number
// adjusted to the left in the number line
x // y
** Exponent - left operand raised to the power of right x**y (x to the power y)
88
Copyright © 2021, ABES Engineering College
Arithmetic operators
Example of all mentioned arithmetic operators
89
Copyright © 2021, ABES Engineering College
Comparison (Relational) Operators
90
Copyright © 2021, ABES Engineering College
Comparison (Relational) Operators
91
Copyright © 2021, ABES Engineering College
Comparison (Relational) Operators
Example –
Note - The == and != operators can actually work with values of any data
type. 92
Copyright © 2021, ABES Engineering College
Bitwise Operators
Bitwise operators act on the bits and performs bit by bit operation on
the operands.
Operator Meaning
Example – Evaluate 2 & 7 & Bitwise AND
| Bitwise OR
How it works - ~ Bitwise NOT
Step 1 – Convert 2 in binary 0010 ^ Bitwise XOR
Step 2 – Convert 7 in binary 0111 >> Bitwise right shift
Step 3 – Perform Bitwise & operation
Step 4 – Convert the result back to << Bitwise left shift
decimal
93
Copyright © 2021, ABES Engineering College
Bitwise Operators – Cont..
Truth Table
Bitwise NOT
A B A&B A|B A^B A ~A
0 1
0 0 0 0 0
1 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
94
Copyright © 2021, ABES Engineering College
Bitwise Operators – Bitwise AND (&)
Example –
Explanation –
95
Copyright © 2021, ABES Engineering College
Bitwise Operators – Bitwise OR( | )
Example –
Explanation –
96
Copyright © 2021, ABES Engineering College
Bitwise Operators – Bitwise XOR ( ^ )
Example –
Explanation –
97
Copyright © 2021, ABES Engineering College
Bitwise Operators – Bitwise Left shift ( << )
Example –
Explanation –
98
Copyright © 2021, ABES Engineering College
Bitwise Operators – Bitwise Right Shift ( >> )
Example –
Explanation –
100
Copyright © 2021, ABES Engineering College
Logical Operators
Logical operators perform Logical AND, Logical OR and Logical NOT operations.
101
Copyright © 2021, ABES Engineering College
Logical Operators
Example –
102
Copyright © 2021, ABES Engineering College
Identity Operators
Identity Operators – is and is not are the identity operators in Python.
They are used to check if two values (or variables) are located on the same part
of the memory or not.
Operator Meaning
is Gives True if the operands are identical (refer to the same ID or Memory)
is not Gives True if the operands are not identical (do not refer to the ID or Memory)
Example
103
Copyright © 2021, ABES Engineering College
Membership Operators
in and not in are the membership operators in Python.
They are used to test whether a value or variable is found in a sequence (string,
list, tuple, set and dictionary) or not.
Operator Meaning
in Gives True if value/variable is found in the sequence otherwise False
not in Gives True if value/variable is not found in the sequence otherwise True
Example
104
Copyright © 2021, ABES Engineering College
Precedence and associativity
Operator precedence and associativity decide the priorities of the operator.
105
Copyright © 2021, ABES Engineering College
Cont..
Precedence and Associativity Table –
106
Copyright © 2021, ABES Engineering College
Python 2 vs Python 3
107
Copyright © 2021, ABES Engineering College
Python 2 vs Python 3
108
Copyright © 2021, ABES Engineering College
Python 2 vs Python 3
In for loop, the iterations are used using a xrange function in python 2, which
is replaced by range function in python3.
Some of the libraries which are available in python 2 are not moved in python
3.
Similarly, now the developers are making new libraries for python 3 which are
incompatible to python 2.
109
Copyright © 2021, ABES Engineering College
Python Programming cycle
The programming cycle in Python, like in most programming languages, involves several key
steps that developers follow to create, test, and maintain Python programs. Here are the
main phases of the Python programming cycle:
1. **Problem Definition*
At the beginning of the programming cycle, you need to clearly define the problem you
want to solve with your Python program. This involves understanding the requirements,
gathering information, and defining the goals and objectives of the program.
2. **Algorithm Design
Once you have a clear understanding of the problem, you can design an algorithm to solve
it. An algorithm is a step-by-step plan that outlines the logic and operations your program will
perform. You may use flowcharts, pseudocode, or other tools to represent your algorithm
3. **Coding
Coding is the process of translating your algorithm into Python code. You write the actual
program by creating functions, classes, and variables, and implementing the logic to perform
the desired operations. This is where you write the Python statements and expressions that
make up your program.
110
Copyright © 2021, ABES Engineering College
4. **Testing:After coding, you need to thoroughly test your Python program to
ensure that it works as intended and handles different scenarios and inputs
correctly. Testing involves both unit testing (testing individual functions or
components) and integration testing (testing how different parts of the
program work together)
5. **Debugging: During testing, you may encounter errors or bugs in your
code. Debugging is the process of identifying and fixing these issues. Python
provides various debugging tools and techniques, such as print statements,
debugging libraries like `pdb`, and integrated development environments
(IDEs) with debugging features.
.
111
Copyright © 2021, ABES Engineering College
6. **Optimization:After you have a working program, you can optimize it to improve performance
and efficiency. This may involve refactoring code, using data structures and algorithms more
effectively, and reducing resource consumption.
7. **Documentation: Proper documentation is crucial for maintaining and sharing your Python
code. Document your code by adding comments, docstrings, and README files to explain its
purpose, usage, and any important considerations for other developers.
8. **Version Control:Using a version control system like Git is essential for tracking changes to
your code, collaborating with others, and maintaining a history of your project. You can use
platforms like GitHub or GitLab to host your Python project repositories.
9. **Deployment: If your Python program is meant for production use, you'll need to deploy it to
a server, cloud platform, or other computing environment. This step involves configuring the
necessary infrastructure and ensuring that the program runs smoothly in a production
environment.
10. **Maintenance:Software maintenance is an ongoing process that involves fixing bugs,
adding new features, and adapting the program to changing requirements. Regularly update
and improve your Python code as needed
112
Copyright © 2021, ABES Engineering College
Memory Management in Python:
113
Copyright © 2021, ABES Engineering College
Memory Pools: Python uses a system of memory pools for small objects to
reduce memory fragmentation and improve memory allocation efficiency.
Dynamic Typing: Python's dynamic typing means that objects can change
their type during runtime, which can have implications for memory
management since objects might need to be reallocated if their type
changes.
Memory Optimizations: Python includes various memory optimization
techniques, such as interning small integers and string literals, to reduce
memory overhead.
114
Copyright © 2021, ABES Engineering College
PEP 8:
PEP 8 is the Python Enhancement Proposal 8, titled "Style Guide for Python
Code." It is a document that provides guidelines and recommendations for
writing Python code that is readable and consistent. PEP 8 covers topics
such as naming conventions, code layout, indentation, whitespace, and
more. Following PEP 8 helps make your Python code more understandable
and maintainable, especially when working on projects with multiple
contributors.
115
Copyright © 2021, ABES Engineering College
Some key points from PEP 8 include:
116
Copyright © 2021, ABES Engineering College
Python is called as dynamic and strongly typed
language?
Python is called a dynamic and strongly typed language due to the way it
handles data types and variable binding during runtime. Let's break down
these two characteristics:
1. **Dynamic Typing**: In Python, variable types are not explicitly declared when you define
a variable. Instead, the data type of a variable is determined dynamically at runtime based on
the value it holds. This means that you can assign different types of values to the same
variable during the execution of your program. For example:
```python
x = 5 # x is an integer
x = "Hello" # x is now a string
Python's dynamic typing offers flexibility and simplifies the coding process because you don't
need to declare the data type of a variable explicitly. The interpreter determines the
appropriate data type based on the value assigned to the variable.
117
Copyright © 2021, ABES Engineering College
2. **Strong Typing: Python is also considered a strongly typed language
because it enforces strict rules regarding type compatibility and type
conversion. In strongly typed languages, operations between incompatible
data types are either prohibited or require explicit type conversion.
For example, in Python, you cannot directly concatenate a string and an integer
without converting the integer to a string:
```python
x = "Hello"
y=5
result = x + y # This will raise a TypeError
118
Copyright © 2021, ABES Engineering College
To perform this operation, you need to explicitly convert the integer to a string:
```python
x = "Hello"
y=5
result = x + str(y) # Now it works
Python's strong typing helps prevent unintended type-related errors and promotes code
safety.
In summary, Python's dynamic typing allows for flexibility in variable assignments by
determining types at runtime, while its strong typing ensures that type-related operations are
well-defined and explicit, reducing the likelihood of subtle bugs and errors. These
characteristics contribute to Python's reputation as a language that is both flexible and safe.
119
Copyright © 2021, ABES Engineering College
Mutable and immutable data type
In Python, data types are categorized into two main groups: mutable and
immutable. These categories describe how the data stored in variables of
these types can be modified. Here's a breakdown of the differences between
mutable and immutable data types:
**Immutable Data Types**:
1. **Immutable** means that once an object of an immutable data type is
created, it cannot be changed or modified. Any operation that appears to
modify the data actually creates a new object with the modified value.
2. Immutable objects are hashable, meaning they can be used as keys in
dictionaries and elements in sets because their value will not change.
Examples of immutable data types in Python include `int`, `float`, `str`,
`tuple`, and `frozenset`.
120
Copyright © 2021, ABES Engineering College
Examples of Immutable Data Types:
```python
# Immutable data types
x = 42 # int
y = 3.14 # float
s = "Hello" # str
t = (1, 2, 3) # tuple
121
Copyright © 2021, ABES Engineering College
Mutable Data Types**:
1. **Mutable** means that objects of these data types can be changed after
they are created. You can modify their contents, add or remove elements,
etc., without creating a new object.
2. Mutable objects are not hashable, so they cannot be used as dictionary
keys or elements in sets.
Examples of mutable data types in Python include `list`, `dict`, and `set`.
Examples of Mutable Data Types:
# Mutable data types
lst = [1, 2, 3] # list
dct = {"a": 1, "b": 2} # dict
st = {1, 2, 3} # set
122
Copyright © 2021, ABES Engineering College
Why Immutability Is Important**:
123
Copyright © 2021, ABES Engineering College
Multiple comments
Multiline Comments: Python does not have a specific multiline comment syntax like
some other programming languages. However, you can achieve multiline comments
using triple-quoted strings (either single or double-quoted). These strings are often
used as docstrings for documenting functions, classes, or modules.
While they are not technically comments, they can serve a similar
purpose for adding multiline explanations or comments within your code. Here's an example:
python
•""" This is a multiline comment or docstring. You can write multiple lines of
text here. It is often used for documentation. """
It's important to note that these multiline strings are not ignored by the Python
interpreter, but they are typically used for documentation and are not treated as comments for execution purposes.
124
Copyright © 2021, ABES Engineering College
•Variable Declaration and Data Types: In Python, you do not need to declare
variables with explicit data types as you do in some statically typed languages
like C or Java. Python uses dynamic typing, which means that variable types
are determined automatically based on the values assigned to them. You can
simply
•assign a value to a variable, and Python will infer its data type. For example:
python
my_variable = 42 # An integer
my_string = "Hello" # A string
my_list = [1, 2, 3] # A list
Python will assign appropriate data types to these variables based on the
values you provide.
125
Copyright © 2021, ABES Engineering College
While you don't need to declare data types explicitly, Python is still strongly
typed,
meaning that variable types matter in operations.
For example, you cannot add a string and an integer directly without explicit
type conversion:
python
result = my_string + str(my_variable) # Convert integer to string before
concatenation
Python will raise a TypeError if you try to perform incompatible operations on variables with
different types
126
Copyright © 2021, ABES Engineering College
solve the mathmaticalll expression 7/3*1.2+3/2
Ans:
127
Copyright © 2021, ABES Engineering College
Prime no is not?
num = 11
# If given number is greater than 1
if num > 1:
# Iterate from 2 to n / 2
for i in range(2, int(num/2)+1):
# If num is divisible by any number between
# 2 and n / 2, it is not prime
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
128
Copyright © 2021, ABES Engineering College
A leap year is exactly divisible by 4 except for century years (years ending with 00).
The century year is a leap year only if it is perfectly divisible by 400.
For example,
2017 is not a leap year 1900 is a not leap year 2012 is a leap year 2000 is a leap year
Source Code
\
129
Copyright © 2021, ABES Engineering College
Find sum of digits , reversal of digits of given no
130
Copyright © 2021, ABES Engineering College
131
Copyright © 2021, ABES Engineering College
semicolons
132
Copyright © 2021, ABES Engineering College
Conditional Expressions: Semicolons can be used within conditional
expressions. For example:
x = 5 if a > b else 10; y = 20 if a < b else 15
While this is possible, it's often more readable to use the regular if-
else statements.
Despite these limited use cases, it's important to note that the
Python community generally follows a coding style that favors
readability and clarity. The use of semicolons to write multiple
statements on a single line is discouraged in most cases.
133
Copyright © 2021, ABES Engineering College
Summary
Python is an open-source, high level, interpreter- based language that can be used for scientific
and non-scientific computing purposes.
Comments are non-executable statements in a program.
An identifier is a user defined name given to a variable or a constant in a program.
Datatype conversion can happen either explicitly or implicitly.
Operators are constructs that manipulate the value of operands.
Python has input() function for taking user input.
Python has print() function to output data to a standard output device.
There are several data types in Python — integer, boolean, float, complex, string, list, tuple, sets,
None and dictionary.
134
Copyright © 2021, ABES Engineering College
References
1. https://docs.python.org/3/tutorial/controlflow.html
4. Python Basics: A Practical Introduction to Python, by David Amos, Dan Bader, Joanna Jablonski,
Fletcher Heisler
5. https://www.fullstackpython.com/turbogears.html
6. https://www.cubicweb.org
7. https://pypi.org/project/Pylons/
8. https://www.upgrad.com/blog/python-applications-in-real-world/
9. https://www.codementor.io/@edwardbailey/coding-vs-programming-what-s-the-difference-yr0aeug9o
135
Copyright © 2021, ABES Engineering College
Thank You
136
Copyright © 2021, ABES Engineering College