RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING

AsifIqbal109 32 views 126 slides Aug 28, 2024
Slide 1
Slide 1 of 126
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126

About This Presentation

RaspberryPI PPT WITH ALL THE DETAILS OF PROGRAMMING


Slide Content

Inventor Of Raspberry Pi
•Eben Christopher Upton 
(born 5 April 1978) is a
British technical director and
 
ASIC architect 
for 
Broadcom.
•He is also a founder of
 
Raspberry Pi Foundation,
and now CEO of Raspberry Pi (Trading) Ltd.
•He is also responsible for the overall
 
software
 
and 
hardware architecture 
of the 
Raspberry Pi
 
device

GPIO - Header

Raspberry PI 3 GPIO Header

Hardware Required
•A
 
monitor 
with the correct cable and adapter.
•A micro USB
 
power supply/USB C-type Power
port.
•A wired
 
keyboard 
and 
mouse, or a
wireless
 
keyboard 
and 
mouse 
with a Bluetooth
adapter.
•A micro SD card.
•A micro SD card reader.
•A Raspberry Pi.

Software Required
•SD card Formatter
–SD card must be formatted before using to boot
Raspberry PI.
•NOOBS
–NOOBS 
is an easy operating system installer
which
 contains 
Raspbian 
and 
LibreELEC. It also provides
a selection of alternative operating systems which are
then downloaded from the internet and installed.

Steps to Boot Raspberry Pi
•Format SD card
•Extract NOOBS in New Folder
–Copy the inside contents of New Folder to SD card
–Place the SD card on the slot of Raspberry Pi
–Power Up Raspberry Pi
–Connect USB Mouse, USB Keyboard and HDMI to
VGA cable to Monitor
–Install Raspbian OS

Command for Update or Upgrade OS
•sudo apt-get update
•sudo apt-get upgrade

Commands to Install Software
To install Arduino
sudo apt-get install arduino
To remove Arduino
sudo autoremove arduino
To install pyfirmata
sudo apt-get install pyfirmata
Or
sudo apt-get install python-pip python-serial
sudo pip install pyfirmata

Run Some Basic Terminal Commands
•pwd
•ls
•ls -l
•cd
•cd..
•mkdir foldername
•rmdir –r foldername
•touch filename
•cat filename

Reserved Keywords

Raspberry PI 3 GPIO Header

Q1. Does RPi have an internal memory?
a) True
b) False
c) Don’t know sir
Q2. What do we use to connect TV to RPi?
a) Male HDMI
b) Female HDMI
c) Male HDMI and Adapter
d) Female HDMI and Adapter
e) Don’t know sir
Q3. How power supply is done to RPi?
a) USB connection
b) Internal battery
c) Charger
d) Adapter
e) Don’t know sir

•Program to toggle the LED connected to BCM-18 pin

Toggle LED
#Program to toggle the LED connected to BCM-18 pin
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
GPIO.output(18,GPIO.HIGH)
time.sleep(3)
GPIO.output(18,GPIO.LOW)
time.sleep(3)

Toggle LED Infinite
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
while True:
GPIO.output(18,GPIO.HIGH)
time.sleep(3)
GPIO.output(18,GPIO.LOW)
time.sleep(3)

Toggle Led N times
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
for x in range(0,5):
GPIO.output(18,GPIO.HIGH)
time.sleep(3)
GPIO.output(18,GPIO.LOW)
time.sleep(3)

Toggle Led According to User Input
import RPi.GPIO as GPIO
import time
x=int(input(“Enter the value: ”))
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
for x in range(x):
GPIO.output(18,GPIO.HIGH)
time.sleep(3)
GPIO.output(18,GPIO.LOW)
time.sleep(3)

Pulse Width Modulation (PWM)
•To create an analog signal, the microcontroller uses a technique
called PWM. By varying the duty cycle, we can mimic an
“average” analog voltage.
•A PWM signal is a digital square wave, where the frequency is constant, but
that fraction of the time the signal is on (the duty cycle) can be varied
between 0 & 100%
PWM has several uses:
• Dimming an LED
• Providing an analog output; if the digital output is filtered,
it will provide an analog voltage between 0% and 100% .
• Generating audio signals.
• Providing variable speed control for motors.

PWM Example
import RPi.GPIO as IO
         #calling header file which helps us use GPIO’s of PI
import time
                           #calling time to provide delays in program
IO.setwarnings(False)
          #do not show any warnings
