PYTHON
PROGRAMMING
What is Python…?
Python is a popular high-level programming language.
It was created by Guido Van Rossum.
It is used for
Web Development
Software Development
System Scripting
Mathematics
What is Python…?
Python is a popular high-level programming language.
It was created by Guido Van Rossum
Python is an easy language to learn because of its simple syntax
Python supports modules and packages, which encourages program modularity
and code reuse.
Python is a general purpose programming language that is often applied in
scripting roles.
So, Python is programming language as well as scripting language.
Python is also called as Interpreted language
What can Python do?
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software
development.
Why Python…?
Python works on different platforms(Windows, Mac, Linux etc).
It has simple syntax similar to English language.
Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
Python runs on interpreter system, meaning that code can be executed as
soon as it written. This means that prototyping can be very quick.
It can be treated in a procedural way an object-oriented way..
Why Python…?
It makes development & debugging fast because no compilation step is
included in python development and the edit-test-debug cycle is very
fast.
Python is a open source, cost free programming language.
It is having large collection of libraries that can be used to make its
function easier.
These libraries cover many domains
Web Development
Scientific Computing
Data Analysis
Python is a case-sensitive language, which means that upper & lower case letters are
treated differently
Where is Python used…?
Data Science
Desktop applications
Mobile Applications
Software Development
AI
Machine Learning
Web Applications
Gaming
IoT
Finance
Networking
Testing
Speech Recognition
Computer Vision or Image
Processing Applications
3D CAD Applications
Python popular Libraries
Web Development ( Server Side) – Django flask, pyramis, cherrypy
GUI Based Applications – TK, PyGTK, PyJs
Machine Learning – TensorFlow, PyTorch, matplotliby, scipy
Mathematics – Numpy, Pandas
Game Development – Pygame
Testing – Pytest
Web Scraping & Parsing – Beautiful Soup
History
Invented in the Netherlands, early 90s by Guido van Rossum
Python was conceived in the late 1980s and its
implementation was started in December 1989
Guido V
an Rossum is fan of ‘Monty Python’s Flying
Circus’, this is a famous TV show in Netherlands
Named after Monty Python
Open sourced from the beginning
Guido van Rossum
“Python is an experiment in how much
freedom program-mers need. Too
much freedom and nobody can read
another's code; too little and
expressive-ness is endangered.”
Whywas python
created?
"My original motivation for creating Python was the
perceived need for a higher level language in the
Amoeba [Operating Systems]project.
I realized that the development of system
Moreover, doing these things in the Bourne
administration utilities in C was taking too long.
shell
wouldn't work for a variety of reasons. ...
So, there was a need for a language that
would bridge the gap between C and the shell”
- Guido VanRossum
Differences between program and
scripting language
• Program
• a program is executed (i.e. the
source is first compiled, and the result
of that compilation is expected)
• A "program" in general, is a
sequence of instructions written so
that a computer can perform certain
task.
• Scripting
• a script is interpreted
• A "script" is code written in a
scripting language. A scripting
language is nothing but a type of
programming language in which we
can write code to control another
software application.
PROGRAMMING LANGUAGE SCRIPTING LANGUAGE
These are Program - Independent A user needs to run scripting languages inside an
existing program. Thus it is Program- Dependent
It create .exe files It doesn’t create file type
These are self Executable . They don not require
any hosts for execution
It requires hosts for execution
Compiled programs runs faster when compared to
interpreted languages
It runs slower when compared to programming
language
C, ++, Java, VB, Cobol, Python & Javascript (front
end & Backend)
VB Script, Perl, Python, Ruby, PHP, Javascript etc
All the programming languages are not Scripting
languages
All Scripting languages are programming languages
Differences between program and
scripting language
Applications of Scripting Languages :
1. To automate certain tasks in a program
2. Extracting information from a data set
3. Less code intensive as compared to traditional programming
languages
Applications of Programming Languages :
1. More compatible while integrating code with mathematical models
2. Languages like JAVA can be compiled and then used on any
platform
Advantages of Python
1. Easy to Read, Learn and Write
Python is a high-level programming language that has English-like syntax. This
makes it easier to read and understand the code.
Python is really easy to pick up and learn, that is why a lot of people recommend
Python to beginners. You need less lines of code to perform the same task as
compared to other major languages like C/C++ and Java.
2. Improved Productivity
Python is a very productive language. Due to the simplicity of Python, developers
can focus on solving the problem. They don’t need to spend too much time in
understanding the syntax or behaviour of the programming language. You write less
code and get more things done.
3. Interpreted Language
• Python is an interpreted language which means that Python directly executes the
code line by line. In case of any error, it stops further execution and reports back the
error which has occurred.
• Python shows only one error even if the program has multiple errors. This
makes debugging easier.
4. Dynamically Typed
• Python doesn’t know the type of variable until we run the code. It automatically
assigns the data type during execution. The programmer doesn’t need to worry
about declaring variables and their data types.
Advantages of Python
5. Free and Open-Source
• Python comes under the OSI approved open-source license. This makes
it free to use and distribute. You can download the source code, modify it and even
distribute your version of Python. This is useful for organizations that want to modify
some specific behaviour and use their version for development.
6. Vast Libraries Support
• The standard library of Python is huge, you can find almost all the functions needed
for your task. So, you don’t have to depend on external libraries.
• But even if you do, a Python package manager (pip) makes things easier to import
other great packages from the Python package index (PyPi). It consists of over
200,000 packages.
Disadvantages of Python
1. Slow Speed
The line by line execution of code often leads to slow execution. The dynamic nature of
Python is also responsible for the slow speed of Python because it has to do the extra
work while executing code. So, Python is not used for purposes where speed is an
important aspect of the project.
2. Not Memory Efficient
To provide simplicity to the developer, Python has to do a little trade-off. The Python
programming language uses a large amount of memory. This can be a disadvantage
while building applications when we prefer memory optimization.
3. Weak in Mobile Computing
Python is generally used in server-side programming. We don’t get to see Python on
the client-side or mobile applications because of the following reasons. Python is not
memory efficient and it has slow processing power as compared to other languages.
4. Database Access
• Programming in Python is easy and stress-free. But when we are interacting with the
database, it lacks behind.
• The Python’s database access layer is primitive and underdeveloped in comparison to the
popular technologies like JDBC and ODBC.
• Huge enterprises need smooth interaction of complex legacy data and Python is thus
rarely used in enterprises.
5. Runtime Errors
• As we know Python is a dynamically typed language so the data type of a variable can
change anytime. A variable containing integer number may hold a string in the future,
which can lead to Runtime Errors.
• Therefore Python programmers need to perform thorough testing of the applications.
Disadvantages of Python
Why do people use Python…?
The following primary factors cited by Python users
seem to be these:
Python is object-oriented
Structure supports such concepts as polymorphism, operation
overloading, and multiple inheritance.
Indentation
Indentation is one of the greatest future in Python.
It's free (open source)
Downloading and installing Python is free and easy
Source code is easily accessible
It's powerful
- Dynamic typing
- Built-in types and tools
- Library utilities
- Third party utilities (e.g. Numeric, NumPy, SciPy)
-It's portable
- Python runs virtually every major platform used today
-As long as you have a compatible Python interpreter installed,
Python programs will run in exactly the same manner,
irrespective of platform.
• It's mixable
- Python can be linked to components written in other languages easily
- Linking to fast, compiled code is useful to computationally intensive
problems
- Python/C integration is quite common
• It's easy to use
- No intermediate compile and link steps as in C/ C++
- Python programs are compiled automatically to an
intermediate form called bytecode, which the interpreter then reads
- This gives Python the development speed of an interpreter without
- the performance loss inherent in purely interpreted languages
• It's easy to learn
- Structure and syntax are pretty intuitive and easy to grasp
• The Server and
Client
applications are
coded using
Python
• Machine Learning is used to
cluster users based on their
interest on shows and retain
them for longer
• Better search result
are provided based
on ranking of the
websites and much
more
• Transfer of files between peer-
to-peer which started out as a
normal python file
Bit-
Torrent
Google
Dropbox
NETFLIX
Where is python used in the Industry
• Scientific calculations
are computed using
python
• Machine Learning and
Artificial Intelligence
• Cyber-Security analysis
and other encryption and
decryption work is done
using python
• Data visualizations
from
the Matplotlib and
Seaborn galleries
National
Security
Agency
NASA
Where is python used in the Industry
Difference between Interactive and Script
mode in Python
Interactive mode: Instructions are given in front of Python prompt
(eg., >>> ) in Python Shell. Python carries out the given instruction and shows the
result there itself.
Script mode: Python instructions are stored in a file generally with .py extension and
are executed together in one go as a unit. The saved instructions are known as Python
script or Python program.
Coding style in Python
Coding style in Python is an important aspect of writing clean, readable, and
maintainable code.
The Python community has established guidelines and best practices, primarily
documented in PEP 8, the Python Enhancement Proposal that provides
conventions for writing code in Python.
Coding style in Python
1. Indentation
2. Line Length
3. Blank Lines
4. Imports
5. Naming Conventions
6. Docstrings
7. Comments
8. Whitespace in Expressions and Statements
9. Error Handling
Coding style in Python
1. Indentation
 Use 4 spaces per indentation level.
 Avoid using tabs.
 Consistent indentation is crucial in Python, as it defines the structure of the code.
