0% found this document useful (0 votes)
3 views

lec 18,19

The document outlines a course on Python programming, detailing its history, basic concepts, and practical applications. It covers fundamental programming principles, data types, operators, control structures, and functions, along with exercises for practice. The course aims to equip students with skills to solve real-world problems using Python.

Uploaded by

headecs.gnit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

lec 18,19

The document outlines a course on Python programming, detailing its history, basic concepts, and practical applications. It covers fundamental programming principles, data types, operators, control structures, and functions, along with exercises for practice. The course aims to equip students with skills to solve real-world problems using Python.

Uploaded by

headecs.gnit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Course Name: Internet of Things and its Applications

Course Code: ECS503


Contact:3:0:0
Credits: 3,
Contact Hours:36

Lecture No.: 18,19


Topic: Python Pro9gramming
By: Ms. Bapita Roy, H.O.D.,ECS, GNIT
WELCOME TO
PYTHON
PROGRAMMING
WHAT IS PROGRAMMING
✓Logical set of instructions carried
out to complete a certain task
✓Can be executed either manually
or in an automated manner
WHY SHOULD WE
LEARN
PROGRAMMING?
✓ Reduce time and manual effort in
performing tasks
✓Accomplish objectives in a more
efficient way
✓Help build applications to solve
some of the real-world problems
✓Create a logical mindset that tries to
answer : “How do I solve problems?”
HISTORY OF PYTHON
✓Created: 1991
✓Creator : Guido van Rossum
✓Inspiration for the name : TV
show “Monty Python’s Flying
Circus”
WHAT IS PYTHON ?
✓Interpreted, general-purpose programming
language

✓Can run/interface with almost any system or


platform

✓Supports Procedural as well as Object-


oriented style of programming (like Java)
PRE-REQUISITES
✓ Download and install python on Desktop or Laptop.
Latest version (3.9.5) available in the following link :

https://www.python.org/downloads/

✓ Online site for practising python code :

https://www.w3schools.com/python/
FIRST PYTHON CODE

print(“Hello World !”)

Output : Hello World


print STATEMENT
✓Displays content that is enclosed within its
parenthesis
eg. print(2, ‘I am Legend’)
✓Supports use of both single and double-quotes
print(2, "I am Legend")
✓Can display the value of any expression
(strings, integers, float, Boolean, etc)
eg. print(True)
ARITHMETIC OPERATORS
 Can be used to perform basic mathematical calculations

 List of Operators :
i. Add : + (eg. 2+3=5)
ii. Subtract : - (eg. 5-3=2)
iii. Multiply : * (eg. 5*3=15)
iv. Divide : / (floating-point division, eg. 10/2=5.0) , //
(integer division, eg. 10//2 = 5)
v. Exponential : ** (eg. 2**3 = 8)
vi. Modulus : % (eg. 5%2 =1) (gets the remainder)
DATA TYPES
• 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
VARIABLES
 Variable is a small space allocated in memory for storing
some value (including NULL’s or no value)
 Variable names :
i. can be as long as you like
ii. must start with a letter or underscore (‘_’)
iii. can contain any combination of letters, number and
underscore
iv. cannot contain reserved words (keywords)
v. are case-sensitive
Eg. _aprateem, aprateem_roy, _aroy53____ (correct)
+sgfafgbef , 42dfgef_avav , for (incorrect)
PYTHON KEYWORDS
False ,class ,finally, is, return
None, continue, for, lambda, try
True, def, from, nonlocal, while
and, del, global, not, with
as, elif, if, or, yield
assert, else, import, pass
break, except, in, raise
EXERCISE
Which of the following is/are correct variable name(s)?

a) +bapt456
b) _bapita456
c) 456bap_
d) Bp_53_ROY
e) class
STATEMENTS & EXPRESSIONS
Statements are a unit of code that primarily :
✓ Allocate some value to a variable (Assignment)
(eg. a=5 , b=‘This is Python !’ , c = 15.345)
✓ Display some output
(eg. print(a) , print(a+c), print(b,c))

Expressions are :
✓ combination of variables, values and operators
✓ can be a variable or a literal(i.e. constant, eg. 5, ‘Hi’) by
itself (eg. print(‘This is Python !’), print(5))
ORDER OF MATHEMATICAL
OPERATIONS
P = Parentheses
E = Exponentiation
M = Multiplication
D = Division
A = Addition
S = Subtraction

NOTE : Operators with same precedence are evaluated


from left to right
STRING OPERATORS