IO.setmode (IO.BCM)
        #we are programming the GPIO by BCM pin numbers. (PIN35 as ‘GPIO19’)
IO.setup(19,IO.OUT)
          # initialize GPIO19 as an output.
p = IO.PWM(19,100)
         #GPIO19 as PWM output, with 100Hz frequency
p.start(0)
                             #generate PWM signal with 0% duty cycle
while 1:
                              #execute loop forever
 
 
for x in range (50):
                         #execute loop for 50 times, x being incremented from 0 to 49.
 
      p.ChangeDutyCycle(x)               #change duty cycle for varying the brightness of LED.
 
      time.sleep(0.1)                           #sleep for 100m second
 
    
 
  for x in range (50):                         #execute loop for 50 times, x being decremented from 49 to 0.
 
      p.ChangeDutyCycle(50-x)        #change duty cycle for changing the brightness of LED.
 
      time.sleep(0.1)                          #sleep for 100m second

IR Sensor
import RPi.GPIO as GPIO
import time as t
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(21,GPIO.IN)
try:
while True:
x=GPIO.input(21)
if(x==1):
print(“Object Detected”)
t.sleep(1)
else:
print(“No Object Detected”)
t.sleep(1)
except KeyboardInterrupt:
print(“User Interrupted”)
GPIO.cleanup()

Ultrasonic Sensor

•An Ultrasonic sensor is a device that can measure the distance to an object
by using sound waves.
•It measures distance by sending out a sound wave at a specific frequency
and listening for that sound wave to bounce back.
•By recording the elapsed time between the sound wave being generated
and the sound wave bouncing back, it is possible to calculate the distance
between the sonar sensor and the object.
 

•Since it is known that sound travels through air at about 344 m/s (1129 ft/s).
•Sound wave to return and multiply it by 344 meters (or 1129 feet) to find the
total round-trip distance of the sound wave.
•Round-trip means that the sound wave traveled 2 times the distance to the
object before it was detected by the sensor.
•To find the distance to the object, simply divide the round-trip distance in
half.

•The
 
Trig
 pin
will be used to send the signal and
•The
 
Echo
 pin
will be used to listen for returning signal

Ultrasonic Sensor
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
trigger=18
echo=23
GPIO.setwarnings(False)
GPIO.setup(trigger,GPIO.OUT)
GPIO.setup(echo,GPIO.IN)
while True:
GPIO.output(trigger,False)
time.sleep(1)
GPIO.output(trigger,True)
time.sleep(0.00001)#keep trigger_pin high for 10 micro_seconds
GPIO.output(trigger,False)

while(GPIO.input(echo)==0):#check, when the echo_pin goes low
starttime=time.time()#and, note down this time stamp
while(GPIO.input(echo)==1):#check, when the echo_pin goes high
stoptime=time.time()#and, note down this time stamp
totaltime=stoptime-starttime
distacne=(totaltime*34400)/2
print(distance)
time.sleep(2)

Key Interfacing
•The Button is wired in such a way that when it
is pressed, it will connect GPIO 23 to the
Ground(GND).

•Each GPIO pin in Raspberry Pi has software
configurable pull-up and pull-down resistors.
•When using a GPIO pin as an input, you can configure
these resistors so that one or either or neither of the
resistors is enabled, using the
optional
 
pull_up_down 
parameter to 
GPIO.setup
•If it is set to
 
GPIO.PUD_UP 
, the pull-up resistor is
enabled; if it is set to
 
GPIO.PUD_DOWN 
, the pull-
down resistor is enabled.
•After running the code, when you push the Button, LED
should turn ON and in terminal window you will see
the text "Button Pressed...".

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup (23, GPIO.IN,pull_up_down=GPIO.PUD_UP) #Button to GPIO23
GPIO.setup(24, GPIO.OUT) #LED to GPIO24
try:
while True:
button_state = GPIO.input(23)
if button_state == False:
GPIO.output(24, True)
print('Button Pressed...')
#time.sleep(0.2)
else:
GPIO.output(24, False)
except:
GPIO.cleanup()

Introduction
•The 7-segment display, also written as “seven
segment display”, consists of seven LEDs arranged in
a rectangular fashion as shown in the Figure.
•Each of the seven LEDs is called a segment.