1. def my_function(x):
2. if x > 0:
3. print("Positive")
4. else:
5. print("Non-positive")
Python Indentation
Indentation refers to the space at the beginning of a code line
Where in another programming language the indentation in code is for the
readability only, the indentation in python is very important.
Python use indentation to indicate a block of code.
The number of spaces is up to you as a programmer, the most common use if
four, but it has to be at least one.
You have to use the same number of spaces in the same block of code.
If 5>2:
print(“ Five greater than two”)
Coding style in Python
2. Line Length
 Limit all lines to a maximum of 79 characters.
 For long blocks of text (e.g., docstrings or comments), lines should be limited to 72 characters.
 Use parentheses to wrap long lines instead of using a backslash () for line continuation.
# Example of wrapping lines
result = some_function_that_does_something(
argument1, argument2, argument3,
argument4, argument5
)
Coding style in Python
3. Blank Lines
 Use blank lines to separate top-level functions and class definitions.
 Inside functions, use blank lines to separate logical sections of the code.
# Example class MyClass:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
def reset(self):
self.value = 0
Coding style in Python
4. Imports
 Imports should be on separate lines and typically at the top of the file.
 Follow the order: standard library imports, related third-party imports, and then local
application/library-specific imports.
Example
# Correct way to do imports
import os
import sys
from datetime import datetime
from collections import defaultdict
import my_local_module
Coding style in Python
5. Naming Conventions
Variables, Functions, and Attributes: Use lowercase words separated by underscores.
 Example
def calculate_area(radius):
pi_value = 3.14159
return pi_value * (radius ** 2)
Python Identifiers
 A python identifier is a name used to identify a variable, function, class, module,
or the object.
The identifier starts with a letter A to Z, or a to z, or an underscore(_) followed by
a zero or more letters, underscore and digits(0 to 9).
Python does not allow punctuation characters within an identifier
Python is a case sensitive language. Ex: num1 & Num1 are two different
identifiers.
Keywords in Python
Coding style in Python
6. Docstrings
 Use docstrings to document all public modules, classes, functions, and methods.
 Follow the convention for multiline docstrings:
 The first line is a short summary.
 The second line is blank
Example
def calculate_area(radius):
"""
Calculate the area of a circle given its radius.
:param radius: The radius of the circle.
:return: The area of the circle.
"""
return 3.14159 * (radius ** 2)
Coding style in Python
7. Comments
 Use comments to explain why something is done, not what is done.
 If the code isn't self-explanatory, it may need to be refactored.
 Comments should be complete sentences, with the first word capitalized and ending with a
period.
Example
# Initialize the count to zero
count = 0
Comments in Python
Comments in Python
 Comments starts with a #
To add multi line comment
# this is a comment
# this is a comment
# written in
# more than just a line
“ “ “
this is a comment
written in
more than just a line
“ “ “
Coding style in Python
8. Whitespace in Expressions and Statements
 Avoid extraneous whitespace.
 Immediately inside parentheses, brackets, or braces: list[1], not list[ 1 ].
 Before a comma, semicolon, or colon: if x == 1:, not if x == 1 :.
 Around the assignment operator when assigning a default value: def func(param=None):,
not def func(param = None):.
Example
# Good
a = (1, 2, 3)
# Avoid
b = ( 1, 2, 3 )
Coding style in Python
9. Error Handling
 Use exceptions to handle errors. Use try/except blocks to manage exceptions gracefully, and
always catch specific exceptions.
Example
try:
result = some_function()
except ValueError as e:
print(f"ValueError encountered: {e}")
print() function
print() function
The print() function in Python is used to output data to the console or terminal.
It can print strings, numbers, and other data types, and it supports various
formatting options.
Multiple Arguments print() function
You can pass multiple arguments to print(), and they will be separated by spaces by
default
End and Separator Parameters print() function
sep: Defines the separator between multiple arguments (default is a space).
end: Defines what is printed at the end of the line (default is a newline).
input() function
input() function
The input() function in Python is used to read user input from the console.
It allows you to prompt the user to enter data, which is then returned as a string.
Basic Input
• This will display the prompt Enter your name:, and whatever the user types in
will be stored in the user_input variable
Using the Prompt
Here, How old are you? is the prompt displayed to the user.
Converting Input
• By default, input() returns a string. To use the input as another data type, such
as an integer or float, you need to convert it:
Handling Invalid Input
You can use try-except blocks to handle cases where the user input cannot be
converted to the expected type:
Input Without Prompt
• If you don't provide a prompt, input() will simply wait for the user to enter
something:
formatted string literal(f-string)
formatted string literal(f-string)
An f-string, short for formatted string literal, is a feature introduced in Python
3.6
It provides a convenient and readable way to embed expressions inside string
literals.
F-strings are prefixed with an f or F and allow expressions to be included within
curly braces {}.
These expressions are evaluated at runtime and formatted using the specified
format.
format specifiers
In Python, format specifiers are used to control the formatting of strings when
using various string formatting methods. These include the % operator,
Common Format Specifiers:
%d: Integer
%f: Floating-point number
%.2f: Floating-point number with 2 decimal places
%s: String
%x: Hexadecimal integer (lowercase)
%X: Hexadecimal integer (uppercase)
format specifiers
name = "Alice"
age = 30
height = 5.7
print("Name: %s, Age: %d, Height: %.1f" % (name, age, height))
Output:
Name: Alice, Age: 30, Height: 5.7
formatted string literal(f-string)
Syntax
f"string text {expression} string text"
Variable Embedding – f-string
Example:
user = "Bob"
print(f"Hello, {user}!")
Output:
Hello, Bob!
Arithmetic Expressions – f-string
Example:
a = 5
b = 3
print(f"{a} + {b} = {a + b}")
Output:
5 + 3 = 8
Function Calls– f-string
Example:
def greet(name):
return f"Hello, {name}!"
name = "Carol"
print(f"{greet(name)}“
Output:
Hello, Carol!
Width and Alignment
Example:
number = 42
print(f"{number:5}") # Right-aligned by default
print(f"{number:<5}") # Left-aligned
print(f"{number:^5}") # Center-aligned
Output:
42
42
42
Variables and Expressions
Variable and data type in Python
Variables
 A variable is a name given to a memory location.
 Variables are the containers for storing data values.
Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
x=5
y = “BCAA"
print(x)
print(y)
Variables
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
Rules for Python variables:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-
z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different
variables)
A variable name cannot be any of the Python keywords.
Multi Words Variable Names
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = “John”
Pascal Case
Each word starts with a capital letter:
MyVariableName = “John”
Snake Case
Each word is separated by an underscore character:
my_variable_name = ”John”
CASTING
If you want to specify the data type of a variable, this can be done with casting.
String variable can be declared either single(‘ ‘) or double quotes(“ “).
To Get the Type of Variable
You can get the data type of a variable with type()
x= int(3) # x will be 3
y= float(3) # y will be 3.0
x=5
y=“BCAA”
print(type(x),type(y))
Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:
One Value to Multiple Variables
You can assign the same value to multiple variables in one line:
x, y, z = 5, 6, 7 x, y, z = “A” , ”B” , “C”
x, y, z = “BCA A”
print(x)
print(y)
print(z)
Many Values to Multiple Variables
Unpack a collection
If you have a collection of values in a list, tuple etc. python allows you to
extract the values into a variable. This is called Unpacking
fruits = [“apple”, “orange”, “cherry”]
x, y, z = fruits
print(x) # output will be apple
print(y) # orange
print(z) # cherry
OUTPUT Variables
By using the print(), we can output the multiple variable separated by
commas(,) .
we can also use + operator to concatenate and output the multiple variables,
but this requires that all variables be of a string type.
x = “python”
y = “is”
z = “awesome”
print(x, y, z) # python is awesome
x = “python ”
y = “is ”
z = “awesome”
print(x+y,+z) # python is awesome
Expressions
An expression is a combination of variables, operators, and values that
evaluates to a result
Example:
result = (5 + 3) * 2 # The expression (5 + 3) * 2 evaluates to 16
Data Types in Python
Data types define the kind of value a variable can hold.
Every value has a data type, we don’t have to characterize the sort of
variable while announcing it.
The interpreter binds the value implicitly to its type.
Python Datatypes
Classification Datatypes
Text Type str
Numeric Types int, float, complex
Sequence Types list, tuple, range
Mapping Type Dictionary
Set Types set, frozenset
Boolean Type bool
Binary Types bytes, bytearray, memoryview
None Type NoneType
Python Numbers
There are three numeric types in Python:
•int
•float
•complex
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(z))
Output
<class 'int'>
<class 'float'>
<class 'complex'>
Int
Int, or integer, is a whole number, positive or negative, without decimals, of
unlimited length
Example
x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Output
<class 'int'>
<class 'int'>
<class 'int'>
Float
Float, or "floating point number" is a number, positive or negative, containing one
or more decimals.
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example
x = 1.10
y = 35e3
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Output
<class 'float'>
<class 'float'>
<class 'float'>
Complex
Complex numbers are written with a "j" as the imaginary part:
Example
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Output
<class 'complex'>
<class 'complex'>
<class 'complex'>
Type Conversion
You can convert from one type to another with int(), float(),
and complex() methods:
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Output
1.0
2
(1+0j)
<class 'float'>
<class 'int'>
<class 'complex'>
List []
Lists are used to store multiple items in a single variable.
A Python list contains items separated by commas and enclosed within square
brackets ([]).
Python lists are similar to arrays in C.
One difference between them is that all the items belonging to a Python list can
be of different data type where as C array can store elements related to a
particular data type.
The values stored in a Python list can be accessed using the slice operator ([ ]
and [:]) with indexes starting at 0 in the beginning of the list and working their
way to end -1.
 The plus (+) sign is the list concatenation operator, and the asterisk (*) is the