✓ Joining two strings (or concatenation) : +

Eg. a= ‘Hi’ , b=‘there’, print(a+b)


Hithere

✓ Repetition of strings : *

Eg. print(‘Hi’*2)
HiHi
IMPORTANT POINTS

✓Operations can be performed only between


similar data types
✓You can concatenate two strings, perform
mathematical operations between two
numeric values.
✓You cannot concatenate a string with a
number or perform mathematical
operations with them
EXERCISE
A= 25 , B= 50 , C =‘This is Fun !’

• A+B = ?
• B/A = ?
• B//A = ?
• C+A = ?
• C*3 = ?
• A*2+(B-5) = ?
• A+C-B = ?
SCRIPT
✓ A program file containing statements or lines of code in a certain
order

✓ A script can contain statements, expressions, variables, literals,


functions and all kinds of data types and data structures supported in
python

✓ To execute a script , please save the lines of code into a file (eg.
sum.py) and type the following in the command prompt :

python sum.py [calling method : python <script>]

NOTE :
❖ every python script must have an extension of ‘.py’
❖ the ‘python’ keyword tells the OS to execute a python script
FIRST PYTHON SCRIPT
✓ Write a script that prints your name in the following manner :
My name is <yourname>
Eg. My name is bapita

✓ Save it as : <yourname>.py
(eg. My script name : bapita.py)

✓ Execute the script at the command prompt :


python bapita.py

✓ Output should look something like :


My name is bapita
FUNCTIONS
✓ Named sequence of statements that perform a task
✓ Are of the form : <func_name>(argument) [eg. type(42)]
✓ Any expression or variable inside the parenthesis is called an
argument
✓ It may have from none to any number of arguments
✓ It may return from none to any number of values
✓ In case we need to return a value after calling a function , we use
the return keyword

✓ They can be called as part of an expression, within another


function and/or as an argument to another function
✓ (eg. 5 + int(42.56), print(type(42)))

✓ We have two types of functions :


i. Built-in (eg. print(), type(), int())
ii. User-defined (created using the def keyword)
keyword that tells
python that this is a
user-defined function Function name Argument

def display_name(my_name) :
statement .. Lines of code
statement ..
return <value>

Keyword that tells python that Return value


some value needs to be
returned (including None)
CREATE AND CALL A FUNCTION
function.py =>
def display_name():
print(“Bapita”)
display_name()

a=‘Bapita’
display_name(a)

python function.py
CONDITIONAL EXECUTION
(if STATEMENT)
✓ Based on a Boolean expression (that evaluates to either
True or False) certain statements may or may not get
executed

✓ We use relational and logical operators to create such


expressions

✓ Syntax : (elif and else blocks are optional)


if exp 1 :
execute statements Executed if exp1 is True
elif exp2 :
execute statements Executed if exp2 is True
else :
execute statements Executed if False
COMMENTS & INDENTATIONS
✓ Comments help improve readability of a code/script (‘#’ ,
everything after this character is not executed as part of the
code/script)
Eg. count=0 # initialise a count variable

✓ Multi-line comment (using a pair of triple quotes (‘’’))


Helps write comments that span more than a line

✓ Indentation : to shift lines of code by 4 spaces (or a single


tab) from the left
i. Denotes where a function definition or an if block
starts/ends
ii. De-indentation means that any line of code written
thereafter is not part of the previous block of code
RELATIONAL OPERATORS
➢ == (whether two operands are equal) (eg. a==2)
➢ != (whether two operands are not equal) (eg. a!=2)
➢ >= (whether 1st operand is greater or equal to 2nd
operand) (eg. a >=2)
➢ <= (whether 1st operand is lesser or equal to 2nd
operand) (eg. a<=2)
➢ > (whether 1st operand is greater than 2nd operand)
(eg. a>2)

➢ < (whether 1st operand is less than 2nd operand)


(eg. a<2)
LOGICAL OPERATORS

➢ and (whether two boolean expressions are True)


(eg. a>2 and a<10 )

➢ or (whether any of the two boolean expressions are


True)
(eg. a<2 or a> 10)

➢ not (negates the Boolean expression)


[eg. not (a==2) : will be True if a is not equal 2 and False
if a is equal to 2]
TYPES OF CONDITIONAL
STRUCTURES
➢ Conditional : (only one possibility)
if (exp) :
statement(s)

➢ Alternative : (only two possibilities)


if (exp) :
statement1
else :
statement2

➢ Chained : (more than two possibilities)