Introduction
•Each one of the seven LEDs in the display is given a positional segment which is
controlled by one pin.
•These LED pins are labeled a, b, c, d, e, f, and g representing each individual
LED.
•The other LED pins are connected together and wired to form a common pin.
•By forward biasing the appropriate pins of the LED segments, some segments
will be light and others will be dark allowing the desired character pattern of
the number to be generated on the display.
•This allows us to display each of the ten decimal digits 0 through to 9 or hexa
decimal numbers 0 through to F , on the same 7-segment display.
•An additional 8th LED is sometimes used within the same package thus allowing
the indication of a decimal point, (DP) when two or more 7-segment displays
are connected together to display numbers greater than ten.

Types of 7-Segment Displays
•The displays common pin is generally used to
identify which type of 7-segment display it is.
•As each LED has two connecting pins, one called the
“Anode” and the other called the “Cathode”.
•Therefore , there are two types of LED 7-segment
display:
 
–1. Common Cathode (CC)
–2. Common Anode (CA)

Common Cathode (CC)
•In the common cathode display,
–all the cathode connections of the LED segments
are joined together to logic “0″ or ground.
–The individual segments are illuminated by
application of a “HIGH”, or logic “1″ signal via a
current limiting resistor to forward bias the
individual Anode terminals (a-g).

Common Anode (CA)
•In the common anode display,
–all the anode connections of the LED segments are
joined together to “HIGH”, or logic “1″.
–The individual segments are illuminated by
application of a logic “0″ or ground signal via a
suitable current limiting resistor to the Cathode of
the particular segment (a-g).

Displaying Digital Digits
•Depending upon the decimal digit to be
displayed, the particular set of LEDs is forward
biased.
•The various digits from 0 through 9 can be
displayed using a 7-segment display as shown.

Displaying Decimal Digits (Cont..)

Table 1: Display decimal digits using the 7-segments (Common Cathode)
Decimal DigitG F E D C B A
0 0 1 1 1 1 1 1
1 0 0 0 0 1 1 0
2 1 0 1 1 0 1 1
3 1 0 0 1 1 1 1
4 1 1 0 0 1 1 0
5 1 1 0 1 1 0 1
6 1 1 1 1 1 0 1
7 0 0 0 0 1 1 1
8 1 1 1 1 1 1 1
9 1 1 0 1 1 1 1
A
B
C
D
E
F
G

Driving a 7-Segment Display
•Although a 7-segment display can be thought of as a single
display, it is still seven individual LEDs within a single package
and as such these LEDs need protection from over-current.
•LEDs produce light only when it is forward biased with the
amount of light emitted being proportional to the forward
current.
•This means that an LEDs light intensity increases in an
approximately linear manner with an increasing current.
•So this forward current must be controlled and limited to a
safe value by an external resistor to prevent damaging the LED
segments.

Driving a 7-Segment Display (Cont..)
•The forward voltage drop across a red LED segment is very low at
about 2-to-2.2 volts.
•To illuminate correctly, the LED segments should be connected to a
voltage source in excess of this forward voltage value with a series
resistance used to limit the forward current to a desirable value.
•Typically for a standard red colored 7-segment display, each LED
segment can draw about 15mA to illuminated correctly, so on a 5
volt digital logic circuit,
–the value of the current limiting resistor would be
about 200Ω (5v – 2v)/15mA, or
–220Ω to the nearest higher preferred value.

Driving a 7-Segment Display (Cont..)
•So to understand how the segments of the display are
connected to a 220Ω current limiting resistor consider the
circuit below.

Driving a 7-Segment Display (Cont..)
•In this example,
–the segments of a common anode display are illuminated using
the switches.
–If switch a is closed, current will flow through the “a” segment of
the LED to the current limiting resistor connected to pin a and to
0 volts, making the circuit.
–Then only segment a will be illuminated.
–If we want the decimal number “4″ to
illuminate on the display, then switches
b, c, f and g would be closed to light the
corresponding LED segments.

Interfacing 7-Segment Display to Arduino
• The 7-Segment Display (shown in Figure below) can be interfaced to the
Arduino Uno Board as shown in the next two slides.
•Power supply of 5V DC is provided, either through Vcc1 pin or Vcc2 pin.,
with respect to a resister connected across.
Pin configuration of the 7-Segment
display with common anode
G F Vcc1 A B
E D Vcc2 C DP
CommonAnode(CA):
Com: Vcc=5V (through a Resistor)
A – G : Vcc=5V i.e. bibary ‘1’ => LEDs (A – G) will be OFF
A – G : Gnd=0V i.e. bibary ‘0’ => LEDs (A – G) will be ON
CommonCathode(CC):
Com: Gnd=0v (through a Resistor)
A – G : Vcc=5V i.e. bibary ‘1’ => LEDs (A – G) will be ON
A – G : Gnd=0V i.e. bibary ‘0’ => LEDs (A – G) will be OFF