repetition operator.
List []
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
Output
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Tuple ( ) Data Type
Python tuple is another sequence data type that is similar to a list.
A Python tuple consists of a number of values separated by commas.
Unlike lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in
brackets ( [ ] ) and their elements and size can be changed, while tuples are
enclosed in parentheses ( ( ) ) and cannot be updated.
Tuples can be thought of as read-only lists.
Tuple ()
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple) # Prints the complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements of the tuple starting from 2nd till 3rd
print (tuple[2:]) # Prints elements of the tuple starting from 3rd element
print (tinytuple * 2) # Prints the contents of the tuple twice
print (tuple + tinytuple) # Prints concatenated tuples
Output
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
List vs Tuple
Feature List Tuple
Mutability Lists are mutable, meaning you can change, add,
or remove elements after the list is created.
my_list = [1, 2, 3]
my_list[1] = 4 # Allowed
my_list.append(5) # Allowed
print(my_list) # Output: [1, 4, 3, 5]
Tuples are immutable, meaning once a tuple is
created, you cannot change its elements.
my_tuple = (1, 2, 3)
my_tuple[1] = 4 # Not allowed, raises TypeError
Syntax: Lists are defined using square brackets [].
my_list = [1, 2, 3]
Tuples are defined using parentheses ().
my_tuple = (1, 2, 3)
Methods: Lists have a variety of built-in methods for
modifying the content, such as append(),
remove(), extend(), pop(), clear(), sort(), and
reverse().
my_list = [1, 2, 3] my_list.append(4) print(my_list) #
Output: [1, 2, 3, 4]
Tuples have fewer methods, primarily for accessing
data, such as count() and index()
my_tuple = (1, 2, 2, 3) print(my_tuple.count(2)) #
Output: 2 print(my_tuple.index(3)) # Output: 3
List vs Tuple
Feature List Tuple
Performance: Lists have a larger memory overhead and are
generally slower than tuples due to their
dynamic nature and ability to be modified.
Tuples are more memory-efficient and faster than
lists due to their immutability.
Use Cases: Use lists when you need a collection of items
that can change, such as when items need to be
added, removed, or modified.
shopping_list = ['milk', 'eggs', 'bread']
shopping_list.append('butter') print(shopping_list)
# Output: ['milk', 'eggs', 'bread', 'butter']
Use tuples for fixed collections of items, such as
coordinates or when you want to ensure the data
remains constant.
coordinates = (10.0, 20.0)
Heterogeneity: can store heterogeneous data types (different
types of items)
can store heterogeneous data types (different types
of items)
List vs Tuple
Feature List Tuple
Iteration: can be iterated over in the same way.
# List iteration
my_list = [1, "apple", 3.14]
for item in my_list:
print(item)
Output
1
apple
3.14
can be iterated over in the same way.
# Tuple iteration
my_tuple = (1, "apple", 3.14)
for item in my_tuple:
print(item)
Output
1
apple
3.14
Range()
It represents an immutable sequence of numbers
Used for looping a specific number of times in ‘for’ loops.
The range() returns a sequence of numbers starting from 0 by and
increments by 1 (by default) and stops before a specific number
Syntax
range(start, stop, step)
Start – optional, An integer number specifying at which position to start. Default is 0
Stop – Required, An integer number specifying at which position to stop(not included)
Step – optional, An integer number specifying the increment. Default is 1
Range() - Example
Create a sequence of numbers from 0 to 5, and print each item in the sequence.
Create a sequence of numbers from 3 to 5, and print each item in the sequence.
Create a sequence of numbers from 3 to 19, but increment by 2 instead of 1
x = range(6)
for n in x :
print(n)
x = range(3, 6)
for n in x :
print(n)
x = range(3, 20,2)
for n in x :
print(n)
Dictionary
In Python, you can use the built-in dict data type to create and manipulate
dictionaries.
Dictionaries are a type of collection that store key-value pairs, where each key maps
to a value.
Dictionaries are also known as associative arrays or hashmaps in other programming
languages.
Creating a dictionary:
You can create a dictionary using curly braces {} and separating key-value pairs with
colons :.
Syntax:
dict_var = {key1 : value1, key2 : value2, …..}
# Empty dictionary
empty_dict = {}
# Dictionary with initial key-value pairs
my_dict = {
"name": "John",
"age": 30,
"city": "New York"
}
# Adding new key-value pair
my_dict["occupation"] = "Engineer"
# Modifying an existing value
my_dict["age"] = 31
print(my_dict)
# Output: {'name': 'John', 'age': 31, 'city': 'New York', 'occupation': 'Engineer'}
SET
In Python, a set is an unordered collection of unique elements.
It is a built-in data type that allows you to store and perform set operations like
union, intersection, difference, and more.
Sets are denoted using curly braces {} or by using the set() constructor.
Here's a basic introduction to working with sets in Python:
Creating a set:
Syntax:
 Using curly braces {}
set_name = {item1, item2, item3, …..itemn}
 Using the set()