if (exp1) : statement1
elif (exp2) : statement2
else : statement3
EXERCISE
1. Write a script to print your name if your age is greater than 18

2. Write a script to print your name if your age is greater than or


equal to 18 . Else, it should print the following line : ‘You are
not an adult’

3. Write a script that prints your name if you are over 18 years of
age. If you are not over 18, it checks the following :
if age less than 8 => ‘Toddler’
If age between 9 and 12 => ‘Infant’
If age between 13 and 17 => ‘Adolescent’
GETTING INPUTS FROM USER

input keyword helps python get some value/data from


the user

Eg. :
name=input()
age=input(‘Enter your age please - ’)
last_name=input(‘Enter your age please - \n’)

[Repeat the previous three exercises by giving an input


to the script]
LOOPS
➢ For executing a certain set of statements repeatedly.
➢ It can be for a fixed number of times (for loop)
for n in range(4) :
execute statement(s)

OR
➢ till a boolean expression becomes False (while loop)
while (bool exp) :
execute statement(s)
INFINITE LOOPS
➢ Which run forever until the system crashes because it
runs out of memory for processing further data
➢ Should be avoided at all costs by carefully constructing
boolean expressions
➢ Can be stopped using break command
eg. i=1
while True:
print(i)
i=i+1
if i >10 : break
➢ For skipping iterations , use continue command
WORKING WITH STRINGS
➢ A sequence of characters
➢ Access any character by its position in the string(called
index)
eg. fruit = ‘banana’
print(fruit[1])
Output : ‘a’ (WHY ?)

➢ In python, everything is zero indexed i.e. left-most position


is denoted as 0 (not 1 )
➢ Index value must be an integer
➢ A negative index indicates that it starts searching from the
right
SOME STRING FUNCTIONS
✓ len : captures length of a string
eg. len(‘banana’) => 6

✓ string[n:m] : Slicing a string i.e. to extract parts of a


string, i.e. it starts from the nth position upto but not
including the mth character
eg. s=‘Monty Python’
print(s[0:5]) => Monty

✓ find : finding character position in a string


eg. ‘banana’.find(‘na’) => 2
STRING COMPARISON

➢ Use relational operator ‘==’ to check if two strings are


exactly the same
➢ With other relational operators ( like < , > ) , it helps to
sort them in alphabetical order.

➢ NOTE : All upper case letters would be lesser than all


lowercase letters
eg. Apple < apple (here ‘A’ is being compared with ‘a’,
irrespective of the length of either string)
LISTS
➢ Python data structure that contains a list of values/objects.
eg. a=[‘aprateem’, ‘aniruddha’, ‘anirban’] (list of names)

➢ All items need not be of the same data type


eg. a=[‘aprateem’, 45,[3,4], 45.34235]

➢ They are mutable i.e. can be changed , unlike strings that


are immutable
eg. a=[2,4,5]
a[0] = ‘banana’
print(a) => [‘banana’,4,5]

➢ Lists are zero-indexed , as we saw for strings

➢ Empty list : [] , contains no items ; can be initialised with


the list() keyword
LIST OPERATIONS & METHODS
➢ Use for loop to go through a list
eg. a=[2,4,5]
for i in a:
print(i)
➢ len(a) : number of elements in the list
➢ List slicing : a[:2] => [2,4]
➢ List concatenation : using ‘+’ operator
➢ List repetition : using ‘*’ operator
➢ append : adds an element at the end of a list
➢ extend : adds another list at the end of a list
➢ sort : arranges list elements in ascending order
LIST OPERATIONS &METHODS(Contd)
➢ sum(list) : add the elements of a list (only if all are
numeric)
➢ a.pop(1) : removes the 2nd element from a list
➢ del a[1] : removes the 2nd element from a list

NOTE : if no index is specified, then it removes the last


element of the list
➢ remove(2) : removes the element 2 from the list
➢ del a[:2] : removes multiple elements from a list
starting from first position and upto 2nd position
EXTRAS
✓ Convert a string to a list :
i. list(‘banana’) => [‘b’, ‘a’, ‘n’, ‘a’, ‘n’, ‘a’,]
ii. ‘I am a banana’.split(‘ ‘) => [‘I’, ‘am’, ‘a’, ‘banana’]

✓ Combine elements of a list into a string :


‘ ‘.join([‘I’, ‘am’, ‘a’, ‘banana’]) => ‘I am a banana’

The first character before the join is called delimiter (or


separator). If we specify it as empty(‘’) then the string
will have no space in between words
THANK
YOU

You might also like