0 – 9 using format()
#CA_SSD
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
data=[0x01,0x4f, 0x12, 0x06, 0x4c, 0x24, 0x20, 0x0f, 0x00, 0x04]
for i in range (2,9):
GPIO.setup(i,GPIO.OUT)
while True:
for j in range(0,10):
c=format(data[j],'08b')
print("c is:",c)
for k in range(2,9):
GPIO.output(k,int(c[k-1]))
time.sleep(1)

0 – 9 without format()
import RPi.GPIO as GPIO
Import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
a,b,c,d,e,f,g=4,17,18,27,22,24,25
char = [[0,0,0,0,0,0,1],[1,0,0,1,1,1,1],[0,0,1,0,0,1,0],[0,0,0,0,1,1,0],
[1,0,0,1,1,0,0],[0,1,0,0,1,0,0],[0,1,0,0,0,0,0],[0,0,0,1,1,1,1],[0,0,0,0,0,0,0],
[0,0,0,1,1,0,0]]
pins = [a,b,c,d,e,f,g]
for k in range(0,7):
GPIO.setup(pins[k],GPIO.OUT)
while True:
for i in range(0,10):
for j in range (0,7):
GPIO.output(pins[j],char[i][j])
time.sleep(1)

00 – 99
import RPi.GPIO as x
import time
x.setmode(x.BCM)
x.setwarnings(False)
data = [0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0x00,0x10]; # dp g f e d c b a
y=[24,23,22,27,18,17,4]
z=[25,5]
for i in range(len(y)):
x.setup(y[i],x.OUT)
for j in range(len(z)):
x.setup(z[j],x.OUT)

00 – 99 (Cont..)
while True:
for j in range(100):
a=j%10
b=j//10
c=format(data[a],'08b’)
g=format(data[b],'08b’)
for i in range(20):
x.output(z[1],1)
x.output(z[0],0)
for k in range(len(y)):
x.output(y[k],int(c[k+1]))
time.sleep(0.01)
x.output(z[1],0)
x.output(z[0],1)
for f in range(len(y)):
x.output(y[f],int(g[f+1]))
time.sleep(0.01)

Introduction
•Liquid crystal displays (LCDs) offer a convenient and
inexpensive way to provide a user interface for a
project.

Introduction (Cont..)

•Here, we are going to install and use the library from Adafruit.
•First, clone the required git directory to the Raspberry Pi by running the
following command in terminal window.
git clone https://github.com/pimylifeup/Adafruit_Python_CharLCD.git
•Next change into the directory, we just cloned and run the setup file.
cd ./Adafruit_Python_CharLCD
sudo python setup.py install (or) sudo python3 setup.py install
•Once it’s finished installing, you can now call the Adafruit library in any Python
script on the Pi.
•To include the library just add the following line at the top of the Python script.
–import Adafruit_CharLCD as LCD
•And to initialize the LCD python library, add the following.
–lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,
lcd_columns, lcd_rows, lcd_backlight)

some of the methods that are available, under Adafruit
library:
home() 

This method will move the cursor back to home which is the first column on
the first line.
clear() 

This method clears the LCD so that it’s completely blank.
set_cursor(col, row) 

This method will move the cursor to a specific position. You
specify the position by passing the column and row numbers as parameters.
Eg. set_cursor(4,1)
enable_display(enable) 

This enables or disables the display. Set it to True to enable it.
show_cursor(show) 

This either shows or hides the cursor. Set it to True if you want
the cursor to be displayed.
blink(blink) 

Turns on or off a blinking cursor. Set this to True if you want the cursor
to be blinking.
move_left() or move_right() 

Moves the cursor either left or right by one position.
set_right_to_left() or set_left_to_right() 

Sets the cursor direction either left to right or
right to left.
autoscroll(autoscroll) 

If autoscroll is set to True then the text will right justify from
the cursor. If set to False it will left justify the text.
message(text) 

Simply writes text to the display. You can also include new lines (\n) in
your message.

#!/usr/bin/python
# Example using a 16x2 character LCD connected to a Raspberry Pi
import time
import Adafruit_CharLCD as LCD
# Raspberry Pi pin setup
lcd_rs = 26
lcd_en = 24
lcd_d4 = 23
lcd_d5 = 17
lcd_d6 = 18
lcd_d7 = 22
lcd_backlight = 2
# Define LCD column and row size for 16x2 LCD.
lcd_columns = 16
lcd_rows = 2

lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,
lcd_columns, lcd_rows, lcd_backlight)
lcd.message('Hello\nworld!')
# Wait 5 seconds
time.sleep(5.0)
lcd.clear()
text = input("Type Something to be displayed: ")
lcd.message(text)
# Wait 5 seconds
time.sleep(5.0)
lcd.clear()
lcd.message('Goodbye\nWorld!')
time.sleep(5.0)
lcd.clear()

