SlideShare a Scribd company logo
Python for Beginners(v2)
Dr.M.Rajendiran
Dept. of Computer Science and Engineering
Panimalar Engineering College
Install Python 3 On Ubuntu
Prerequisites
Step 1.A system running Ubuntu
Step 2.A user account with sudo privileges
Step 3.Access to a terminal command-line (Ctrl–Alt–T)
Step 4.Make sure your environment is configured to use
Python 3.8
2
Install Python 3
Now you can start the installation of Python 3.8.
$sudo apt install python3.8
Allow the process to complete and verify the Python
version was installed successfully
$python ––version
3
Installing and using Python on Windows is very simple.
Step 1: Download the Python Installer binaries
Step 2: Run the Executable Installer
Step 3: Add Python to environmental variables
Step 4: Verify the Python Installation
4
Python Installation
Open the Python website in your web browser.
https://www.python.org/downloads/windows/
Once the installer is downloaded, run the Python installer.
Add the following path
C:Program FilesPython37-32: for 64-bit installation
Once the installation is over, you will see a Python Setup
Successful window.
You are ready to start developing Python applications in
your Windows 10 system.
5
iPython Installation
If you already have Python installed, you can use pip to
install iPython using the following command:
$pip install iPython
To use it, type the following command in your computer’s
terminal:
$ipython
6
BOOLEAN VALUES
 Boolean data type have two values. They are 0 and 1.
 0 represents False
 1 represents True
 True and False are keyword.
Example:
>>> 3==5
False
>>> 6==6
True
>>> True+True
2
>>> False+True
1
>>> False*True
0
CONDITIONALS
 Conditional if
 Alternative if… else
 Chained if…elif…else
 Nested if….else
Conditional (if)
 conditional (if) is used to test a condition, if the condition is