set_name = set(item1, item2, item3, …..itemn)
Set (Set Types)
Key Characteristics:
Unordered: Sets do not maintain any specific order of elements.
Unique Elements: Each element in a set must be unique. If you try to add a
duplicate element, it will be ignored.
Mutable: You can add or remove elements after the set is created.
Unindexed: Sets do not support indexing, slicing, or other sequence-like
behaviors.
Example
set1 = set()
set2 = {'James', 2, 3,'Python'}
#Printing Set value
print(set2)
# Adding element to the set
set2.add(10)
print(set2)
#Removing element from the set
set2.remove(2)
print(set2)
frozenset()
Freeze the list, and make it unchangeable
Syntax:
frozenset(iterable)
Parameter Description
iterable An iterable object, like list, set, tuple etc.
frozenset()
Example
mylist=['apple','banana','cherry']
x = frozenset(mylist)
x[1] = "strawberry“
Output:
File "demo_ref_frozenset2.py", line 3, in <module>
x[1] = "strawberry"
TypeError: 'frozenset' object does not support item assignment
None Type
‘None’ data type represent an object that does not conduct any value.
In Java, it is called ‘Null’ object, in python it is called ‘None’ object.
In Python program, maximum of only one ‘None’ object is provided.
‘None’ type is used inside a function as a default value of the arguments.
When calling the function, if no value is passed, then the default value will be
taken as ‘None’.
In Boolean expressions, ‘None’ datatype is represents ‘False’.
Operators
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators
7. Membership Operators
Arithmetic Operators
Operator Name Example
+ Addition Adds two operands. x + y 3 + 2 # 5
- Subtraction Subtracts the second operand from the first x - y 3 - 2 # 1
* Multiplication Multiplies two operands. x * y 3 * 2 # 6
/ Division Divides the first operand by the second x / y 3 / 2 # 1.5
% Modulus Returns the remainder when the first operand is
divided by the second.
x % y 3 % 2 # 1
** Exponentiation Raises the first operand to the power of the
second
x ** y 3 ** 2 # 9
// Floor division Divides the first operand by the second and
returns the largest integer less than or equal to
the result.
x // y 3 // 2 # 1
Comparison Operators
Operator Name Example
== Equal x == y 3 == 2 # False
!= Not equal x != y 3 != 2 # True
> Greater than x > y 3 > 2 # True
< Less than x < y 3 < 2 # False
>= Greater than or equal to x >= y 3 >= 2 # True
<= Less than or equal to x <= y 3 <= 2 # False
Logical Operators
Operator Description Example
and Returns True if both
statements are true
x < 5 and x < 10 True and False # False
or Returns True if one of the
statements is true
x < 5 or x < 4 True or False # True
not Reverse the result,
returns False if the result
is true
not(x < 5 and x <
10)
not True # False
Bitwise Operators
Operator Name Description Example
& AND Sets each bit to 1 if both bits
are 1
x & y 3 & 2 # 2
| OR Sets each bit to 1 if one of two
bits is 1
x | y 3 | 2 # 3
^ XOR Sets each bit to 1 if only one of
two bits is 1
x ^ y 3 ^ 2 # 1
~ NOT Inverts all the bits ~x ~3 # -4
<< Zero fill
left shift
Shift left by pushing zeros in
from the right and let the
leftmost bits fall off
x << 2 3 << 1 # 6
>> Signed
right shift
Shift right by pushing copies
of the leftmost bit in from the
left, and let the rightmost bits
fall off
x >> 2 3 >> 1 # 1
Assignment Operators
1. = (Assign)
2. += (Add and assign)
3. -= (Subtract and assign)
4. *= (Multiply and assign)
5. /= (Divide and assign)
6. //= (Floor divide and assign)
7. %= (Modulus and assign)
8. **= (Exponentiate and assign)
9. &= (Bitwise AND and assign)
10.|= (Bitwise OR and assign)
11.^= (Bitwise XOR and assign)
12.<<= (Bitwise Left Shift and assign)
13.>>= (Bitwise Right Shift and assign)
Identity Operators
Operator Description Example
is Returns True if both variables are the
same object
x is y
is not Returns True if both variables are not
the same object
x is not y
Membership Operators
Operator Description Example
in Returns True if a sequence with the
specified value is present in the object
x in y 2 in [1, 2, 3] # True
not in Returns True if a sequence with the
specified value is not present in the
object
x not in y 4 not in [1, 2, 3] # True
Conditional Statements
Conditional Statements
• In python, the Conditional Statements are the statements that controls the execution of
the program on the basis of the specified condition.
• It is useful for determining whether a condition is true or not.
• If the condition is true, a single or block of statement is executed.
• Examples
• if statement
• if else statement
• Nested if statement
• elif else statement
if statement
Executes a block of code if a specified condition is true.
Syntax:
if condition:
# code block
if statement
Example
age = 18
if age >= 18:
print("You are an adult.")
Output
You are an adult.
elif Statement
elif Short for "else if", it checks another condition if the previous if or elif
condition is false.
Syntax:
if condition:
# code block
elif another_condition:
# another code block
elif Statement
Example
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
Output
Grade: B
else statement
Executes a block of code if none of the preceding conditions are true.
if condition:
# code block
elif another_condition:
# another code block
else:
# code block if no conditions
are true
Syntax:
else Statement
Example
score = 70
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Grade: C")
Output
Grade: C
Short Hand If
If you have only one statement to execute, you can put it on the same line as the
if statement.
Example:
a = 200
b = 33
if a > b: print("a is greater than b")
Output
a is greater than b
Short Hand If ... Else
If you have only one statement to execute, one for if, and one for else, you can put
it all on the same line:
Example:
a = 2
b = 330
print("A") if a > b else print("B")
Output
B
The pass Statement
if statements cannot be empty, but if you for some reason have an if statement
with no content, put in the pass statement to avoid getting an error.
Example:
a = 33
b = 200
if b > a:
pass
Output
Python Loops
Python Loops
Python has two primitive loop commands:
1. while loops
2. for loops
while loops
Executes a block of code as long as a specified condition is true.
while condition:
# code block
Syntax:
while loops
Example
count = 0
while count < 5:
print(count)
count += 1
Output
0
1
2
3
4
The break Statement
With the break statement we can stop the loop even if the while condition is true:
Example:
i = 1
while i < 6:
print(i)
if (i == 3):
break
i += 1
Output
1
2
3
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Output
1
2
3
4
5
6
for loops
The for loop in Python is used to iterate over a sequence (such as a list, tuple,
dictionary, set, or string) and execute a block of code for each item in the
sequence.
It is particularly useful when you need to perform an operation on each element
of a collection.
for loops
for: The keyword to start the loop.
item: A variable that takes the value of the next item in the sequence on each
iteration.
in: The keyword used to specify the sequence to iterate over.
sequence: The collection (list, tuple, string, etc.) to iterate over.
# code block: The block of code to execute for each item in the sequence.
for item in sequence:
# code block
Syntax:
for loops
Example 1: Iterating Over a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output
apple
banana
cherry
for loops
Example 2: Iterating Over a String
for letter in "Python":
print(letter)
Output
P
y
t
h
o
n
for loops
Example 3: Using range() Function
for number in range(5):
print(number)
Output
0
1
2
3
4
for loops
Example 4: Iterating Over a Dictionary
person = {"name": "Alice", "age": 25}
for key in person:
print(key)
Output
Name
age
for loops
Example 4: Iterating Over a Dictionary
person = {"name": "Alice", "age": 25}
for key in person:
print(value)
Output
Alice
25
Example 5: Nested for Loop
Example
colors = ["red", "green", "blue"]
objects = ["ball", "pen"]
for color in colors:
for obj in objects:
print(color, obj)
Output:
red ball
red pen
green ball
green pen
blue ball
blue pen