Connecting the LCD using I2C Protocol

DC Motor Interfacing

L293D Motor Driver IC

DC Motor connections to L293D

connections to L293D

Sulphur Sulphur
dioxide/Hydrogedioxide/Hydroge
n Sulphide gas n Sulphide gas
sensorsensor
Temperature/Temperature/
Humidity Humidity
SensorSensor
Thermal Thermal
mass flow mass flow
sensorsensor

Data Types
1.list
2.tuple
3.dictionary
4.set

Pre-define (Built-in) math functions
Import math
1.math.ceil(x)
2.math.floor(y)
3.math.fmod(x,y)
4.math.exp(x)
5.math.factorial(x)
6.math.sqrt(x)
7.math.pow(x,y)

Mathematical constants
Import math
1.math.pi
2.math.e

Pre-defined random numbers
generator functions
Import random
1.random.random()
2.random.uniform(a,b)
3.random.randint(a,b)
4.random.getrandbits(k)
5.random.choice(seq.)

Strings
•Initialization
•Concatination
•Repetetion
Split function:
•string_name.split()

Built-in string functions:
1. input_string_name.capitalize()
2. input_string_name.center(width,fill_char)
3. input_string_name.count(sub_string,beginning_index, end_index)
4. input_string_name.endswith(sub_string,beginning_index, end_index)
5. input_string_name.find(sub_string,beginning_index, end_index)

Built-in string functions (Cont..):
6. input_string_name.index(sub_string,beginning_index, end_index)
7. input_string_name.isupper()
8. input_string_name.islower()
9. input_string_name.istitle()
10. len(input_string_name)

Built-in string functions (Cont..):
11. input_string_name.lower()
12. input_string_name.upper()
13. max(input_string_name)
14. min(input_string_name)
15. input_string_name.startswith(sub_string,beginning_index,
end_index)

Built-in string functions (Cont..):
16. input_string_name.rfind(sub_string,beginning_index, end_index)
17. input_string_name.rindex(sub_string,beginning_index, end_index)
18. input_string_name.swapcase()
19. input_string_name.title()

Python input/output
•Input(prompt)
•N= input(“Enter the number”)
•Print()
•Print (“statement”)
•>>> print(1,2,3,4,5,sep='@')
1@2@3@4@5
•>>> print(1,2,3,4,5,sep='*',end='&')
1*2*3*4*5&

Decision making
•Sequential structure
i=i+1, j=j+1
•Selection structure
if(x<y):
i=i+1
else:
j=j+1
•Iteration structure
for I in range(5):
print(i)
•Encapsulation structure

If statement
if test expression:
statement(s)
Ex: num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
if test expression:
Body of if
else:
Body of else

Cont…
Ex:num = 3
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else

Cont…
Ex:num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

Iteration - Looping
•While Loop:-
while test_expression:
Body of while
Ex: n = 10
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
print("The sum is", sum)

Cont…
Ex: counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")

Cont…
Ex:i = 1
while i < 6:
   print(i)
   if i == 3:
     break
  i += 1
Ex: i = 0
while i < 6:
   i += 1
   if i == 3:
     continue
  print(i)

Cont…
•For loop:-
for val in sequence:
Body of for
Ex: numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:
sum = sum+val
print("The sum is", sum)

Cont…
print(range(10))
print(list(range(10)))
print(list(range(2, 8)))
print(list(range(2, 20, 3)))
genre = ['pop', 'rock', 'jazz']
for i in range(len(genre)):
print("I like", genre[i])

Cont…
Ex: digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
Ex: student_name = 'Soyuj’
marks = {'James': 90, 'Jules': 55, 'Arthur': 77}
for student in marks:
if student == student_name:
print(marks[student])
break
else:
print('No entry with that name found.')

Functions:
•Function definition:
•Function call
•No function declaration

Functions (Cont..):
Eg.
/* Function to add two numbers*/
def add(a,b):
sum=a+b
return sum
a=int(input(“Enter 1
st
no. for a”))
b=int(input(“Enter 2
nd
no. for b”))
result=add(a,b)
print(“Result=”, result)