true the statements inside will be executed.
Syntax:
if(conditions):
……………..
statements
……………..
CONDITIONALS
Flowchart
Example:
1. Program to provide discount Rs 500, if the purchase amount is greater
than 2000.
Program Output
purchase=eval(input(“enter your
purchase amount”)
if(purchase>=2000):
purchase=purchase-500
print(“amount to pay”, purchase)
enter your purchase amount
2500
amount to pay
2000
CONDITIONALS
2.Program to provide bonus mark if the category is sports
Program Output
m=eval(input(“enter your mark”))
c=input(“enter your category G/S”)
if(c==“S”):
m=m+5
print(“mark is”,m)
enter your mark
85
enter your category G/S
S
mark is 90
CONDITIONALS
Alternative (if-else)
In the alternative the condition must be true or false.
In this else statement can be combined with if statement.
The else statement contains the block of code that executes when
the condition is false.
If the condition is true statements inside the if get executed
otherwise else part gets executed.
The alternatives are called branches.
syntax:
if (condition1):
statement1
else:
statement2
CONDITIONALS
Flowchart:
Examples:
Odd or even number Output
n=eval(input("enter a number"))
if(n%2==0):
print("even number")
else:
print("odd number")
enter a number 4
even number
CONDITIONALS
.
Positive or negative number Output
n=eval(input("enter a number"))
if(n>=0):
print("positive number")
else:
print("negative number")
enter a number 8
positive number
Leap year or not Output
y=eval(input("enter a year"))
if(y%4==0):
print("leap year")
else:
print("not leap year")
enter a year 2000
leap year
CONDITIONALS
.
Greatest of two numbers Output
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
if(a>b):
print("greatest”,a)
else:
print("greatest:",b)
enter a value:4
enter b value:7
greatest: 7
Eligibility for voting Output
age=eval(input("enter your age:"))
if(age>=18):
print("you are eligible for vote")
else:
print("you are eligible for vote")
enter ur age:78
you are eligible for vote
CONDITIONALS
Chained conditionals(if-elif-else)
The elif is short for else if.
This is used to check more than one condition.
If the condition1 is false, it checks the condition2 of the elif block.
If all the conditions are false, then the else part is executed.
Only one part is executed according to the condition.
The if block can have only one else block. But it can have multiple
elif blocks.
The way to express a computation like that is a chained conditional.
CONDITIONALS
Syntax:
if(condition 1):
statement 1
elif(condition 2):
statement 2
elif(condition 3):
statement 3
else:
default statement
CONDITIONALS
Flowchart:
SAMPLE PROGRAMS
.
Student mark system Output
mark=eval(input("enter your mark:"))
if(mark>=90):
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
Enter your mark:78
grade:B
Roots of quadratic equation Output
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
c=eval(input("enter c value:"))
d=(b*b-4*a*c)
if(d==0):
print("same and real roots")
elif(d>0):
print("diffrent real roots")
else:
print("imaginagry roots")
enter a value:1
enter b value:0
enter c value:0
same and real roots
CONDITIONALS
Nested conditionals
One conditional can also be nested within another.
Any number of condition can be nested inside one another.
If the condition is true it checks another ifcondition1.
Syntax: Flowchart:
if (condition1):
if(condition2):
statement1
else:
statement2
else:
statement3
SAMPLE PROGRAMS
.
Greatest of three numbers Output
a=eval(input("enter the value of a"))
b=eval(input("enter the value of b"))
c=eval(input("enter the value of c"))
if(a>b):
if(a>c):
print("the greatest no is",a)
else:
print("the greatest no is",c)
else:
if(b>c):
print("the greatest no
is",b)
else:
print("the greatest no is",c)
Enter your mark:78
grade:B
ITERATION
1.while
2.for
while loop
While loop is used to repeatedly executes set of statement as
long as a given condition is true.
In while loop, test expression is checked first. The body of the loop
is entered only if the test expression is True.
This process continues until the test expression evaluates to False.
The body of the while loop is determined through indentation.
The statements inside the while start with indentation
ITERATION
. Syntax
initial value
while(condition):
body of while loop
increment
Flowchart
Example
i = 1
while i <=5:
print(i)
i = i + 1
print("Finished!")
Output
1
2
3
4
5
Finished!
ITERATION
else in while loop
The else part will be executed when the condition become false.
Example
i=1
while(i<=5):
print(i)
i=i+1
else:
print("the number greater than 5")
Output
1
2
3
4
5
the number greater than 5
ITERATION
Nested while
While inside another while is called nested while
Syntax:
While(condition1):
while(condtion2):
statement2
Statement1
Example
i=1
while i<4:
j=4
while j<6:
print(i*j)
j=j+1
i=i+1
output
4
5
8
10
12
15
ITERATION
for loop(for in range)
We can generate a sequence of numbers using range() function.
range(10) will generate numbers from 0 to 9 (10 numbers).
In range function have to define the start, stop and step size as
range(start,stop,step size).
step size defaults to 1 if not provided.
Syntax:
for i in range(start, stop, steps):
body of the for loop
Example:
for i in range(1,6):
print(i)
Flowchart
Output
1 2 3 4 5
ITERATION
else in for loop
The else statement is executed when the loop has reached the limit.
The statements inside for loop and statements inside else will also
execute.
Example:
for i in range(1,6):
print(i)
else:
print("the number greater than 6")
Output
1
2
3
4
5
the number greater than 6
ITERATION
for in sequence
The for loop in Python is used to iterate over a sequence (list, tuple,
string).
Iterating over a sequence is called traversal.
Loop continues until we reach the last element in the sequence.
The body of for loop is separated from the rest of the code using
indentation.
Syntax:
for i in sequence:
print(i)
ITERATION
Sequence can be a list, strings or tuples
No. Sequences Example Output
1 for loop in string for in in “RAJA”
print(i)
R
A
J
A
2. for loop in list for i in [2,3,5,6,9]
print(i)
2
3
5
6
9
3. for loop in tuple for i in (2,3,1):
print(i)
2
3
1
ITERATION
Nested for loop
for inside another for is called nested for.
Syntax
for i in sequence:
for j in sequence:
statements
statements
Example:
for i in range(1,4):
for j in range(4,7):
print(i*j)
Output
4
5
6
8
10
12
12
15
18
Assignments
Programs
1. print nos divisible by 5 not by 10:
2. Program to print fibonacci series.
3. Program to find factors of a given number
4. check the given number is perfect number or not
5. check the no is prime or not
6. Print first n prime numbers
7. Program to print prime numbers in range
LOOP CONTROL STRUCTURES
1.break 2.continue 3.pass
1.break
To end a while loop prematurely, the break statement can be used.
When encountered inside a loop, the break statement causes the
loop to finish immediately.
Syntax : break Flowchart
while(test expression)
if(condition):
break
Example
i = 0
while 1==1:
print(i)
i = i + 1
if i >= 5:
print("Breaking")
break
print("Finished")
Output
0
1
2
3
4
Breaking
Finished
LOOP CONTROL STRUCTURES
2.continue
It is unlike break, continue jumps back to the top of the loop, rather
than stopping it.
Another statement that can be used within loops is continue.
Syntax : continue Flowchart
while(test expression):
if(condition):
continue
Example
i = 0
while True:
i = i +1
if i == 2:
print("Skipping 2")
continue
if i == 5:
print("Breaking")
break
print(i)
print("Finished")
Result:
>>>
1
Skipping
2
3
4
Breaking
Finished
>>>
LOOP CONTROL STRUCTURES
3.pass
It is a null statement, nothing happens when it is executed.
Syntax : pass
for i in sequence:
if(condition):
pass
Example
for i in "welcome":
if (i == "c"):
pass
print(i)
Result:
>>>
w
e
l
c
o
m
e
>>>
SCOPE OF VARIABLES
Global scope
The scope of a variable refers to the places that you can see or
access a variable.
A variable with global scope can be used anywhere in the program.
It can be created by defining a variable outside the function.
Example
a=50 #Global variable
def add():
b=20
c=a+b
print(c)
def sub():
b=30
c=a-b
print(c)
add()
sub()
print(a)
Result:
>>>
70
20
50
>>>
SCOPE OF VARIABLES
Local scope
A variable with local scope can be used only within the function .
Example
a=50 #global variable
def add():
b=20 #local variable
c=a+b
print(c)
def sub():
b=30
c=a-b
print(c)
add()
sub()
print(a)
print(b)
Result:
>>>
70
20
50
error
>>>
FUNCTION COMPOSITION
It is the ability to call one function from within another function
It is a way of combining functions such that the result of each
function is passed as the argument of the next function.
The output of one function is given as the input of another function is
known as function composition.
Example
def max(x, y):
if x >=y:
return x
else:
return y
print(max(4, 7))
z = max(8, 5)
print(z)
Result:
>>>
7
8
>>>
RECURSION
A function calling itself till it reaches the base value.
#Factorial of a given number
def fact(n):
if(n==1):
return 1
else:
return n*fact(n-1)
n=eval(input("enter no:"))
fact=fact(n)
print("Fact is",fact)
Result:
>>>
enter no:5
Fact is 120
>>>
STRINGS
It is defined as sequence of characters represented either single
quotes (' ') or double quotes (" ").
An individual character in a string is accessed using a index.
The index should always be an integer (positive or negative).
An index starts from 0 to n-1.
Strings are immutable i.e. the contents of the string cannot be
changed after it is created.
Python will get the input at run time by default as a string.
Python does not support character data type. A string of size 1 can
be treated as characters.
STRINGS
1. single quotes (' ')
2. double quotes (" ")
3. triple quotes(""" """)
Opération on strings
1.Indexing
2.Slicing
3.Concatenation
4.Repetions
5.Membership
STRINGS
Indexing
>>>a= HELLO
>>>print(a[0])
>>>H
>>>print(a[-1])
>>>O
Positive indexing helps in accessing the string from
the beginning
Negative subscript helps in accessing the string from
the end.
Slicing
print a[0:4]-HELL
print a[ :3]-HEL
print a[0: ]-HELLO
The Slice[start : stop] operator extracts sub string
from the strings.
A segment of a string is called a slice.
Concatenation
a= “tham”
b=”man”
>>>print(a+b)
thamman
+ operator joins the text on both sides of the operator.
Repetitions
a= “RAJ”
>>>print(3*a)
RAJRAJRAJ
* operator repeats the string.
Membership
>>> s="WELCOME"
>>>"E" in s
True
>>> "a" not in s
True
Check a particular character is in string or not.
Returns true if present.
STRINGS
Immutability
Strings are immutable as they cannot be changed after they are
created.
[ ] operator cannot be used on the left side of an assignment.
Element
assignment
A=“PYTHON”
A[0]=‘X’
Element assignment error
Element deletion
A=“PYTHON”
del A[0]
Element deletion error
Delete a string
A=“PYTHON”
del A
print(A)
A is not defined
STRINGS
String built-in functions and methods
A method is a function that belongs to an object.
Syntax: stringname.method(), a=“happy birthday”
Syntax Example Description
a.capitalize()
>>> a.capitalize()
' Happy birthday
capitalize only the first letter in a
string
a.upper()
>>> a.upper()
'HAPPY BIRTHDAY
change string to upper case
a.lower()
>>> a.lower()
' happy birthday
change string to lower case
a.title()
>>> a.title()
' Happy Birthday '
change string to title case
a.isupper()
A= happy birthday
>>> a.isupper()
False
whether letters are upper case or
not
a.islower()
>>> a.islower()
True
whether letters are lower case or
not
len(a)
>>>len(a)
>>>14
length of the string
STRING MODULES
A module is a file containing python definitions, functions,
statements.
Standard library of python is extended as modules.
Programmer needs to import the module.
We can use to any of its functions or variables in our code.
Large number of standard modules also available in python.
Standard modules can be imported the same way as we import our
user-defined modules.
Syntax:
import module_name
STRING MODULES
Example
>>>import string
>>>print(string.punctuation)
!"#$%&'()*+,-./:;<=>?@[]^_`{|}~
>>>print(string.hexdigits)
0123456789abcdefABCDEF
>>>print(string.octdigits)
01234567
ARRAY
Array is a collection of similar elements. Elements in the array can
be accessed by index. Index starts with 0. Array can be handled in
python by module named array.
To create array have to import array module in the program.
Syntax :
import array
Syntax to create array:
array_name = module_name.function_name( datatype ,[elements])
Example:
a=array.array(i,[1,2,3,4])
a- array name
array- module name
i- integer datatype
ARRAY
Program to find sum of array elements
import array
sum=0
a=array.array('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)
Result:
10
Convert LIST into ARRAY
fromlist() function is used to append list to array.
List is act like a array.
Syntax:
arrayname.fromlist(list_name)
Example
import array
sum=0
l=[6,7,8,9]
a=array.array('i',[])
a.fromlist(l)
for i in a:
sum=sum+i
print(sum)
Result:
35
Methods in ARRAY
a=[2,3,4,5]
syntax:
array(data type, value list)
array(i, [2,3,4,5])
Syntax Example
append()
>>>a.append(6)
[2,3,4,5,6]
insert(index, element)
>>>a.insert(2,10)
[2,3,10,5,6]
pop(index)
>>>a.pop(1)
[2,10,5,6]
count() a.count()
4
reverse() >>>a.reverse()
[6,5,10,2]
Assignment
1.Square root using newtons method
2.GCD of two numbers
3.Exponent of number
4.Sum of array elements
5.Linear search
6.Binary search
.

More Related Content

PPTX
Python for Data Science
PPTX
Python for Beginners(v3)
PDF
Python programming Workshop SITTTR - Kalamassery
PDF
Python-02| Input, Output & Import
PDF
Python unit 2 as per Anna university syllabus
ODP
Introduction to Python - Training for Kids
PPTX
Introduction to Python Programming
PPTX
Python for Data Science
Python for Beginners(v3)
Python programming Workshop SITTTR - Kalamassery
Python-02| Input, Output & Import
Python unit 2 as per Anna university syllabus
Introduction to Python - Training for Kids
Introduction to Python Programming

What's hot (16)

PPTX
GE8151 Problem Solving and Python Programming
PPTX
Looping statement in python
PPTX
Python language data types
PPTX
Python for Beginners(v1)
PPT
Introduction to Python Language and Data Types
PPTX
Programming in Python
PPTX
PPTX
10. Recursion
PPTX
PPT on Data Science Using Python
PPTX
02. Primitive Data Types and Variables
PPTX
Loops in Python
PPTX
02. Data Types and variables
PPTX
Python ppt
PPTX
Python programming workshop session 1
GE8151 Problem Solving and Python Programming
Looping statement in python
Python language data types
Python for Beginners(v1)
Introduction to Python Language and Data Types
Programming in Python
10. Recursion
PPT on Data Science Using Python
02. Primitive Data Types and Variables
Loops in Python
02. Data Types and variables
Python ppt
Python programming workshop session 1
Ad

Similar to Python for Beginners(v2) (20)

PPTX
Bikalpa_Thapa_Python_Programming_(Basics).pptx
PPTX
Python programing
PPTX
Python programming workshop session 2
PDF
pythonQuick.pdf
PDF
python notes.pdf
PDF
python 34💭.pdf
PPT
Python Control structures
PPTX
Basics of Control Statement in C Languages
PPTX
TN 12 computer Science - ppt CHAPTER-6.pptx
PPTX
Control structure of c
PPT
Lecture 1
PPT
Lecture 1
PPTX
What is c
PDF
LOOPS TOPIC FOR CLASS XI PYTHON SYLLABUS
PPTX
made it easy: python quick reference for beginners
PPTX
Control Structures in C
PPT
C Sharp Jn (3)
PDF
04-Looping( For , while and do while looping) .pdf
PPTX
1. control structures in the python.pptx
PPTX
lecture 2.pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Python programing
Python programming workshop session 2
pythonQuick.pdf
python notes.pdf
python 34💭.pdf
Python Control structures
Basics of Control Statement in C Languages
TN 12 computer Science - ppt CHAPTER-6.pptx
Control structure of c
Lecture 1
Lecture 1
What is c
LOOPS TOPIC FOR CLASS XI PYTHON SYLLABUS
made it easy: python quick reference for beginners
Control Structures in C
C Sharp Jn (3)
04-Looping( For , while and do while looping) .pdf
1. control structures in the python.pptx
lecture 2.pptx
Ad

Recently uploaded (20)

PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
RMMM.pdf make it easy to upload and study
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Institutional Correction lecture only . . .
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Sports Quiz easy sports quiz sports quiz
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Basic Mud Logging Guide for educational purpose
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Complications of Minimal Access Surgery at WLH
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Insiders guide to clinical Medicine.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Lesson notes of climatology university.
STATICS OF THE RIGID BODIES Hibbelers.pdf
Cell Types and Its function , kingdom of life
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
RMMM.pdf make it easy to upload and study
O5-L3 Freight Transport Ops (International) V1.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Institutional Correction lecture only . . .
TR - Agricultural Crops Production NC III.pdf
Sports Quiz easy sports quiz sports quiz
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Basic Mud Logging Guide for educational purpose
PPH.pptx obstetrics and gynecology in nursing
Complications of Minimal Access Surgery at WLH
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
Insiders guide to clinical Medicine.pdf
VCE English Exam - Section C Student Revision Booklet
Lesson notes of climatology university.

Python for Beginners(v2)

  • 1. Python for Beginners(v2) Dr.M.Rajendiran Dept. of Computer Science and Engineering Panimalar Engineering College
  • 2. Install Python 3 On Ubuntu Prerequisites Step 1.A system running Ubuntu Step 2.A user account with sudo privileges Step 3.Access to a terminal command-line (Ctrl–Alt–T) Step 4.Make sure your environment is configured to use Python 3.8 2
  • 3. Install Python 3 Now you can start the installation of Python 3.8. $sudo apt install python3.8 Allow the process to complete and verify the Python version was installed successfully $python ––version 3
  • 4. Installing and using Python on Windows is very simple. Step 1: Download the Python Installer binaries Step 2: Run the Executable Installer Step 3: Add Python to environmental variables Step 4: Verify the Python Installation 4
  • 5. Python Installation Open the Python website in your web browser. https://www.python.org/downloads/windows/ Once the installer is downloaded, run the Python installer. Add the following path C:Program FilesPython37-32: for 64-bit installation Once the installation is over, you will see a Python Setup Successful window. You are ready to start developing Python applications in your Windows 10 system. 5
  • 6. iPython Installation If you already have Python installed, you can use pip to install iPython using the following command: $pip install iPython To use it, type the following command in your computer’s terminal: $ipython 6
  • 7. BOOLEAN VALUES  Boolean data type have two values. They are 0 and 1.  0 represents False  1 represents True  True and False are keyword. Example: >>> 3==5 False >>> 6==6 True >>> True+True 2 >>> False+True 1 >>> False*True 0
  • 8. CONDITIONALS  Conditional if  Alternative if… else  Chained if…elif…else  Nested if….else Conditional (if)  conditional (if) is used to test a condition, if the condition is true the statements inside will be executed. Syntax: if(conditions): …………….. statements ……………..
  • 9. CONDITIONALS Flowchart Example: 1. Program to provide discount Rs 500, if the purchase amount is greater than 2000. Program Output purchase=eval(input(“enter your purchase amount”) if(purchase>=2000): purchase=purchase-500 print(“amount to pay”, purchase) enter your purchase amount 2500 amount to pay 2000
  • 10. CONDITIONALS 2.Program to provide bonus mark if the category is sports Program Output m=eval(input(“enter your mark”)) c=input(“enter your category G/S”) if(c==“S”): m=m+5 print(“mark is”,m) enter your mark 85 enter your category G/S S mark is 90
  • 11. CONDITIONALS Alternative (if-else) In the alternative the condition must be true or false. In this else statement can be combined with if statement. The else statement contains the block of code that executes when the condition is false. If the condition is true statements inside the if get executed otherwise else part gets executed. The alternatives are called branches. syntax: if (condition1): statement1 else: statement2
  • 12. CONDITIONALS Flowchart: Examples: Odd or even number Output n=eval(input("enter a number")) if(n%2==0): print("even number") else: print("odd number") enter a number 4 even number
  • 13. CONDITIONALS . Positive or negative number Output n=eval(input("enter a number")) if(n>=0): print("positive number") else: print("negative number") enter a number 8 positive number Leap year or not Output y=eval(input("enter a year")) if(y%4==0): print("leap year") else: print("not leap year") enter a year 2000 leap year
  • 14. CONDITIONALS . Greatest of two numbers Output a=eval(input("enter a value:")) b=eval(input("enter b value:")) if(a>b): print("greatest”,a) else: print("greatest:",b) enter a value:4 enter b value:7 greatest: 7 Eligibility for voting Output age=eval(input("enter your age:")) if(age>=18): print("you are eligible for vote") else: print("you are eligible for vote") enter ur age:78 you are eligible for vote
  • 15. CONDITIONALS Chained conditionals(if-elif-else) The elif is short for else if. This is used to check more than one condition. If the condition1 is false, it checks the condition2 of the elif block. If all the conditions are false, then the else part is executed. Only one part is executed according to the condition. The if block can have only one else block. But it can have multiple elif blocks. The way to express a computation like that is a chained conditional.
  • 16. CONDITIONALS Syntax: if(condition 1): statement 1 elif(condition 2): statement 2 elif(condition 3): statement 3 else: default statement
  • 18. SAMPLE PROGRAMS . Student mark system Output mark=eval(input("enter your mark:")) if(mark>=90): print("grade:S") elif(mark>=80): print("grade:A") elif(mark>=70): print("grade:B") elif(mark>=50): print("grade:C") else: print("fail") Enter your mark:78 grade:B Roots of quadratic equation Output a=eval(input("enter a value:")) b=eval(input("enter b value:")) c=eval(input("enter c value:")) d=(b*b-4*a*c) if(d==0): print("same and real roots") elif(d>0): print("diffrent real roots") else: print("imaginagry roots") enter a value:1 enter b value:0 enter c value:0 same and real roots
  • 19. CONDITIONALS Nested conditionals One conditional can also be nested within another. Any number of condition can be nested inside one another. If the condition is true it checks another ifcondition1. Syntax: Flowchart: if (condition1): if(condition2): statement1 else: statement2 else: statement3
  • 20. SAMPLE PROGRAMS . Greatest of three numbers Output a=eval(input("enter the value of a")) b=eval(input("enter the value of b")) c=eval(input("enter the value of c")) if(a>b): if(a>c): print("the greatest no is",a) else: print("the greatest no is",c) else: if(b>c): print("the greatest no is",b) else: print("the greatest no is",c) Enter your mark:78 grade:B
  • 21. ITERATION 1.while 2.for while loop While loop is used to repeatedly executes set of statement as long as a given condition is true. In while loop, test expression is checked first. The body of the loop is entered only if the test expression is True. This process continues until the test expression evaluates to False. The body of the while loop is determined through indentation. The statements inside the while start with indentation
  • 22. ITERATION . Syntax initial value while(condition): body of while loop increment Flowchart Example i = 1 while i <=5: print(i) i = i + 1 print("Finished!") Output 1 2 3 4 5 Finished!
  • 23. ITERATION else in while loop The else part will be executed when the condition become false. Example i=1 while(i<=5): print(i) i=i+1 else: print("the number greater than 5") Output 1 2 3 4 5 the number greater than 5
  • 24. ITERATION Nested while While inside another while is called nested while Syntax: While(condition1): while(condtion2): statement2 Statement1 Example i=1 while i<4: j=4 while j<6: print(i*j) j=j+1 i=i+1 output 4 5 8 10 12 15
  • 25. ITERATION for loop(for in range) We can generate a sequence of numbers using range() function. range(10) will generate numbers from 0 to 9 (10 numbers). In range function have to define the start, stop and step size as range(start,stop,step size). step size defaults to 1 if not provided. Syntax: for i in range(start, stop, steps): body of the for loop Example: for i in range(1,6): print(i) Flowchart Output 1 2 3 4 5
  • 26. ITERATION else in for loop The else statement is executed when the loop has reached the limit. The statements inside for loop and statements inside else will also execute. Example: for i in range(1,6): print(i) else: print("the number greater than 6") Output 1 2 3 4 5 the number greater than 6
  • 27. ITERATION for in sequence The for loop in Python is used to iterate over a sequence (list, tuple, string). Iterating over a sequence is called traversal. Loop continues until we reach the last element in the sequence. The body of for loop is separated from the rest of the code using indentation. Syntax: for i in sequence: print(i)
  • 28. ITERATION Sequence can be a list, strings or tuples No. Sequences Example Output 1 for loop in string for in in “RAJA” print(i) R A J A 2. for loop in list for i in [2,3,5,6,9] print(i) 2 3 5 6 9 3. for loop in tuple for i in (2,3,1): print(i) 2 3 1
  • 29. ITERATION Nested for loop for inside another for is called nested for. Syntax for i in sequence: for j in sequence: statements statements Example: for i in range(1,4): for j in range(4,7): print(i*j) Output 4 5 6 8 10 12 12 15 18
  • 30. Assignments Programs 1. print nos divisible by 5 not by 10: 2. Program to print fibonacci series. 3. Program to find factors of a given number 4. check the given number is perfect number or not 5. check the no is prime or not 6. Print first n prime numbers 7. Program to print prime numbers in range
  • 31. LOOP CONTROL STRUCTURES 1.break 2.continue 3.pass 1.break To end a while loop prematurely, the break statement can be used. When encountered inside a loop, the break statement causes the loop to finish immediately. Syntax : break Flowchart while(test expression) if(condition): break Example i = 0 while 1==1: print(i) i = i + 1 if i >= 5: print("Breaking") break print("Finished") Output 0 1 2 3 4 Breaking Finished
  • 32. LOOP CONTROL STRUCTURES 2.continue It is unlike break, continue jumps back to the top of the loop, rather than stopping it. Another statement that can be used within loops is continue. Syntax : continue Flowchart while(test expression): if(condition): continue Example i = 0 while True: i = i +1 if i == 2: print("Skipping 2") continue if i == 5: print("Breaking") break print(i) print("Finished") Result: >>> 1 Skipping 2 3 4 Breaking Finished >>>
  • 33. LOOP CONTROL STRUCTURES 3.pass It is a null statement, nothing happens when it is executed. Syntax : pass for i in sequence: if(condition): pass Example for i in "welcome": if (i == "c"): pass print(i) Result: >>> w e l c o m e >>>
  • 34. SCOPE OF VARIABLES Global scope The scope of a variable refers to the places that you can see or access a variable. A variable with global scope can be used anywhere in the program. It can be created by defining a variable outside the function. Example a=50 #Global variable def add(): b=20 c=a+b print(c) def sub(): b=30 c=a-b print(c) add() sub() print(a) Result: >>> 70 20 50 >>>
  • 35. SCOPE OF VARIABLES Local scope A variable with local scope can be used only within the function . Example a=50 #global variable def add(): b=20 #local variable c=a+b print(c) def sub(): b=30 c=a-b print(c) add() sub() print(a) print(b) Result: >>> 70 20 50 error >>>
  • 36. FUNCTION COMPOSITION It is the ability to call one function from within another function It is a way of combining functions such that the result of each function is passed as the argument of the next function. The output of one function is given as the input of another function is known as function composition. Example def max(x, y): if x >=y: return x else: return y print(max(4, 7)) z = max(8, 5) print(z) Result: >>> 7 8 >>>
  • 37. RECURSION A function calling itself till it reaches the base value. #Factorial of a given number def fact(n): if(n==1): return 1 else: return n*fact(n-1) n=eval(input("enter no:")) fact=fact(n) print("Fact is",fact) Result: >>> enter no:5 Fact is 120 >>>
  • 38. STRINGS It is defined as sequence of characters represented either single quotes (' ') or double quotes (" "). An individual character in a string is accessed using a index. The index should always be an integer (positive or negative). An index starts from 0 to n-1. Strings are immutable i.e. the contents of the string cannot be changed after it is created. Python will get the input at run time by default as a string. Python does not support character data type. A string of size 1 can be treated as characters.
  • 39. STRINGS 1. single quotes (' ') 2. double quotes (" ") 3. triple quotes(""" """) Opération on strings 1.Indexing 2.Slicing 3.Concatenation 4.Repetions 5.Membership
  • 40. STRINGS Indexing >>>a= HELLO >>>print(a[0]) >>>H >>>print(a[-1]) >>>O Positive indexing helps in accessing the string from the beginning Negative subscript helps in accessing the string from the end. Slicing print a[0:4]-HELL print a[ :3]-HEL print a[0: ]-HELLO The Slice[start : stop] operator extracts sub string from the strings. A segment of a string is called a slice. Concatenation a= “tham” b=”man” >>>print(a+b) thamman + operator joins the text on both sides of the operator. Repetitions a= “RAJ” >>>print(3*a) RAJRAJRAJ * operator repeats the string. Membership >>> s="WELCOME" >>>"E" in s True >>> "a" not in s True Check a particular character is in string or not. Returns true if present.
  • 41. STRINGS Immutability Strings are immutable as they cannot be changed after they are created. [ ] operator cannot be used on the left side of an assignment. Element assignment A=“PYTHON” A[0]=‘X’ Element assignment error Element deletion A=“PYTHON” del A[0] Element deletion error Delete a string A=“PYTHON” del A print(A) A is not defined
  • 42. STRINGS String built-in functions and methods A method is a function that belongs to an object. Syntax: stringname.method(), a=“happy birthday” Syntax Example Description a.capitalize() >>> a.capitalize() ' Happy birthday capitalize only the first letter in a string a.upper() >>> a.upper() 'HAPPY BIRTHDAY change string to upper case a.lower() >>> a.lower() ' happy birthday change string to lower case a.title() >>> a.title() ' Happy Birthday ' change string to title case a.isupper() A= happy birthday >>> a.isupper() False whether letters are upper case or not a.islower() >>> a.islower() True whether letters are lower case or not len(a) >>>len(a) >>>14 length of the string
  • 43. STRING MODULES A module is a file containing python definitions, functions, statements. Standard library of python is extended as modules. Programmer needs to import the module. We can use to any of its functions or variables in our code. Large number of standard modules also available in python. Standard modules can be imported the same way as we import our user-defined modules. Syntax: import module_name
  • 45. ARRAY Array is a collection of similar elements. Elements in the array can be accessed by index. Index starts with 0. Array can be handled in python by module named array. To create array have to import array module in the program. Syntax : import array Syntax to create array: array_name = module_name.function_name( datatype ,[elements]) Example: a=array.array(i,[1,2,3,4]) a- array name array- module name i- integer datatype
  • 46. ARRAY Program to find sum of array elements import array sum=0 a=array.array('i',[1,2,3,4]) for i in a: sum=sum+i print(sum) Result: 10
  • 47. Convert LIST into ARRAY fromlist() function is used to append list to array. List is act like a array. Syntax: arrayname.fromlist(list_name) Example import array sum=0 l=[6,7,8,9] a=array.array('i',[]) a.fromlist(l) for i in a: sum=sum+i print(sum) Result: 35
  • 48. Methods in ARRAY a=[2,3,4,5] syntax: array(data type, value list) array(i, [2,3,4,5]) Syntax Example append() >>>a.append(6) [2,3,4,5,6] insert(index, element) >>>a.insert(2,10) [2,3,10,5,6] pop(index) >>>a.pop(1) [2,10,5,6] count() a.count() 4 reverse() >>>a.reverse() [6,5,10,2]
  • 49. Assignment 1.Square root using newtons method 2.GCD of two numbers 3.Exponent of number 4.Sum of array elements 5.Linear search 6.Binary search
  • 50. .