Python Programming_Unit 1_Prof. Jishnu M S.pdf

  • 1.
  • 2.
    What is Python…? Pythonis a popular high-level programming language. It was created by Guido Van Rossum. It is used for Web Development Software Development System Scripting Mathematics
  • 3.
    What is Python…? Pythonis a popular high-level programming language. It was created by Guido Van Rossum Python is an easy language to learn because of its simple syntax Python supports modules and packages, which encourages program modularity and code reuse. Python is a general purpose programming language that is often applied in scripting roles. So, Python is programming language as well as scripting language. Python is also called as Interpreted language
  • 4.
    What can Pythondo? Python can be used on a server to create web applications. Python can be used alongside software to create workflows. Python can connect to database systems. It can also read and modify files. Python can be used to handle big data and perform complex mathematics. Python can be used for rapid prototyping, or for production-ready software development.
  • 5.
    Why Python…? Python workson different platforms(Windows, Mac, Linux etc). It has simple syntax similar to English language. Python has syntax that allows developers to write programs with fewer lines than some other programming languages. Python runs on interpreter system, meaning that code can be executed as soon as it written. This means that prototyping can be very quick. It can be treated in a procedural way an object-oriented way..
  • 6.
    Why Python…? It makesdevelopment & debugging fast because no compilation step is included in python development and the edit-test-debug cycle is very fast. Python is a open source, cost free programming language. It is having large collection of libraries that can be used to make its function easier. These libraries cover many domains Web Development Scientific Computing Data Analysis Python is a case-sensitive language, which means that upper & lower case letters are treated differently
  • 7.
    Where is Pythonused…? Data Science Desktop applications Mobile Applications Software Development AI Machine Learning Web Applications Gaming IoT Finance Networking Testing Speech Recognition Computer Vision or Image Processing Applications 3D CAD Applications
  • 8.
    Python popular Libraries WebDevelopment ( Server Side) – Django flask, pyramis, cherrypy GUI Based Applications – TK, PyGTK, PyJs Machine Learning – TensorFlow, PyTorch, matplotliby, scipy Mathematics – Numpy, Pandas Game Development – Pygame Testing – Pytest Web Scraping & Parsing – Beautiful Soup
  • 9.
    History Invented in theNetherlands, early 90s by Guido van Rossum Python was conceived in the late 1980s and its implementation was started in December 1989 Guido V an Rossum is fan of ‘Monty Python’s Flying Circus’, this is a famous TV show in Netherlands Named after Monty Python Open sourced from the beginning
  • 10.
    Guido van Rossum “Pythonis an experiment in how much freedom program-mers need. Too much freedom and nobody can read another's code; too little and expressive-ness is endangered.”
  • 11.
    Whywas python created? "My originalmotivation for creating Python was the perceived need for a higher level language in the Amoeba [Operating Systems]project. I realized that the development of system Moreover, doing these things in the Bourne administration utilities in C was taking too long. shell wouldn't work for a variety of reasons. ... So, there was a need for a language that would bridge the gap between C and the shell” - Guido VanRossum
  • 12.
    Differences between programand scripting language • Program • a program is executed (i.e. the source is first compiled, and the result of that compilation is expected) • A "program" in general, is a sequence of instructions written so that a computer can perform certain task. • Scripting • a script is interpreted • A "script" is code written in a scripting language. A scripting language is nothing but a type of programming language in which we can write code to control another software application.
  • 13.
    PROGRAMMING LANGUAGE SCRIPTINGLANGUAGE These are Program - Independent A user needs to run scripting languages inside an existing program. Thus it is Program- Dependent It create .exe files It doesn’t create file type These are self Executable . They don not require any hosts for execution It requires hosts for execution Compiled programs runs faster when compared to interpreted languages It runs slower when compared to programming language C, ++, Java, VB, Cobol, Python & Javascript (front end & Backend) VB Script, Perl, Python, Ruby, PHP, Javascript etc All the programming languages are not Scripting languages All Scripting languages are programming languages
  • 14.
    Differences between programand scripting language Applications of Scripting Languages : 1. To automate certain tasks in a program 2. Extracting information from a data set 3. Less code intensive as compared to traditional programming languages Applications of Programming Languages : 1. More compatible while integrating code with mathematical models 2. Languages like JAVA can be compiled and then used on any platform
  • 16.
    Advantages of Python 1.Easy to Read, Learn and Write Python is a high-level programming language that has English-like syntax. This makes it easier to read and understand the code. Python is really easy to pick up and learn, that is why a lot of people recommend Python to beginners. You need less lines of code to perform the same task as compared to other major languages like C/C++ and Java. 2. Improved Productivity Python is a very productive language. Due to the simplicity of Python, developers can focus on solving the problem. They don’t need to spend too much time in understanding the syntax or behaviour of the programming language. You write less code and get more things done.
  • 17.
    3. Interpreted Language •Python is an interpreted language which means that Python directly executes the code line by line. In case of any error, it stops further execution and reports back the error which has occurred. • Python shows only one error even if the program has multiple errors. This makes debugging easier. 4. Dynamically Typed • Python doesn’t know the type of variable until we run the code. It automatically assigns the data type during execution. The programmer doesn’t need to worry about declaring variables and their data types. Advantages of Python
  • 18.
    5. Free andOpen-Source • Python comes under the OSI approved open-source license. This makes it free to use and distribute. You can download the source code, modify it and even distribute your version of Python. This is useful for organizations that want to modify some specific behaviour and use their version for development. 6. Vast Libraries Support • The standard library of Python is huge, you can find almost all the functions needed for your task. So, you don’t have to depend on external libraries. • But even if you do, a Python package manager (pip) makes things easier to import other great packages from the Python package index (PyPi). It consists of over 200,000 packages.
  • 19.
    Disadvantages of Python 1.Slow Speed The line by line execution of code often leads to slow execution. The dynamic nature of Python is also responsible for the slow speed of Python because it has to do the extra work while executing code. So, Python is not used for purposes where speed is an important aspect of the project. 2. Not Memory Efficient To provide simplicity to the developer, Python has to do a little trade-off. The Python programming language uses a large amount of memory. This can be a disadvantage while building applications when we prefer memory optimization. 3. Weak in Mobile Computing Python is generally used in server-side programming. We don’t get to see Python on the client-side or mobile applications because of the following reasons. Python is not memory efficient and it has slow processing power as compared to other languages.
  • 20.
    4. Database Access •Programming in Python is easy and stress-free. But when we are interacting with the database, it lacks behind. • The Python’s database access layer is primitive and underdeveloped in comparison to the popular technologies like JDBC and ODBC. • Huge enterprises need smooth interaction of complex legacy data and Python is thus rarely used in enterprises. 5. Runtime Errors • As we know Python is a dynamically typed language so the data type of a variable can change anytime. A variable containing integer number may hold a string in the future, which can lead to Runtime Errors. • Therefore Python programmers need to perform thorough testing of the applications. Disadvantages of Python
  • 21.
    Why do peopleuse Python…? The following primary factors cited by Python users seem to be these: Python is object-oriented Structure supports such concepts as polymorphism, operation overloading, and multiple inheritance. Indentation Indentation is one of the greatest future in Python. It's free (open source) Downloading and installing Python is free and easy Source code is easily accessible
  • 22.
    It's powerful - Dynamictyping - Built-in types and tools - Library utilities - Third party utilities (e.g. Numeric, NumPy, SciPy) -It's portable - Python runs virtually every major platform used today -As long as you have a compatible Python interpreter installed, Python programs will run in exactly the same manner, irrespective of platform.
  • 23.
    • It's mixable -Python can be linked to components written in other languages easily - Linking to fast, compiled code is useful to computationally intensive problems - Python/C integration is quite common • It's easy to use - No intermediate compile and link steps as in C/ C++ - Python programs are compiled automatically to an intermediate form called bytecode, which the interpreter then reads - This gives Python the development speed of an interpreter without - the performance loss inherent in purely interpreted languages • It's easy to learn - Structure and syntax are pretty intuitive and easy to grasp
  • 25.
    • The Serverand Client applications are coded using Python • Machine Learning is used to cluster users based on their interest on shows and retain them for longer • Better search result are provided based on ranking of the websites and much more • Transfer of files between peer- to-peer which started out as a normal python file Bit- Torrent Google Dropbox NETFLIX Where is python used in the Industry
  • 26.
    • Scientific calculations arecomputed using python • Machine Learning and Artificial Intelligence • Cyber-Security analysis and other encryption and decryption work is done using python • Data visualizations from the Matplotlib and Seaborn galleries National Security Agency NASA Where is python used in the Industry
  • 29.
    Difference between Interactiveand Script mode in Python Interactive mode: Instructions are given in front of Python prompt (eg., >>> ) in Python Shell. Python carries out the given instruction and shows the result there itself. Script mode: Python instructions are stored in a file generally with .py extension and are executed together in one go as a unit. The saved instructions are known as Python script or Python program.
  • 30.
    Coding style inPython Coding style in Python is an important aspect of writing clean, readable, and maintainable code. The Python community has established guidelines and best practices, primarily documented in PEP 8, the Python Enhancement Proposal that provides conventions for writing code in Python.
  • 31.
    Coding style inPython 1. Indentation 2. Line Length 3. Blank Lines 4. Imports 5. Naming Conventions 6. Docstrings 7. Comments 8. Whitespace in Expressions and Statements 9. Error Handling
  • 32.
    Coding style inPython 1. Indentation  Use 4 spaces per indentation level.  Avoid using tabs.  Consistent indentation is crucial in Python, as it defines the structure of the code. 1. def my_function(x): 2. if x > 0: 3. print("Positive") 4. else: 5. print("Non-positive")
  • 33.
    Python Indentation Indentation refersto the space at the beginning of a code line Where in another programming language the indentation in code is for the readability only, the indentation in python is very important. Python use indentation to indicate a block of code. The number of spaces is up to you as a programmer, the most common use if four, but it has to be at least one. You have to use the same number of spaces in the same block of code. If 5>2: print(“ Five greater than two”)
  • 34.
    Coding style inPython 2. Line Length  Limit all lines to a maximum of 79 characters.  For long blocks of text (e.g., docstrings or comments), lines should be limited to 72 characters.  Use parentheses to wrap long lines instead of using a backslash () for line continuation. # Example of wrapping lines result = some_function_that_does_something( argument1, argument2, argument3, argument4, argument5 )
  • 35.
    Coding style inPython 3. Blank Lines  Use blank lines to separate top-level functions and class definitions.  Inside functions, use blank lines to separate logical sections of the code. # Example class MyClass: def __init__(self): self.value = 0 def increment(self): self.value += 1 def reset(self): self.value = 0
  • 36.
    Coding style inPython 4. Imports  Imports should be on separate lines and typically at the top of the file.  Follow the order: standard library imports, related third-party imports, and then local application/library-specific imports. Example # Correct way to do imports import os import sys from datetime import datetime from collections import defaultdict import my_local_module
  • 37.
    Coding style inPython 5. Naming Conventions Variables, Functions, and Attributes: Use lowercase words separated by underscores.  Example def calculate_area(radius): pi_value = 3.14159 return pi_value * (radius ** 2)
  • 38.
    Python Identifiers  Apython identifier is a name used to identify a variable, function, class, module, or the object. The identifier starts with a letter A to Z, or a to z, or an underscore(_) followed by a zero or more letters, underscore and digits(0 to 9). Python does not allow punctuation characters within an identifier Python is a case sensitive language. Ex: num1 & Num1 are two different identifiers.
  • 39.
  • 40.
    Coding style inPython 6. Docstrings  Use docstrings to document all public modules, classes, functions, and methods.  Follow the convention for multiline docstrings:  The first line is a short summary.  The second line is blank Example def calculate_area(radius): """ Calculate the area of a circle given its radius. :param radius: The radius of the circle. :return: The area of the circle. """ return 3.14159 * (radius ** 2)
  • 41.
    Coding style inPython 7. Comments  Use comments to explain why something is done, not what is done.  If the code isn't self-explanatory, it may need to be refactored.  Comments should be complete sentences, with the first word capitalized and ending with a period. Example # Initialize the count to zero count = 0
  • 42.
  • 43.
    Comments in Python Comments starts with a # To add multi line comment # this is a comment # this is a comment # written in # more than just a line “ “ “ this is a comment written in more than just a line “ “ “
  • 44.
    Coding style inPython 8. Whitespace in Expressions and Statements  Avoid extraneous whitespace.  Immediately inside parentheses, brackets, or braces: list[1], not list[ 1 ].  Before a comma, semicolon, or colon: if x == 1:, not if x == 1 :.  Around the assignment operator when assigning a default value: def func(param=None):, not def func(param = None):. Example # Good a = (1, 2, 3) # Avoid b = ( 1, 2, 3 )
  • 45.
    Coding style inPython 9. Error Handling  Use exceptions to handle errors. Use try/except blocks to manage exceptions gracefully, and always catch specific exceptions. Example try: result = some_function() except ValueError as e: print(f"ValueError encountered: {e}")
  • 46.
  • 47.
    print() function The print()function in Python is used to output data to the console or terminal. It can print strings, numbers, and other data types, and it supports various formatting options.
  • 48.
    Multiple Arguments print()function You can pass multiple arguments to print(), and they will be separated by spaces by default
  • 49.
    End and SeparatorParameters print() function sep: Defines the separator between multiple arguments (default is a space). end: Defines what is printed at the end of the line (default is a newline).
  • 50.
  • 51.
    input() function The input()function in Python is used to read user input from the console. It allows you to prompt the user to enter data, which is then returned as a string. Basic Input • This will display the prompt Enter your name:, and whatever the user types in will be stored in the user_input variable
  • 52.
    Using the Prompt Here,How old are you? is the prompt displayed to the user. Converting Input • By default, input() returns a string. To use the input as another data type, such as an integer or float, you need to convert it:
  • 53.
    Handling Invalid Input Youcan use try-except blocks to handle cases where the user input cannot be converted to the expected type: Input Without Prompt • If you don't provide a prompt, input() will simply wait for the user to enter something:
  • 54.
  • 55.
    formatted string literal(f-string) Anf-string, short for formatted string literal, is a feature introduced in Python 3.6 It provides a convenient and readable way to embed expressions inside string literals. F-strings are prefixed with an f or F and allow expressions to be included within curly braces {}. These expressions are evaluated at runtime and formatted using the specified format.
  • 56.
    format specifiers In Python,format specifiers are used to control the formatting of strings when using various string formatting methods. These include the % operator, Common Format Specifiers: %d: Integer %f: Floating-point number %.2f: Floating-point number with 2 decimal places %s: String %x: Hexadecimal integer (lowercase) %X: Hexadecimal integer (uppercase)
  • 57.
    format specifiers name ="Alice" age = 30 height = 5.7 print("Name: %s, Age: %d, Height: %.1f" % (name, age, height)) Output: Name: Alice, Age: 30, Height: 5.7
  • 58.
  • 59.
    Variable Embedding –f-string Example: user = "Bob" print(f"Hello, {user}!") Output: Hello, Bob!
  • 60.
    Arithmetic Expressions –f-string Example: a = 5 b = 3 print(f"{a} + {b} = {a + b}") Output: 5 + 3 = 8
  • 61.
    Function Calls– f-string Example: defgreet(name): return f"Hello, {name}!" name = "Carol" print(f"{greet(name)}“ Output: Hello, Carol!
  • 62.
    Width and Alignment Example: number= 42 print(f"{number:5}") # Right-aligned by default print(f"{number:<5}") # Left-aligned print(f"{number:^5}") # Center-aligned Output: 42 42 42
  • 63.
  • 64.
    Variable and datatype in Python
  • 65.
    Variables  A variableis a name given to a memory location.  Variables are the containers for storing data values. Creating Variables Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. x=5 y = “BCAA" print(x) print(y)
  • 66.
    Variables Variable Names A variablecan have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables: A variable name must start with a letter or the underscore character A variable name cannot start with a number A variable name can only contain alpha-numeric characters and underscores (A- z, 0-9, and _ ) Variable names are case-sensitive (age, Age and AGE are three different variables) A variable name cannot be any of the Python keywords.
  • 67.
    Multi Words VariableNames Variable names with more than one word can be difficult to read. There are several techniques you can use to make them more readable: Camel Case Each word, except the first, starts with a capital letter: myVariableName = “John” Pascal Case Each word starts with a capital letter: MyVariableName = “John” Snake Case Each word is separated by an underscore character: my_variable_name = ”John”
  • 68.
    CASTING If you wantto specify the data type of a variable, this can be done with casting. String variable can be declared either single(‘ ‘) or double quotes(“ “). To Get the Type of Variable You can get the data type of a variable with type() x= int(3) # x will be 3 y= float(3) # y will be 3.0 x=5 y=“BCAA” print(type(x),type(y))
  • 69.
    Many Values toMultiple Variables Python allows you to assign values to multiple variables in one line: One Value to Multiple Variables You can assign the same value to multiple variables in one line: x, y, z = 5, 6, 7 x, y, z = “A” , ”B” , “C” x, y, z = “BCA A” print(x) print(y) print(z)
  • 70.
    Many Values toMultiple Variables Unpack a collection If you have a collection of values in a list, tuple etc. python allows you to extract the values into a variable. This is called Unpacking fruits = [“apple”, “orange”, “cherry”] x, y, z = fruits print(x) # output will be apple print(y) # orange print(z) # cherry
  • 71.
    OUTPUT Variables By usingthe print(), we can output the multiple variable separated by commas(,) . we can also use + operator to concatenate and output the multiple variables, but this requires that all variables be of a string type. x = “python” y = “is” z = “awesome” print(x, y, z) # python is awesome x = “python ” y = “is ” z = “awesome” print(x+y,+z) # python is awesome
  • 72.
    Expressions An expression isa combination of variables, operators, and values that evaluates to a result Example: result = (5 + 3) * 2 # The expression (5 + 3) * 2 evaluates to 16
  • 73.
    Data Types inPython Data types define the kind of value a variable can hold. Every value has a data type, we don’t have to characterize the sort of variable while announcing it. The interpreter binds the value implicitly to its type.
  • 74.
    Python Datatypes Classification Datatypes TextType str Numeric Types int, float, complex Sequence Types list, tuple, range Mapping Type Dictionary Set Types set, frozenset Boolean Type bool Binary Types bytes, bytearray, memoryview None Type NoneType
  • 75.
    Python Numbers There arethree numeric types in Python: •int •float •complex Variables of numeric types are created when you assign a value to them: Example x = 1 # int y = 2.8 # float z = 1j # complex print(type(x)) print(type(y)) print(type(z)) Output <class 'int'> <class 'float'> <class 'complex'>
  • 76.
    Int Int, or integer,is a whole number, positive or negative, without decimals, of unlimited length Example x = 1 y = 35656222554887711 z = -3255522 print(type(x)) print(type(y)) print(type(z)) Output <class 'int'> <class 'int'> <class 'int'>
  • 77.
    Float Float, or "floatingpoint number" is a number, positive or negative, containing one or more decimals. Float can also be scientific numbers with an "e" to indicate the power of 10. Example x = 1.10 y = 35e3 z = -35.59 print(type(x)) print(type(y)) print(type(z)) Output <class 'float'> <class 'float'> <class 'float'>
  • 78.
    Complex Complex numbers arewritten with a "j" as the imaginary part: Example x = 3+5j y = 5j z = -5j print(type(x)) print(type(y)) print(type(z)) Output <class 'complex'> <class 'complex'> <class 'complex'>
  • 79.
    Type Conversion You canconvert from one type to another with int(), float(), and complex() methods: x = 1 # int y = 2.8 # float z = 1j # complex #convert from int to float: a = float(x) #convert from float to int: b = int(y) #convert from int to complex: c = complex(x) print(a) print(b) print(c) print(type(a)) print(type(b)) print(type(c)) Output 1.0 2 (1+0j) <class 'float'> <class 'int'> <class 'complex'>
  • 80.
    List [] Lists areused to store multiple items in a single variable. A Python list contains items separated by commas and enclosed within square brackets ([]). Python lists are similar to arrays in C. One difference between them is that all the items belonging to a Python list can be of different data type where as C array can store elements related to a particular data type. The values stored in a Python list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1.  The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.
  • 81.
    List [] list =[ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print (list) # Prints complete list print (list[0]) # Prints first element of the list print (list[1:3]) # Prints elements starting from 2nd till 3rd print (list[2:]) # Prints elements starting from 3rd element print (tinylist * 2) # Prints list two times print (list + tinylist) # Prints concatenated lists Output ['abcd', 786, 2.23, 'john', 70.2] abcd [786, 2.23] [2.23, 'john', 70.2] [123, 'john', 123, 'john'] ['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
  • 82.
    Tuple ( )Data Type Python tuple is another sequence data type that is similar to a list. A Python tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses. The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.
  • 83.
    Tuple () tuple =( 'abcd', 786 , 2.23, 'john', 70.2 ) tinytuple = (123, 'john') print (tuple) # Prints the complete tuple print (tuple[0]) # Prints first element of the tuple print (tuple[1:3]) # Prints elements of the tuple starting from 2nd till 3rd print (tuple[2:]) # Prints elements of the tuple starting from 3rd element print (tinytuple * 2) # Prints the contents of the tuple twice print (tuple + tinytuple) # Prints concatenated tuples Output ('abcd', 786, 2.23, 'john', 70.2) abcd (786, 2.23) (2.23, 'john', 70.2) (123, 'john', 123, 'john') ('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
  • 84.
    List vs Tuple FeatureList Tuple Mutability Lists are mutable, meaning you can change, add, or remove elements after the list is created. my_list = [1, 2, 3] my_list[1] = 4 # Allowed my_list.append(5) # Allowed print(my_list) # Output: [1, 4, 3, 5] Tuples are immutable, meaning once a tuple is created, you cannot change its elements. my_tuple = (1, 2, 3) my_tuple[1] = 4 # Not allowed, raises TypeError Syntax: Lists are defined using square brackets []. my_list = [1, 2, 3] Tuples are defined using parentheses (). my_tuple = (1, 2, 3) Methods: Lists have a variety of built-in methods for modifying the content, such as append(), remove(), extend(), pop(), clear(), sort(), and reverse(). my_list = [1, 2, 3] my_list.append(4) print(my_list) # Output: [1, 2, 3, 4] Tuples have fewer methods, primarily for accessing data, such as count() and index() my_tuple = (1, 2, 2, 3) print(my_tuple.count(2)) # Output: 2 print(my_tuple.index(3)) # Output: 3
  • 85.
    List vs Tuple FeatureList Tuple Performance: Lists have a larger memory overhead and are generally slower than tuples due to their dynamic nature and ability to be modified. Tuples are more memory-efficient and faster than lists due to their immutability. Use Cases: Use lists when you need a collection of items that can change, such as when items need to be added, removed, or modified. shopping_list = ['milk', 'eggs', 'bread'] shopping_list.append('butter') print(shopping_list) # Output: ['milk', 'eggs', 'bread', 'butter'] Use tuples for fixed collections of items, such as coordinates or when you want to ensure the data remains constant. coordinates = (10.0, 20.0) Heterogeneity: can store heterogeneous data types (different types of items) can store heterogeneous data types (different types of items)
  • 86.
    List vs Tuple FeatureList Tuple Iteration: can be iterated over in the same way. # List iteration my_list = [1, "apple", 3.14] for item in my_list: print(item) Output 1 apple 3.14 can be iterated over in the same way. # Tuple iteration my_tuple = (1, "apple", 3.14) for item in my_tuple: print(item) Output 1 apple 3.14
  • 89.
    Range() It represents animmutable sequence of numbers Used for looping a specific number of times in ‘for’ loops. The range() returns a sequence of numbers starting from 0 by and increments by 1 (by default) and stops before a specific number Syntax range(start, stop, step) Start – optional, An integer number specifying at which position to start. Default is 0 Stop – Required, An integer number specifying at which position to stop(not included) Step – optional, An integer number specifying the increment. Default is 1
  • 90.
    Range() - Example Createa sequence of numbers from 0 to 5, and print each item in the sequence. Create a sequence of numbers from 3 to 5, and print each item in the sequence. Create a sequence of numbers from 3 to 19, but increment by 2 instead of 1 x = range(6) for n in x : print(n) x = range(3, 6) for n in x : print(n) x = range(3, 20,2) for n in x : print(n)
  • 91.
    Dictionary In Python, youcan use the built-in dict data type to create and manipulate dictionaries. Dictionaries are a type of collection that store key-value pairs, where each key maps to a value. Dictionaries are also known as associative arrays or hashmaps in other programming languages. Creating a dictionary: You can create a dictionary using curly braces {} and separating key-value pairs with colons :. Syntax: dict_var = {key1 : value1, key2 : value2, …..}
  • 92.
    # Empty dictionary empty_dict= {} # Dictionary with initial key-value pairs my_dict = { "name": "John", "age": 30, "city": "New York" }
  • 93.
    # Adding newkey-value pair my_dict["occupation"] = "Engineer" # Modifying an existing value my_dict["age"] = 31 print(my_dict) # Output: {'name': 'John', 'age': 31, 'city': 'New York', 'occupation': 'Engineer'}
  • 94.
    SET In Python, aset is an unordered collection of unique elements. It is a built-in data type that allows you to store and perform set operations like union, intersection, difference, and more. Sets are denoted using curly braces {} or by using the set() constructor. Here's a basic introduction to working with sets in Python: Creating a set: Syntax:  Using curly braces {} set_name = {item1, item2, item3, …..itemn}  Using the set() set_name = set(item1, item2, item3, …..itemn)
  • 95.
    Set (Set Types) KeyCharacteristics: Unordered: Sets do not maintain any specific order of elements. Unique Elements: Each element in a set must be unique. If you try to add a duplicate element, it will be ignored. Mutable: You can add or remove elements after the set is created. Unindexed: Sets do not support indexing, slicing, or other sequence-like behaviors.
  • 96.
    Example set1 = set() set2= {'James', 2, 3,'Python'} #Printing Set value print(set2) # Adding element to the set set2.add(10) print(set2) #Removing element from the set set2.remove(2) print(set2)
  • 97.
    frozenset() Freeze the list,and make it unchangeable Syntax: frozenset(iterable) Parameter Description iterable An iterable object, like list, set, tuple etc.
  • 98.
    frozenset() Example mylist=['apple','banana','cherry'] x = frozenset(mylist) x[1]= "strawberry“ Output: File "demo_ref_frozenset2.py", line 3, in <module> x[1] = "strawberry" TypeError: 'frozenset' object does not support item assignment
  • 100.
    None Type ‘None’ datatype represent an object that does not conduct any value. In Java, it is called ‘Null’ object, in python it is called ‘None’ object. In Python program, maximum of only one ‘None’ object is provided. ‘None’ type is used inside a function as a default value of the arguments. When calling the function, if no value is passed, then the default value will be taken as ‘None’. In Boolean expressions, ‘None’ datatype is represents ‘False’.
  • 101.
    Operators 1. Arithmetic Operators 2.Comparison Operators 3. Logical Operators 4. Bitwise Operators 5. Assignment Operators 6. Identity Operators 7. Membership Operators
  • 102.
    Arithmetic Operators Operator NameExample + Addition Adds two operands. x + y 3 + 2 # 5 - Subtraction Subtracts the second operand from the first x - y 3 - 2 # 1 * Multiplication Multiplies two operands. x * y 3 * 2 # 6 / Division Divides the first operand by the second x / y 3 / 2 # 1.5 % Modulus Returns the remainder when the first operand is divided by the second. x % y 3 % 2 # 1 ** Exponentiation Raises the first operand to the power of the second x ** y 3 ** 2 # 9 // Floor division Divides the first operand by the second and returns the largest integer less than or equal to the result. x // y 3 // 2 # 1
  • 103.
    Comparison Operators Operator NameExample == Equal x == y 3 == 2 # False != Not equal x != y 3 != 2 # True > Greater than x > y 3 > 2 # True < Less than x < y 3 < 2 # False >= Greater than or equal to x >= y 3 >= 2 # True <= Less than or equal to x <= y 3 <= 2 # False
  • 104.
    Logical Operators Operator DescriptionExample and Returns True if both statements are true x < 5 and x < 10 True and False # False or Returns True if one of the statements is true x < 5 or x < 4 True or False # True not Reverse the result, returns False if the result is true not(x < 5 and x < 10) not True # False
  • 105.
    Bitwise Operators Operator NameDescription Example & AND Sets each bit to 1 if both bits are 1 x & y 3 & 2 # 2 | OR Sets each bit to 1 if one of two bits is 1 x | y 3 | 2 # 3 ^ XOR Sets each bit to 1 if only one of two bits is 1 x ^ y 3 ^ 2 # 1 ~ NOT Inverts all the bits ~x ~3 # -4 << Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off x << 2 3 << 1 # 6 >> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off x >> 2 3 >> 1 # 1
  • 106.
    Assignment Operators 1. =(Assign) 2. += (Add and assign) 3. -= (Subtract and assign) 4. *= (Multiply and assign) 5. /= (Divide and assign) 6. //= (Floor divide and assign) 7. %= (Modulus and assign) 8. **= (Exponentiate and assign) 9. &= (Bitwise AND and assign) 10.|= (Bitwise OR and assign) 11.^= (Bitwise XOR and assign) 12.<<= (Bitwise Left Shift and assign) 13.>>= (Bitwise Right Shift and assign)
  • 107.
    Identity Operators Operator DescriptionExample is Returns True if both variables are the same object x is y is not Returns True if both variables are not the same object x is not y
  • 108.
    Membership Operators Operator DescriptionExample in Returns True if a sequence with the specified value is present in the object x in y 2 in [1, 2, 3] # True not in Returns True if a sequence with the specified value is not present in the object x not in y 4 not in [1, 2, 3] # True
  • 109.
  • 110.
    Conditional Statements • Inpython, the Conditional Statements are the statements that controls the execution of the program on the basis of the specified condition. • It is useful for determining whether a condition is true or not. • If the condition is true, a single or block of statement is executed. • Examples • if statement • if else statement • Nested if statement • elif else statement
  • 111.
    if statement Executes ablock of code if a specified condition is true. Syntax: if condition: # code block
  • 112.
    if statement Example age =18 if age >= 18: print("You are an adult.") Output You are an adult.
  • 113.
    elif Statement elif Shortfor "else if", it checks another condition if the previous if or elif condition is false. Syntax: if condition: # code block elif another_condition: # another code block
  • 114.
    elif Statement Example score =85 if score >= 90: print("Grade: A") elif score >= 80: print("Grade: B") Output Grade: B
  • 115.
    else statement Executes ablock of code if none of the preceding conditions are true. if condition: # code block elif another_condition: # another code block else: # code block if no conditions are true Syntax:
  • 116.
    else Statement Example score =70 if score >= 90: print("Grade: A") elif score >= 80: print("Grade: B") else: print("Grade: C") Output Grade: C
  • 117.
    Short Hand If Ifyou have only one statement to execute, you can put it on the same line as the if statement. Example: a = 200 b = 33 if a > b: print("a is greater than b") Output a is greater than b
  • 118.
    Short Hand If... Else If you have only one statement to execute, one for if, and one for else, you can put it all on the same line: Example: a = 2 b = 330 print("A") if a > b else print("B") Output B
  • 119.
    The pass Statement ifstatements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error. Example: a = 33 b = 200 if b > a: pass Output
  • 120.
  • 121.
    Python Loops Python hastwo primitive loop commands: 1. while loops 2. for loops
  • 122.
    while loops Executes ablock of code as long as a specified condition is true. while condition: # code block Syntax:
  • 123.
    while loops Example count =0 while count < 5: print(count) count += 1 Output 0 1 2 3 4
  • 124.
    The break Statement Withthe break statement we can stop the loop even if the while condition is true: Example: i = 1 while i < 6: print(i) if (i == 3): break i += 1 Output 1 2 3
  • 125.
    The continue Statement Withthe continue statement we can stop the current iteration, and continue with the next: Example: i = 0 while i < 6: i += 1 if i == 3: continue print(i) Output 1 2 3 4 5 6
  • 126.
    for loops The forloop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) and execute a block of code for each item in the sequence. It is particularly useful when you need to perform an operation on each element of a collection.
  • 127.
    for loops for: Thekeyword to start the loop. item: A variable that takes the value of the next item in the sequence on each iteration. in: The keyword used to specify the sequence to iterate over. sequence: The collection (list, tuple, string, etc.) to iterate over. # code block: The block of code to execute for each item in the sequence. for item in sequence: # code block Syntax:
  • 128.
    for loops Example 1:Iterating Over a List fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) Output apple banana cherry
  • 129.
    for loops Example 2:Iterating Over a String for letter in "Python": print(letter) Output P y t h o n
  • 130.
    for loops Example 3:Using range() Function for number in range(5): print(number) Output 0 1 2 3 4
  • 131.
    for loops Example 4:Iterating Over a Dictionary person = {"name": "Alice", "age": 25} for key in person: print(key) Output Name age
  • 132.
    for loops Example 4:Iterating Over a Dictionary person = {"name": "Alice", "age": 25} for key in person: print(value) Output Alice 25
  • 133.
    Example 5: Nestedfor Loop Example colors = ["red", "green", "blue"] objects = ["ball", "pen"] for color in colors: for obj in objects: print(color, obj) Output: red ball red pen green ball green pen blue ball blue pen