Local and Global variables in
Functions:
Eg.
a=20
def display():
b=30
print(“Inside the user defi. fun.:”, a)
print(“Local variable:”, b)
display()
c=40
print(“Outside the user defi. fun.:”, a)
print(“Local variable:”, b)

Type of arguments:
Different ways, that the arguments could be passed to the system call are:
1.Required arguments
2.Keyword arguments
3.Default arguments
4.Variable length arguments

1. Required arguments:
Eg.
def display(a,b):
print(“a=”,a,”b=”,b)
display(10,20)
/*display(20,10)*/

2. Keyword arguments:
Eg.
def display(a,b):
print(“a=”,a,”b=”,b)
display(a=10,b=20)
/*display(b=10,a=20)*/

3. Default arguments:
Eg.
def display(name=“abc”,courses=“b.tech”):
print(“name=”, name)
print(“courses=”, courses)
display(name=“abc”, courses=“m.tech”)
display(name=“pqr”)

4. Variable length arguments:
Eg.
def display(*subjects):
for i in subjects:
print(i)
display(“b.tech”,”m.tech”,”mba”,”mca”)

Recursion Function:
1.Base case
2.Recursive case

Recursion Function (Cont..):
Eg.
def factorial(n):
if(n==0 or n==1)
return 1
else:
return n*factorial(n-1)
n=int(input(“Enter a value for n”))
result=factorial(n)
print(“Factorial of”,n,”is:”,result)

Anonymous/Lambda Function:
•Do not define by “def” keyword
–Will be defined by using “lambda” keyword
•Will return expression but not value
•Are one line functions
•Can take any number of arguments
•Can not access global variables
•Does not have any specific name
–Syntax: lambda argument(s):expression

Anonymous/Lambda Function:
Eg. /* Function to add two numbers*/
sum=(lambda x,y:x+y)
a=int(input(“Enter a value for a:”)
b=int(input(“Enter a value for b:”)
Print(“sum=”, sum(a,b))

Command line Arguments:
•input()  takes the i/p in runtime (string format)
–Another way to accept the i/p’s. i.e. i/p’s will be processed to the
program as an arguments from the command prompt directly
•“sys” module
•All the arguments will be formed/saved as a LIST in
argv (argument’s value)
•By using sys.argv  we can access the command
prompt
•Arguments passing from command prompt will also
be considered as string

Command line Arguments (Cont..):
•Elements will be having by “sys.argv(LIST)”
•Elements of argv can be accessed using INDEX values
–sys.argv[0] is our file name, then from sys.argv[1] on wards
are the arguments/elements
•So we have to import “sys” module before using argv
Eg. Import sys
print(sys.argv)
print(len(sys.argv))
for ele in sys.argv:
print(“Arguments:”,ele)

Command line Arguments (Cont..):
•Eg. Program to add two add two numbers:
# sum of all the elements inputed from command line
Import sys
sum=0
for i in range(0,length(sys.argv)):
sum+=int(sys.argv[i])
print(“result=”, sum)

Meta-Characters:
[ ]  return a match if string contains characters specified in [ ]
^  return a match if string starts with given pattern
$  return a match if string ends with given pattern
.  accept any character except new line
*  return a match if there is zero or more occurrences of given pattern
+  return a match if there is one or more occurrences of given pattern
{ }  return a match if the string contains specified no. of occurrences

Spatial Sequences:
\d  return a match if the given string having digits
\D  return a match if the given string does not have digits
\w  return a match if the given string having word characters
\W  return a match if the given string does not have word characters
\s  return a match if the given string having spaces
\S  return a match if the given string does not have spaces
\Z  return a match if the given string ends with specified character

Meta-Characters/Spatial sequences (Cont..):

Meta-Characters (Cont..):
import re
str = “Example for metacharacters in regular expression”
result=re.findall(“[a]”, str)
print(result)
result =re.findall(“^Example”, str)
result =re.findall(“expression$”, str)
result =re.findall(“Exam..”, str)
result =re.findall(“m*”, str)

Spatial Sequences (Cont..):
import re
str = “Example for metacharacters in regular expression”
Str2=“123 friend in need is a friend in deed”
result=re.findall(“\s”, str2)
print(result)
res=re.findall(“\d”, str2)
res=re.findall(“expression$”, str)

Date and Time Module:

Time-Delta Function:

Any Query ???
Tags