Python Programming
Dr D R Srinivas
Associate Professor in ECE
G.Pulla Reddy Engineering College(Autonomous)
Kurnool
Why we need to learn Programming
Languages ?
• Programming is using a language that a
machine can understand in order to get it to
perform various tasks.
• Computer programming is how we
communicate with machines in a way that
makes them function how we need.
Why Python?
Python Programming Introduction
• Python
• Guido Van Rossam in 1989
• Programming features from
– Procedural Programming Features from C
– Object Oriented Programming Features from C++
– Scripting Language Features from Perl and Shell
Script
– Modular Programming Features from Modula-3
Introduction to Python
Python is a high-level, interpreted, interactive and object-oriented
scripting language. It is designed to be highly readable.
Python is Interpreted: Python is processed at runtime by the
interpreter. You do not need to compile your program before
executing it .
Python is Interactive: You can actually sit at a Python prompt and
interact with the interpreter directly to write your programs.
Python is Object-Oriented: Python supports Object-Oriented style
or technique of programming that encapsulates code within
objects.
Python is a Beginner's Language: Python is a great language for
the beginner-level programmers and supports the development of a
wide range of applications from simple text processing to WWW
browsers
11/13/2021 to games. 5
Where?
Automation Applications
Data Analytics & Visualization
Scientific Applications
Web Applications
Web Scrapping
Administration Script
Networking with IOT Applications
Test Cases
GUI Applications
Gaming Applications
11/13/2021
Animation Applications 6
Features
Simple & Easy to Learn
Free and Open Source
High Level
Dynamically typed
Cross Platform Compatibility (platform independent)
Portable,
Object Oriented
Interpreted
Extendable
Embedded
Extensive Standard Library
Interactive Mode
Databases and GUI Programming
Scalable
11/13/2021
Automatic Garbage Collection 7
A simple language which is easier to learn
Python has a very simple and elegant syntax. It's much easier to read
and write when compared to other languages like: C++, Java, C#.
Free and open-source
You can freely use and distribute Python, even for commercial use. Not
only can you use and distribute software's written in it, you can even
make changes to the Python's source code.
Portability
You can move Python programs from one platform to another, and run it
without any changes. It runs seamlessly on almost all platforms
including Windows, Mac OS X and Linux.
Extensible and Embeddable
Suppose an application requires high performance. You can easily
combine pieces of C/C++ or other languages with Python code. This will
give your application high performance as well as scripting capabilities
which other languages may not provide out of the box.
11/13/2021 8
A high-level, interpreted language
Unlike C/C++, you don't have to worry about difficult tasks like
memory management, garbage collection and so on. Likewise, when
you run Python code, it automatically converts your code to the
language your computer understands. You don't need to worry about
any lower-level operations.
Large standard libraries to solve common tasks
Python has a number of standard libraries which makes life of a
programmer much easier since you don't have to write all the code
yourself.
Object-oriented
Everything in Python is an object. Object oriented programming
(OOP) helps you solve a complex problem very easily With OOP, you
are able to divide these complex problems into smaller sets by
creating objects.
11/13/2021 9
Limitations
• Interpreted
• Mobile APP
• Performance wise slower
Python Installation
Go to windows search and type control panel
Visit - python.org
Download for windows
Based on your system type download either 32 bit or
64 bit installation …
Put tick mark on two check boxes and click on install
now
Go to cmd prompt in windows machine and then type “py” to
check the installation is complete or not
Difference Between Python & Other
Languages
class HelloWorld {
public static void main(String[] args) {
Java
System.out.println("Hello,
Everyone!");
}
}
#include <iostream>
using namespace std;
C++ int main() {
cout << "Hello, Everyone!" << endl;
return 0;
}
print(“Hello, Everyone!”) Python
Python Compiled or Interpreted ?
Working with Python Basic Syntax
There are two ways to use the Python interpreter:
1. Interactive Mode / shell mode (line by line execution)
In shell mode, you type Python expressions into the Python
shell, and the interpreter immediately shows the result.
>>> 2 + 3
5
>>>
The >>> is called the Python prompt.
2. Batch Mode (entire program execution at a time)
The concept of writing group of python statements into a file,
saving that file with the extension ‘.py’ and submitting the entire file
to the python interpreter at a time is known as Batch mode.
11/13/2021 21
Python Keywords
Python has a set of keywords that are reserved words that cannot be
used as variable names, function names, or any other identifiers
There are Thirty Five Key Words in Python
Value Keywords: True, False, None.
Operator Keywords: and, or, not, in, is.
Control Flow Keywords: if, elif, else.
Iteration Keywords: for, while, break, continue.
Structure Keywords: def, class, with, as, pass, lambda, global.
.
Returning Keywords: return, yield.
Import Keywords: import, from, del, try, except, finally, raise, assert, async,
await, nonlocal.
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
Python Comments
• Comments can be used to explain Python
code.
• Comments can be used to make the code more
readable.
• Comments can be used to prevent execution
when testing code.
Creating a Comment
Comments starts with a #, and Python will ignore
them:
Example:
1. #This is a comment
print("Hello, World!")
2.print("Hello, World!") #This is a comment
3.#print("Hello, World!")
print("Cheers, Mate!")
Multi Line Comments
• Python does not really have a syntax for multi line
comments.
• To add a multiline comment you could insert
a # for each line:
Example:
1. #This is a comment
#written in
#more than just one line
print("Hello, World!")
2. """
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Python Variables
Variables
Variables are 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.
Example
x=5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any
particular type, and can even change type after
they have been set.
Example
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Get the Type of the Variable
You can get the data type of a variable with
the type() function.
Example
x=5
y = "John"
print(type(x))
print(type(y))
Single or Double Quotes?
String variables can be declared either by using
single or double quotes:
Example
x = "John"
# is the same as
x = 'John‘
Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a=4
A = "Sally"
#A will not overwrite a
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)
Example
Legal variable names:
myvar = "John“
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Example
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
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"
Python Variables - Assign Multiple
Values
Python allows you to assign values to multiple
variables in one line
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
One Value to Multiple Variables
• You can assign the same value to multiple
variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Unpack a Collection
• If you have a collection of values in a list, tuple etc.
Python allows you extract the values into variables.
This is called unpacking.
Example
Unpack a list:
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
Python - Output Variables
Output Variables
The Python print statement is often used to
output variables.
• To combine both text and a variable, Python uses
the + character:
Example
x = "awesome"
print("Python is " + x)
You can also use the + character to add a variable to
another variable:
Example
x = "Python is "
y = "awesome"
z= x+y
print(z)
For numbers, the + character works as a mathematical
operator:
Example
x=5
y = 10
print(x + y)
If you try to combine a string and a number,
Python will give you an error:
Example
x=5
y = "John"
print(x + y)
Indentation
Python is a procedural language. The indentation
error can occur when the spaces or tabs are not
placed properly.
There will not be an issue if the interpreter does
not find any issues with the spaces or tabs. If
there is an error due to indentation, it will come
in between the execution and can be a show
stopper.
Python Numbers
There are three numeric types in Python:
int
float
complex
Example x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(z))
Type Conversion
Convert from one type to another:
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))
Random Number
Python does not have a random() function to make
a random number, but Python has a built-in module
called random that can be used to make random
numbers:
Example
Import the random module, and display a random
number between 1 and 99:
import random
print(random.randrange(1, 100))
Strings
Strings are sequence of Characters, using the
syntax of either single quotes or double quotes
‘hello’
“ hello”
Because strings are ordered sequences it means
we can use indexing and Slicing to grab the
subsection of the string
Indexing notation uses [] notation after the string
(or variable assigned the string)
Indexing allows you to grab a single character from
the string
These actions use [] square brackets and a number
index to indicate positions of what you wish to grab
Character: h e l l o
Index: 0 1 2 3 4
Reverse Index : 0 -4 -3 -2 -1
Slicing allows you to grab a subsection of multiple
characters , a “slice” of the string.
This has the following syntax
[start:stop:step]
Start is a numerical index for the slice start
Stop is the index you will go up to (but not include)
Step is the size of the “jump” you take
Python Data Types
Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and
different types can do different things.
Python has the following data types built-in by default,
in these categories:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
Getting the Data Type
You can get the data type of any object by using
the type() function
Example
Print the data type of the variable x:
x=5
print(type(x))
Setting the Data Type
x = "Hello World”
x = 20
x = 20.5 Use print (type(x))
x = 1j
x = ["apple", "banana", "cherry“]
x = ("apple", "banana", "cherry“)
x = range(6)
x = {"name" : "John", "age" : 36}
x = {"apple", "banana", "cherry“}
x = frozenset({"apple", "banana", "cherry"})
x = True
x = b"Hello”
x = bytearray(5)
x = memoryview(bytes(5))
Setting the Specific Data Type
x = str("Hello World”)
x = int(20)
x =float(20.5) Use print (type(x))
x = complex(1j)
x =list(("apple", "banana", "cherry“))
x =tuple(("apple", "banana", "cherry“))
x = range(6)
x = dict(name : "John", age : 36)
x = set(("apple", "banana", "cherry“))
x = frozenset(("apple", "banana", "cherry”))
x = bool(5)
x = bytes(5)
x = bytearray(5)
x = memoryview(bytes(5))
Python Operators
• Arithmetic Operators
• Comparison (Relational) operators
• Logical Operators
• Bitwise operators
• Assignment operators
• Identity Operators
• Membership Operators
Arithmetic Operators
Example
a = 10
b=4
print(‘a+b = ’, a+b)
print(‘a-b = ’, a-b)
print(‘a*b = ’, a*b)
print(‘a/b = ’, a/b)
print(‘a%b = ’, a%b)
print(‘a//b = ’, a//b)
print(‘a**b = ’, a**b)
Comparison operators
To compare the values of two operands,we can use
the comparison operators.
The result of these operators is either true or false
i.e. a boolean value
Example
a = 10;
b = 4;
print('a>b is ', a>b)
print('a<b is ‘, a<b)
print('a==b is ', a==b)
print('a!=b is ', a!=b)
print('a>=b is ', a>=b)
print('a<=b is ', a<=b)
Logical Operators
Bitwise Operators
Bitwise operators are used to compare (binary) numbers
Ex:
Let x = 10 (0000 1010 in binary)
y=4 (0000 0100 in binary)
Bitwise AND x&y=0 (0000 0000)
Bitwise OR x | y = 14 (0000 1110)
Bitwise NOT ~x = -11 (1111 0101)
Bitwise XOR x ^ y = 14 (0000 1110)
Bitwise right shift x >> 2 = 2 (0000 0010)
Bitwise left shift x << 2 = 40 (0010 1000)
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. Two variables
that are equal does not imply that they are identical.
is True if the operands are identical (refer to the
same object) Ex : x is True
is not True if the operands are not identical (do not
refer to the same object) Ex :x is not True
Example : Identity operators in Python
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
Output
print(x1 is not y1) False
print(x2 is y2) True
print(x3 is y3) False
Here, we see that x1 and y1 are integers of the
same values, so they are equal as well as identical.
Same is the case with x2 and y2 (strings)
But x3 and y3 are lists. They are equal but not
identical. It is because the interpreter locates
them separately in memory although they are
equal.
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).
in True if value/variable is found in the
sequence
not in True if value/variable is not found in the
sequence
Example : Membership operators in Python
x = 'Hello world'
y = {1:'a',2:'b'}
print('H' in x) # Output: True
print('hello' not in x) # Output: True
print(1 in y) # Output: True
print('a' in y) # Output: False
Here, 'H' is in x
but 'hello' is not present in x (remember, Python
is case sensitive).
Similarly, 1 is key and 'a' is the value in
dictionary y.
Hence, 'a' in y returns False.
Assignment operators
Assignment operators are used in Python to
assign values to variables.
a = 5 is a simple assignment operator that assigns
the value 5 on the right to the variable a on the
left.
Operator Example Equivalent to
= x =5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x–5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x=x&5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5