Python Programming - Unit 1
Python Programming - Unit 1
PROGRAMMING AND
Getting Started with Python PRODUCT DEVELOPMENT
Programming
© Kalasalingam academy of research and education
Course Outline
CO 1
Course description
This course teaches the core of programming
computers using Python. We deal python
CO 2
programming from basics to core. The course does
not demand any pre-requisites but knowledge of basic
mathematics. The naive computer users can be able to
master the Python. This course will touch upon
CO 3.Implement user defined python functions and build an Python data types, functions, control and looping
efficient program leveraging modules constructs, regular expressions, user interface
modules and the data analytic packages. Once a
student completes this course, they will be ready to
CO 4.Create python programs to handle file I/O and exceptions, perform core python problem solving and also
and solve problems with Object Oriented Concepts develop their own python packages. This course
covers Python 3.
Lesson 1. Unit - 1
Develop basic programs using control flow
structure
Lesson 2. Basics of
➢Understand the basic python concept
from scratch
Lesson 3. ➢Analyze the uses of various data types,
methods and control structures
➢Apply control structures to various
Lesson 4. Language components applications
Lesson 1. Introduction
Topic 2
About Python & its versions
First Lesson Outline
Topic 3 We will be learning about Computers, Program
Notable Features
translation
Topic 4
Getting Started Python and its versions
Topic 5
Interpreter Features of Python
Topic 6 Interactive mode in Python IDEs
Applications
Applications in mainstream technologies
• Interpretation
• Compilation
- immediately translates and executes the statement before processing the next one
Compilation approach
•uses a program called compiler
•reads and converts the source code of a high-level language programme into
machine-language instructions in an executable file.
•the converted machine-language instructions can be executed on the computer
when the program is launched
•examples: C and C++
•example: Java
Interpreter
Compiler
• very portable across different
computing platforms •program runs very fast after compilation
• produces results almost •smaller in code size after compilation
immediately •must compile the entire program before
execution
• easy to debug
•needs to be re-compiled if to be used on
• program executes more slowly
different computing platforms
• useful for implementing dynamic, •used in large and sophisticated software
interactive features, such as those applications when speed is of the utmost
used on web pages importance
Object Oriented
Functional
•Objects are small capsules that hold
some internal state as well as a set of •Functional programming avoids the state
method calls that allow you to modify it, changes as much as possible and works with
and programmes are made up of the data flowing between functions.
correct set of state modifications.
Version 1 (1994)
Version 2 (2000)
Fig. 3. Installation setup of Python IDLE – all default packages can be installed
• The interpreter converts Python code into bytecode, which is then executed by the Python
Virtual Machine.
•Two modes: normal and interactive.
• Normal mode: full .py files are given to the interpreter.
• Interactive mode: piecewise execution of statements by read-eval-print loop (REPL).
Some options:
-c : executes single command.
-O: use basic optimizations.
-d: debugging info.
More can be found here:
https://docs.python.org/3/using/cmd
line.html
Android: https://play.google.com/store/apps/details?id=ru.iiec.pydroid3
Iphone: https://apps.apple.com/us/app/python-ide/id1065305069
*Source: https://www.cleveroad.com/blog/python-vs-swift
Application Description
Web Application Web development frameworks
Development •Django
•Flask
Application Description
Artificial Intelligence Libraries for Machine Learning applications.
•SciPy
•Pandas
•Keras
•TensorFlow
•NumPy
Game development Libraries
•PySoy
•PyGame
Internet of Things •Raspberry Pi turns any thing into an electronic
gadget
•Creation of embedded software
Application Description
Web Scraping Selenium, PythonRequest, MechanicalSoup tools are
used for building web scraping applications
Lesson 1.
Lesson 2. Basics of
Example:
• sum
• average
• day
•case sensitive
Operations
• Once a variable is created, we can store, retrieve, or modify the value associated with the
variable name.
3.14
Name Value
x = 3.14
x 3.14
X
Case Sensitive:
Example:
a=4
a and A are
A=5 treated as
two
different
variables
Example:
a1, a2, a3 = 4,5,6
print(a1)
print(a2) a1=4
print(a3) a2=5
a3=6
Type of variables
Numeric
Note: The built in function type(variable) returns the class of the datatype.
st=“cse”
st=“CSE”
st=“Cse”
st=“100”
st‘=“Welcome CSE”
Note: The built in function type(variable) returns the class of the datatype.
x=True
z=False
print(10>12)
Prints
False
Example:
n= 6
print (n)
print(type(n)) Prints
<class ‘int’> Example:
n= 6j
print (n)
Example: print(type(n)) Prints
n= 6.5 <class ‘complex’>
print (n)
print(type(n)) Prints
<class ‘float’>
Example:
Example:
n= ”KARE”
n= True
print (n)
print (n)
print(type(n)) Prints print(type(n))
<class ‘str’> Prints
<class ‘bool’>
Example:
#initialization of variables Commented
line
a=10
b=20
Example:
print(“hi”) # It’s a comment line
print(“hello”)
No syntax for multiline comment, hence use multiline string (triple quotes)
Example:
”””
This code is
written in Python Multiline
comment
enclosed in triple
to print a message quotes
”””
print(“KARE")
output:
7
Output:
* With strings
performs
repetition
Output:
•Type conversion is the process of converting the value of one data type (integer, text, float, etc.) to another data
type.
• Python converts one data type to another automatically without user interaction
Note:
To avoid data loss, convert the lower data type (integer) to the higher data type (float).
n_int = 123
n_str = "456"
Output
TypeError: unsupported operand type(s) for +: 'int' and
'str’
TypeError
Note:
Conversion of the higher data type (String) to the lower data type (integer) is not implicit.
• The data type of an object is converted to the needed data type by users
• Predefined functions like int(), float(), str(), etc can be used to do explicit type conversion.
• Also known as typecasting as the user casts the data type of objects.
Syntax
<reqd_datatype>(expression)
Simple Output
Syntax
Simple Output
Example :
print("Python is cool.")
w=5
print(“w =", w)
sFile = open('pyth.txt', 'w')
print(‘KARE’, file = sFile)
z=w
sFile.close()
print(‘w =', w, '= z')
w=5
print(“w =", w, sep='0000', end=‘\n\n')
print(“w =", w, sep='0', end='')
Simple Input
Syntax Example
num=input('Enter a num')
input([prompt]) num1=input('Enter another num')
print(num+num1)
• The value 10 and 20 are strings, not a
number. Enter a num10
• use int() or float() functions to convert to Enter another number20
number 1020
num=input('Enter a num')
• Here, we converted both num and num1 to num1=input('Enter another number')
integer and the result we get is integer print(int(num)+int(num1))
Enter a num10
Enter another number20
30
Simple Input
• eval()
It evaluates the expression given as a string and returns integer
Example
print(math.pi)
❑ Python supports various types of Operators including Arithmetic, Boolean, Repetition, among others
❑ Data types of variables are updated based on the operations performed on the variables.
❑ Python supports type conversion at any level. type() is used to check type of the variable
❑ datatype(var) can convert the variable var to the corresponding datatype. Eg. int(3.5) = 3 (Converting
floating point data to integer data)
❑ Simple input and output staements
Lesson 1.
Lesson 2. Basics of
Topic 2
Indexing and Slicing Strings Third Lesson Outline
Topic 3
Operators in Strings
We will be learning about strings
Topic 4
Formatting Operators Strings methods for various formatting options
Operators in Strings
•Enclosed by single quotes or double quotes or triple quotes (only for multiline string)
• Example: ‘KARE’ or “KARE”
• The ASCII or Unicode character is used to encode each character. As a result, Python strings can also be referred
to as a list of Unicode characters.
• The character data-type is not supported in Python; rather, a character written as 'w' is a string of length 1.
• Example:
st=“KARE”
• Single quotes
• Example:
st = 'Hello'
print(st)
Prints Hello
• Double quotes
•Example:
st = ”Hello”
print(st)
Prints Hello
• Triple quotes
•Example:
st = ”””Hello
World
KARE”””
print(st)
Prints Hello
World
KARE
st=“KARE”
K A R E
0 1 2 3
Indices
st[0]=‘K’
st[1]=‘A’
st[2]=‘R’
st[3]=‘E’
st=“KARE”
K A R E
0 1 2 3
print(st[0])
print(st[1])
print(st[2])
print(st[3])
IndexError: string
print(st[4]) index out of range
To get to the individual characters in a string, use the slice operator []. However, we can get the substring of the given string
by using the : (colon) operator.
st=‘KARE’
K A R E
0 1 2 3
st[:]= ‘KARE’
st[0:]=‘KARE’
st[:4]=‘KARE’
st[:2]=‘KA’
st[0:3]=‘KAR’
st[1:3]=‘AR’
st=‘KARE’
K A R E
0 1 2 3
st[1:3]=‘AR’
K A R E
-4 -3 -2 -1
st[-1]=‘E’
st[-2]=‘R’
st[-3:-1]=‘AR’
K A R E
-4 -3 -2 -1
It prints ERAK
print(st[::-1]
As strings are immutable, the characters cannot be deleted from the string. However, the entire string can
be deleted using the del keyword.
Example:
st = “KARE"
del st[1]
TypeError: 'st' object
doesn't support item
deletion
del st
print(st)
NameError: name 'st'
is not defined
• The + and * operators are applied to both numeric operands and strings
+ operator – Concatenation of Strings
Example:
>>> s = ‘cse'
>>> t = ‘ece'
>>> u = ‘eee'
>>> s + t
‘cseece'
>>> s + t + u
‘cseeceeee'
in operator – If the provided string is contained within another string, it returns True; otherwise, it returns
False.
Example:
>>> s = ‘cse'
>>> s in ‘An Engineering department comprises of cse '
True
>>> s in ‘An Engineering department comprises of ece'
False
not in operator – returns True if the given string is not contained within another string, and False otherwise:
Example:
>>> s = ‘cse'
>>> s not in ‘An Engineering department comprises of cse '
False
>>> s not in ‘An Engineering department comprises of ece'
True
capitalize()
Example:
st = ”cse”
x = st.capitalize()
Prints CSE
print (x)
casefold()
Example:
st = ”CSE”
x = st.casefold()
Prints cse
print (x)
startswith()
Example:
st = ”hi CSE”
x = st.startswith(“hi”)
Prints True
print (x)
endswith()
Example:
st = ”hi CSE”
x = st.endswith(“CSE”)
Prints True
print (x)
find()
Example:
st = ”hi CSE”
x = st.find(“CSE”)
Prints position 3
print (x)
replace()
Example:
st = ”hi CSE”
x = st.replace(“CSE”, “ECE”)
Prints hi ECE
print (x)
index()
Example:
st = ”hi CSE”
x = st.index(“CSE”)
Prints 3
print (x)
islower()
Example:
st = ”CSE”
x = st.islower()
Prints False
print (x)
isupper()
Example:
st = ”CSE”
x = st.isupper()
Prints True
print (x)
upper()
Example:
st = ”cse”
x = st.upper()
Prints CSE
print (x)
lower()
Example:
st = ”CSE”
x = st.lower()
Prints cse
print (x)
isaplpha()
Example:
st = ”CSE”
x = st.isalpha()
Prints True
print (x)
isdigit()
Example:
st = ”555”
x = st.isdigit()
Prints True
print (x)
split()
Example:
st = ”welcome to KARE”
x = st.split()
Prints
print (x) [‘welcome’,’to’,’KARE’]
join()
Example:
tu= (“CSE”,”ECE”,”EEE”)
x = “$”.join(tu)
Prints
print (x) CSE$ECE$EEE
count()
Example:
st= ”I like books, books are my friends”
x = st.count(“books”)
Prints
print (x) 2
format()
Example:
st =”The book is {price: .2f} rupees”
Prints
The book is 200.00 rupees
print(st.format(price=200))
strip()
Example 1:
st =” Diya ”
z=st.strip()
Prints
print(“of all friends”, z, “is my best friend”) of all friends Diya is my best friend
strip()
Example 2:
st =”,,,,…..Diya…..ohhhh”
z=st.strip(“,.oh”)
Prints
print(z) Diya
Example:
st =”I like \“science\” books” Prints
print(st) I like science books
• Generate a string which is made of the first 3 and the last 3 characters from a given string.
•Code:
st=“welcomecse”
if len(st) < 3:
print (‘’)
print (st[0:3] + st[-3:]) prints
welcse
Lesson 1.
Lesson 2. Basics of
Topic 2
Relational Operators
Topic 3
Logical Operators
Topic 4
Bitwise Operators
Topic 5
if Statements
Topic 6
for Statement
Topic 7
break and continue Statements
Fourth Lesson Outline
Topic 8
pass Statement
We will be learning about the operators and control
flow tools in Python
if 3 > 1:
print(“Three is greater than one")
No Indentation
raises syntax
error
•Equals:
•Not Equals:
•Less than:
•Greater than:
returns True
Example: because 7 is
w1 = 7 greater than 3
w2 = 3
print(w1 > w2)
returns True
Example: because 7 is
w1 = 7 greater than or
w2 = 3 equal to 3
•and
returns True
because 7 is greater
than 2 AND 7 is less
Example: than 12
a=7
print(a > 2 and a < 12)
Example:
a=7
print(not(a > 4 and a < 12))
•and - &
Example:
x = 60 # 60 = 0011 1100
y = 13 # 13 = 0000 1101
z=0 value of z is
12
z = x & y; # 12 = 0000 1100
print ("Value of z is ", z)
•or - |
Example:
x = 60 # 60 = 0011 1100
y = 13 # 13 = 0000 1101
z=0
value of z is 61
z = x | y; # 61 = 0011 1101
print ("Value of z is ", z)
•not - ~
•It is unary and is inverting all the bits
Example:
x = 60 # 60 = 0011 1100
z=0
value of z is
195
z = ~x ; # 195 = 1100 0011
print ("Value of z is ", z)
•XOR - ^
• If just one of two bits is 1, sets each bit to 1.
Example:
x = 60 # 60 = 0011 1100
y = 13 # 13 = 0000 1101
z=0 value of z is 49
z = x ^ y; # 49 = 0011 0001
print ("Value of z is ", z)
•So far, you've only seen sequential execution, which means that statements are always executed one after the
other, in the exact order defined.
•However, life is frequently more complex than that.
•A program will often need to skip over certain statements, repeat a series of statements, or select between two
sets of statements to execute.
•Control structures play a role in this.
•The order in which statements in a program are executed is guided by a control structure.
•Python supports
• if
• if…else
• elif ladder
• nested if
•In reality, we often must analyse information and then select one of two courses of action:
“If the weather is nice, then I’ll go for picnic. (It’s implied that if the weather isn’t nice, then I won’t go for picnic.)”
•Syntax
if <expre>:
<statement>
•Example
w1=4 It executes print
statement as the
w2=5 value of w1 is less
than w2
if w1<w2:
print(“w1 is less than w2”)
•Example
w1=6 It will not execute
print statement as the
w2=5 value of w1 is not less
than w2
if w1<w2: It will skip to this
statement and execute
print(“w1 is less than w2”) it if <expr> evaluates
to false
print(“hi”)
•To evaluate a condition and if it's true take one direction, but another direction if it's false.
•An else clause is used to do this
•Syntax
if <expre>:
<stmt(s)>
else:
<stmt(s)>
•Example
w1=5
w2=4 It executes print
statement in else
if w1<w2: block as the value
of w1 is not less
print(“w1 is less than w2”) than w2
else
print(“w2 is less than w1”)
Syntax: outer if
if (condition1):
# executes statements when condition1 is true
if (condition2): inner if
•Example
>>> age = 50
>>> s = ‘junior' if age < 25 else ‘senior'
>>> s
‘senior'
•Example
•Example
if x > y:
z = x if x > y else y
z=x equivalent
else:
z=y
•The while loop iterates over a code block as long as the test expression is true.
•When it’s not sure how many times we'll iterate ahead of time, we'll use this loop.
•Syntax
while expr:
body of while
Initialization
•Example 1
Test
expression
ind = 1
while ind <= 10:
print("The value of ind is", i)
ind = ind+1
Update
counter
•Example 2
ind = 1
while ind < 6:
print(ind)
ind += 1
Prints
1,2,3,4,5
•In the while loop, any non-zero value denotes an always-true condition, while zero denotes an always-
false condition
Example
while (1):
print(”KARE”)
Prints KARE
infinitely
When the test condition is no longer true, the else statement is used to run a code block once.
Example:
ind = 0
while ind < 5:
print(ind) Prints
0
ind += 1 1
2
else: 3
4
i is not less than 5
print("ind is not less than 5")
•Example
total = 0
while (total == 0): print("Hello KARE")
‘in’ is the
Syntax: membership
operator
for value in sequence:
Body of for block
In a for loop, the else keyword specifies a code block that will be executed when the loop is completed.
Example:
For w in range(3):
Prints
print(w) 0
else: 1
2
print(“done") done
If the loop is terminated by a break statement, the else block will not be executed.
Example:
for x in range(5): Prints
if x==4: break 0
1
2
print(x) 3
else:
print(“done")
•Nested means presence of one for loop within another for loop
Syntax:
for v1 in seq: #outer for loop
for v2 in seq: #inner for loop
#block of code
#following statements
Example:
lt1 = [1, 2, 3]
lt2 = [4, 5, 6]
For w1 in lt1:
14
for w2 in lt2: 15
16
print(w1, w2) 24
25
26
34
35
36
•Example:
Output:
The built-in function range() is used to iterate over a sequence of numbers. It returns a sequence of
numbers that starts at 0 and increments by 1 (by default) and stops before a specified number.
Example:
Generate a sequence of numbers from 0 to 6:
n = range(7)
for x1 in n:
print(x1) Prints
0,1,2,3,4,5,6
Example:
Generate a sequence of numbers from 2 to 6:
n = range(3, 6)
for x1 in n:
print(x1) Prints 2,3,4,5
Example:
Generate a sequence of numbers from 2 to 8,
increment by 2:
n = range(2, 9,2)
for x1 in n: Prints 2,4,6,8
print(x1)
Example:
Generate a sequence of numbers from 5 to 1,
decrement by 1:
n = range(5, 0,-1)
for x1 in n: Prints 5,4,3,2,1
print(x1)
Example:
Generate a sequence of numbers from -1 to -5,
decrement by 1:
n = range(-1, -6,-1)
for x1 in n: Prints -1,-2,-3,-4,-5
print(x1)
Example: Output:
numb = int(input("Enter the number ")) Enter the number 5
for w in range(1,6): 5*1=5
m = numb*w 5 * 2 = 10
print(numb,"*",i,"=“,m) 5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
Output:
Accessing all
elements of list
•Break •Continue
o Breaks the loop o Skips the remaining code
inside a loop for the current
oProgram control flows to the iteration only.
statement immediately after the
body of the loop. o The loop does not end, but
instead continues with the next
iteration.
Example:
for x1 in “KARECSE":
if x1 == “C":
Prints
break K
A
R
print(x1) E
Example:
for x1 in “KARECSE":
Prints
if x1 == “C": K
A
continue R
E
print(x1) S
E
Output
The continue statement continues with the next iteration of the loop, skipping the current iteration:
Output
Continue: skip
current iteration
•Syntax
pass
•Example:
seq = {‘k', 'a', ‘r', ‘e'}
for x in seq:
Does nothing
pass