SlideShare a Scribd company logo
Python3 Beginner Workshop
“Talk is cheap. Show me the code.”
― Linus Torvalds
Himanshu Awasthi
B.Tech(VII Sem)
@himanshu230195
2
Agenda for todays workshop
• Numbers
• Strings
• List
• Tuples
• Dictionary
• Control statements - if/for
• functions
• in built functions
• classes
3
4
5
Lets dive into Python
Numbers :
Python supports integers, floating point numbers and complex
numbers. They are defined as int, float and complex class in Python.
Integers and floating points are separated by the presence or absence
of a decimal point. 5 is integer whereas 5.0 is a floating point number.
Complex numbers are written in the form, x + yj, where x is the real
part and y is the imaginary part.
We can use the type() function to know which class a variable or a
value belongs to and isinstance() function to check if it belongs to a
particular class.
6
Numbers
Open you terminal & start code :
>>> a=5
>>> type(a)
<class 'int'>
>>> type(5.0)
<class 'float'>
>>> c =5+3j
>>> c+3
(8+3j)
>>> isinstance(c,complex)
True
>>> type(c)
<class 'complex'>
7
Cont..
Number System Prefix
Binary ‘0b’ or ‘0B’
Octal ‘0o’ or ‘0O’
Hexadecimal ‘0x’ or ‘0X’
For eg :
>>> 0b1101011
107
>>> 0xFB + 0b10
253
>>> 0o15
13
8
Cont..
Type Conversion:
We can convert one type of number into another. This is also known as coercion.
We can also use built-in functions like int(), float() and complex() to convert between types explicitly.
For eg:
>>> int(2.3)
2
>>> int(-2.8)
-2
>>> float(5)
5.0
>>> complex('3+5j')
(3+5j)
When converting from float to integer, the number gets truncated (integer that is closer to zero).
9
Cont..
Python Decimal:
Python built-in class float performs some calculations that
might amaze us. We all know that the sum of 1.1 and 2.2 is
3.3, but Python seems to disagree.
>>> (1.1 + 2.2) == 3.3
False
10
Cont..
To overcome this issue, we can use decimal module that
comes with Python. While floating point numbers have
precision up to 15 decimal places, the decimal module has
user settable precision.
For eg:
>>> from decimal import Decimal
>>> print(Decimal('1.1')+Decimal('2.2'))
3.3
11
String
Strings are nothing but simple text. In Python we declare strings in between
“” or ‘’ or ‘” ‘” or “”” “””. The examples below will help you to understand
string in a better way.
>>> s = "I am Indian"
>>> s
'I am Indian'
>>> s = 'I am Indian'
>>> s
'I am Indian'
>>> s = "Here is a line
... splitted in two lines"
>>> s
'Here is a linesplitted in two lines'
12
Cont..
Now if you want to multiline strings you have to use triple
single/double quotes.
>>> s = """This is a
... multiline string, so you can
... write many lines"""
>>> print(s)
This is a
multiline string, so you can
write many lines
13
Cont..
Every string object is having couple of buildin methods available, we already saw
some of them like s.split(” ”).
>>> s = "Himanshu Awasthi"
>>> s.title()
'Himanshu Awasthi'
>>> z = s.upper()
>>> z
'HIMANSHU AWASTHI'
>>> z.lower()
'himanshu awasthi'
>>> s.swapcase()
'hIMANSHU aWASTHI'
14
Cont..
Lets practice :
isalnum()
isalpha()
isdigit()
islower()
split()
join()
len()
#Lets check Palindrome
15
List
We are going to learn a data structure called list. Lists can be written as
a list of comma-separated values (items) between square brackets.
>>>list = [ 1, 342, 2233423, 'Kanpur', 'python']
>>>a
[1, 342, 2233423, 'Kanpur', 'python']
Lets practice ^^
16
Cont..
Practice these inbuilt functions and keywords :
del
sort()
reverse()
remove()
count()
insert()
append()
17
Cont..
Using lists as stack and queue:
pop()
List Comprehensions:
For example if we want to make a list out of the square values of another list, then;
>>>a = [1, 2, 3]
>>>[x**2 for x in a]
[1, 4, 9]
>>>z = [x + 1 for x in [x**2 for x in a]]
>>>z
[2, 5, 10]
18
Touple
Tuples are data separated by comma.
>>> tuple = 'this', 'is' , 'kanpur' , 'tech' , 'community'
>>> tuple
('this', 'is', 'kanpur', 'tech', 'community')
>>> for x in tuple:
... print(x, end=' ')
...
this is kanpur tech community
Note :Tuples are immutable, that means you can not del/add/edit any
value inside the tuple
19
Dictionary
Dictionaries are unordered set of key: value pairs where keys are unique. We
declare dictionaries using {} braces. We use dictionaries to store data for any
particular key and then retrieve them.
>>> data = { 'himanshu':'python' , 'hitanshu':'designer' , 'hardeep':'wordpress'}
>>> data
{'hardeep': 'wordpress', 'hitanshu': 'designer', 'himanshu': 'python'}
>>> data['himanshu']
'python'
Lets practice Add/Del elements in dictionary
20
Cont..
dict() can create dictionaries from tuples of key,value pair.
>>> dict((('himanshu','python') , ('hardeep','wordpress')))
{'hardeep': 'wordpress', 'himanshu': 'python'}
If you want to loop through a dict use Iteritems() method.
In python3 we use only items()
>>> data
{'hardeep': 'wordpress', 'hitanshu': 'designer', 'himanshu': 'python'}
>>> for x , y in data.items():
... print("%s uses %s" % (x ,y))
...
hardeep uses wordpress
hitanshu uses designer
himanshu uses python
21
Cont..
You may also need to iterate through two sequences same time, for that use
zip() function.
Eg:
>>> name= ['ankit', 'hardeep']
>>> work= ['php' , 'wordpress']
>>> for x , y in zip(name , work):
... print("%s uses %s" % (x ,y))
...
ankit uses php
hardeep uses wordpress
22
Control statements
Lets practice :
If statement
Else statement
While loop
Eg : Fibonacci Series
Table multiplication
23
functions
Reusing the same code is required many times within a same program.
Functions help us to do so. We write the things we have to do repeatedly in a
function then call it where ever required.
Defining a function:
We use def keyword to define a function. General syntax is like
def functionname(params):
– statement1
– Statement2
– >>> def sum(a, b):
– ... return a + b
24
Cont..
Practice some functions example ;
Like factorial
>>> def fact(n):
... if n == 0:
... return 1
... return n* fact(n-1)
...
>>> print(fact(5))
120
How map & lambda works
25
classes
Classes provide a means of bundling data and functionality together.
We define a class in the following way :
class nameoftheclass(parent_class):
● statement1
● statement2
● statement3
●
>>> class MyClass(object):
… a = 90
… b = 88
...
>>>p = MyClass()
>>>p
<__main__.MyClass instance at 0xb7c8aa6c>
>>>dir(p)
26
Cont..
__init__ method:
__init__ is a special method in Python classes, it is the constructor method for a
class. In the following example you can see how to use it.
class Student(object):
– def __init__(self, name, branch, year):
● self.name = name
● self.branch = branch
● self.year = year
● print("A student object is created.")
– def print_details(self):
● print("Name:", self.name)
● print("Branch:", self.branch)
● print("Year:", self.year)
27
Cont..
>>> std1 = Student('Himanshu','CSE','2014')
A student object is created
>>>std1.print_details()
Name: Himanshu
Branch: CSE
Year: 2014
Lets take a look another example ;
28
Happy Coding
Thank you!

More Related Content

What's hot (20)

PDF
Python unit 2 M.sc cs
KALAISELVI P
 
PDF
Programming with matlab session 1
Infinity Tech Solutions
 
PPT
Lecture 15 - Array
Md. Imran Hossain Showrov
 
PPTX
16. Arrays Lists Stacks Queues
Intro C# Book
 
PPTX
Introduction to Python Programming
VijaySharma802
 
PPTX
C# Arrays
Hock Leng PUAH
 
PDF
C Programming Interview Questions
Gradeup
 
PPT
Java: Introduction to Arrays
Tareq Hasan
 
PDF
Matlab quickref
Arduino Aficionado
 
PDF
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
Philip Schwarz
 
PPTX
Computer Science Assignment Help
Programming Homework Help
 
PPT
Arrays
archikabhatia
 
PPTX
13. Java text processing
Intro C# Book
 
PPTX
Programming Homework Help
Programming Homework Help
 
PDF
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
Philip Schwarz
 
PDF
Monad Fact #4
Philip Schwarz
 
PPT
Arrays
Rahul Mahamuni
 
PPTX
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
PPTX
C# Strings
Hock Leng PUAH
 
Python unit 2 M.sc cs
KALAISELVI P
 
Programming with matlab session 1
Infinity Tech Solutions
 
Lecture 15 - Array
Md. Imran Hossain Showrov
 
16. Arrays Lists Stacks Queues
Intro C# Book
 
Introduction to Python Programming
VijaySharma802
 
C# Arrays
Hock Leng PUAH
 
C Programming Interview Questions
Gradeup
 
Java: Introduction to Arrays
Tareq Hasan
 
Matlab quickref
Arduino Aficionado
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
Philip Schwarz
 
Computer Science Assignment Help
Programming Homework Help
 
13. Java text processing
Intro C# Book
 
Programming Homework Help
Programming Homework Help
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
Philip Schwarz
 
Monad Fact #4
Philip Schwarz
 
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
C# Strings
Hock Leng PUAH
 

Similar to Python basics (20)

PDF
cel shading as PDF and Python description
MarcosLuis32
 
PPTX
Pythonlearn-02-Expressions123AdvanceLevel.pptx
AninditaSarkarNaha
 
PDF
03-Variables, Expressions and Statements (1).pdf
MirHazarKhan1
 
PPTX
matlab presentation fro engninering students
SyedSadiq73
 
PPTX
Keep it Stupidly Simple Introduce Python
SushJalai
 
PPTX
made it easy: python quick reference for beginners
SumanMadan4
 
PPTX
PPT_1_9102501a-a7a1-493e-818f-cf699918bbf6.pptx
myatminsoe180
 
PPTX
世预赛买球-世预赛买球竞彩平台-世预赛买球竞猜平台|【​网址​🎉ac123.net🎉​】
hanniaarias53
 
PPTX
美洲杯买球-美洲杯买球怎么押注-美洲杯买球押注怎么玩|【​网址​🎉ac99.net🎉​】
kokoparmod677
 
PPTX
欧洲杯足彩-欧洲杯足彩线上体育买球-欧洲杯足彩买球推荐网站|【​网址​🎉ac55.net🎉​】
brunasordi905
 
PPTX
欧洲杯下注-欧洲杯下注买球网-欧洲杯下注买球网站|【​网址​🎉ac10.net🎉​】
brendonbrash97589
 
PPTX
世预赛买球-世预赛买球比赛投注-世预赛买球比赛投注官网|【​网址​🎉ac10.net🎉​】
bljeremy734
 
PPTX
世预赛投注-世预赛投注投注官网app-世预赛投注官网app下载|【​网址​🎉ac123.net🎉​】
bljeremy734
 
PPTX
欧洲杯体彩-欧洲杯体彩比赛投注-欧洲杯体彩比赛投注官网|【​网址​🎉ac99.net🎉​】
lopezkatherina914
 
PPTX
欧洲杯买球-欧洲杯买球投注网-欧洲杯买球投注网站|【​网址​🎉ac44.net🎉​】
rodriguezkiko995
 
PPTX
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
PDF
Introduction To Programming with Python
Sushant Mane
 
PPTX
Improve Your Edge on Machine Learning - Day 1.pptx
CatherineVania1
 
PDF
Get started python programming part 1
Nicholas I
 
PPTX
Chapter 2-Python and control flow statement.pptx
atharvdeshpande20
 
cel shading as PDF and Python description
MarcosLuis32
 
Pythonlearn-02-Expressions123AdvanceLevel.pptx
AninditaSarkarNaha
 
03-Variables, Expressions and Statements (1).pdf
MirHazarKhan1
 
matlab presentation fro engninering students
SyedSadiq73
 
Keep it Stupidly Simple Introduce Python
SushJalai
 
made it easy: python quick reference for beginners
SumanMadan4
 
PPT_1_9102501a-a7a1-493e-818f-cf699918bbf6.pptx
myatminsoe180
 
世预赛买球-世预赛买球竞彩平台-世预赛买球竞猜平台|【​网址​🎉ac123.net🎉​】
hanniaarias53
 
美洲杯买球-美洲杯买球怎么押注-美洲杯买球押注怎么玩|【​网址​🎉ac99.net🎉​】
kokoparmod677
 
欧洲杯足彩-欧洲杯足彩线上体育买球-欧洲杯足彩买球推荐网站|【​网址​🎉ac55.net🎉​】
brunasordi905
 
欧洲杯下注-欧洲杯下注买球网-欧洲杯下注买球网站|【​网址​🎉ac10.net🎉​】
brendonbrash97589
 
世预赛买球-世预赛买球比赛投注-世预赛买球比赛投注官网|【​网址​🎉ac10.net🎉​】
bljeremy734
 
世预赛投注-世预赛投注投注官网app-世预赛投注官网app下载|【​网址​🎉ac123.net🎉​】
bljeremy734
 
欧洲杯体彩-欧洲杯体彩比赛投注-欧洲杯体彩比赛投注官网|【​网址​🎉ac99.net🎉​】
lopezkatherina914
 
欧洲杯买球-欧洲杯买球投注网-欧洲杯买球投注网站|【​网址​🎉ac44.net🎉​】
rodriguezkiko995
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
Introduction To Programming with Python
Sushant Mane
 
Improve Your Edge on Machine Learning - Day 1.pptx
CatherineVania1
 
Get started python programming part 1
Nicholas I
 
Chapter 2-Python and control flow statement.pptx
atharvdeshpande20
 
Ad

More from Himanshu Awasthi (9)

PDF
RoadMap to Cyber Certs.pdf
Himanshu Awasthi
 
ODP
Introduction to web design
Himanshu Awasthi
 
ODP
Data analysis using python
Himanshu Awasthi
 
ODP
Kanpur Python Users Group
Himanshu Awasthi
 
ODP
Crpto unit1
Himanshu Awasthi
 
ODP
Intro to python
Himanshu Awasthi
 
PPTX
Software unit4
Himanshu Awasthi
 
ODP
Software design
Himanshu Awasthi
 
ODP
DomainNameSystem
Himanshu Awasthi
 
RoadMap to Cyber Certs.pdf
Himanshu Awasthi
 
Introduction to web design
Himanshu Awasthi
 
Data analysis using python
Himanshu Awasthi
 
Kanpur Python Users Group
Himanshu Awasthi
 
Crpto unit1
Himanshu Awasthi
 
Intro to python
Himanshu Awasthi
 
Software unit4
Himanshu Awasthi
 
Software design
Himanshu Awasthi
 
DomainNameSystem
Himanshu Awasthi
 
Ad

Recently uploaded (20)

PPTX
ManageIQ - Sprint 264 Review - Slide Deck
ManageIQ
 
PPTX
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
 
PDF
Rewards and Recognition (2).pdf
ethan Talor
 
PDF
WholeClear Split vCard Software for Split large vCard file
markwillsonmw004
 
PDF
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 
PPTX
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
 
PDF
Dealing with JSON in the relational world
Andres Almiray
 
PDF
TEASMA: A Practical Methodology for Test Adequacy Assessment of Deep Neural N...
Lionel Briand
 
PPTX
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
 
PPTX
CONCEPT OF PROGRAMMING in language .pptx
tamim41
 
PPTX
NeuroStrata: Harnessing Neuro-Symbolic Paradigms for Improved Testability and...
Ivan Ruchkin
 
PDF
Telemedicine App Development_ Key Factors to Consider for Your Healthcare Ven...
Mobilityinfotech
 
PDF
Difference Between Kubernetes and Docker .pdf
Kindlebit Solutions
 
PPTX
For my supp to finally picking supp that work
necas19388
 
PDF
capitulando la keynote de GrafanaCON 2025 - Madrid
Imma Valls Bernaus
 
PDF
Writing Maintainable Playwright Tests with Ease
Shubham Joshi
 
PDF
>Nitro Pro Crack 14.36.1.0 + Keygen Free Download [Latest]
utfefguu
 
PDF
Automated Test Case Repair Using Language Models
Lionel Briand
 
PDF
>Wondershare Filmora Crack Free Download 2025
utfefguu
 
PPTX
ERP - FICO Presentation BY BSL BOKARO STEEL LIMITED.pptx
ravisranjan
 
ManageIQ - Sprint 264 Review - Slide Deck
ManageIQ
 
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
 
Rewards and Recognition (2).pdf
ethan Talor
 
WholeClear Split vCard Software for Split large vCard file
markwillsonmw004
 
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
 
Dealing with JSON in the relational world
Andres Almiray
 
TEASMA: A Practical Methodology for Test Adequacy Assessment of Deep Neural N...
Lionel Briand
 
Wondershare Filmora Crack 14.5.18 + Key Full Download [Latest 2025]
HyperPc soft
 
CONCEPT OF PROGRAMMING in language .pptx
tamim41
 
NeuroStrata: Harnessing Neuro-Symbolic Paradigms for Improved Testability and...
Ivan Ruchkin
 
Telemedicine App Development_ Key Factors to Consider for Your Healthcare Ven...
Mobilityinfotech
 
Difference Between Kubernetes and Docker .pdf
Kindlebit Solutions
 
For my supp to finally picking supp that work
necas19388
 
capitulando la keynote de GrafanaCON 2025 - Madrid
Imma Valls Bernaus
 
Writing Maintainable Playwright Tests with Ease
Shubham Joshi
 
>Nitro Pro Crack 14.36.1.0 + Keygen Free Download [Latest]
utfefguu
 
Automated Test Case Repair Using Language Models
Lionel Briand
 
>Wondershare Filmora Crack Free Download 2025
utfefguu
 
ERP - FICO Presentation BY BSL BOKARO STEEL LIMITED.pptx
ravisranjan
 

Python basics

  • 1. Python3 Beginner Workshop “Talk is cheap. Show me the code.” ― Linus Torvalds Himanshu Awasthi B.Tech(VII Sem) @himanshu230195
  • 2. 2 Agenda for todays workshop • Numbers • Strings • List • Tuples • Dictionary • Control statements - if/for • functions • in built functions • classes
  • 3. 3
  • 4. 4
  • 5. 5 Lets dive into Python Numbers : Python supports integers, floating point numbers and complex numbers. They are defined as int, float and complex class in Python. Integers and floating points are separated by the presence or absence of a decimal point. 5 is integer whereas 5.0 is a floating point number. Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part. We can use the type() function to know which class a variable or a value belongs to and isinstance() function to check if it belongs to a particular class.
  • 6. 6 Numbers Open you terminal & start code : >>> a=5 >>> type(a) <class 'int'> >>> type(5.0) <class 'float'> >>> c =5+3j >>> c+3 (8+3j) >>> isinstance(c,complex) True >>> type(c) <class 'complex'>
  • 7. 7 Cont.. Number System Prefix Binary ‘0b’ or ‘0B’ Octal ‘0o’ or ‘0O’ Hexadecimal ‘0x’ or ‘0X’ For eg : >>> 0b1101011 107 >>> 0xFB + 0b10 253 >>> 0o15 13
  • 8. 8 Cont.. Type Conversion: We can convert one type of number into another. This is also known as coercion. We can also use built-in functions like int(), float() and complex() to convert between types explicitly. For eg: >>> int(2.3) 2 >>> int(-2.8) -2 >>> float(5) 5.0 >>> complex('3+5j') (3+5j) When converting from float to integer, the number gets truncated (integer that is closer to zero).
  • 9. 9 Cont.. Python Decimal: Python built-in class float performs some calculations that might amaze us. We all know that the sum of 1.1 and 2.2 is 3.3, but Python seems to disagree. >>> (1.1 + 2.2) == 3.3 False
  • 10. 10 Cont.. To overcome this issue, we can use decimal module that comes with Python. While floating point numbers have precision up to 15 decimal places, the decimal module has user settable precision. For eg: >>> from decimal import Decimal >>> print(Decimal('1.1')+Decimal('2.2')) 3.3
  • 11. 11 String Strings are nothing but simple text. In Python we declare strings in between “” or ‘’ or ‘” ‘” or “”” “””. The examples below will help you to understand string in a better way. >>> s = "I am Indian" >>> s 'I am Indian' >>> s = 'I am Indian' >>> s 'I am Indian' >>> s = "Here is a line ... splitted in two lines" >>> s 'Here is a linesplitted in two lines'
  • 12. 12 Cont.. Now if you want to multiline strings you have to use triple single/double quotes. >>> s = """This is a ... multiline string, so you can ... write many lines""" >>> print(s) This is a multiline string, so you can write many lines
  • 13. 13 Cont.. Every string object is having couple of buildin methods available, we already saw some of them like s.split(” ”). >>> s = "Himanshu Awasthi" >>> s.title() 'Himanshu Awasthi' >>> z = s.upper() >>> z 'HIMANSHU AWASTHI' >>> z.lower() 'himanshu awasthi' >>> s.swapcase() 'hIMANSHU aWASTHI'
  • 15. 15 List We are going to learn a data structure called list. Lists can be written as a list of comma-separated values (items) between square brackets. >>>list = [ 1, 342, 2233423, 'Kanpur', 'python'] >>>a [1, 342, 2233423, 'Kanpur', 'python'] Lets practice ^^
  • 16. 16 Cont.. Practice these inbuilt functions and keywords : del sort() reverse() remove() count() insert() append()
  • 17. 17 Cont.. Using lists as stack and queue: pop() List Comprehensions: For example if we want to make a list out of the square values of another list, then; >>>a = [1, 2, 3] >>>[x**2 for x in a] [1, 4, 9] >>>z = [x + 1 for x in [x**2 for x in a]] >>>z [2, 5, 10]
  • 18. 18 Touple Tuples are data separated by comma. >>> tuple = 'this', 'is' , 'kanpur' , 'tech' , 'community' >>> tuple ('this', 'is', 'kanpur', 'tech', 'community') >>> for x in tuple: ... print(x, end=' ') ... this is kanpur tech community Note :Tuples are immutable, that means you can not del/add/edit any value inside the tuple
  • 19. 19 Dictionary Dictionaries are unordered set of key: value pairs where keys are unique. We declare dictionaries using {} braces. We use dictionaries to store data for any particular key and then retrieve them. >>> data = { 'himanshu':'python' , 'hitanshu':'designer' , 'hardeep':'wordpress'} >>> data {'hardeep': 'wordpress', 'hitanshu': 'designer', 'himanshu': 'python'} >>> data['himanshu'] 'python' Lets practice Add/Del elements in dictionary
  • 20. 20 Cont.. dict() can create dictionaries from tuples of key,value pair. >>> dict((('himanshu','python') , ('hardeep','wordpress'))) {'hardeep': 'wordpress', 'himanshu': 'python'} If you want to loop through a dict use Iteritems() method. In python3 we use only items() >>> data {'hardeep': 'wordpress', 'hitanshu': 'designer', 'himanshu': 'python'} >>> for x , y in data.items(): ... print("%s uses %s" % (x ,y)) ... hardeep uses wordpress hitanshu uses designer himanshu uses python
  • 21. 21 Cont.. You may also need to iterate through two sequences same time, for that use zip() function. Eg: >>> name= ['ankit', 'hardeep'] >>> work= ['php' , 'wordpress'] >>> for x , y in zip(name , work): ... print("%s uses %s" % (x ,y)) ... ankit uses php hardeep uses wordpress
  • 22. 22 Control statements Lets practice : If statement Else statement While loop Eg : Fibonacci Series Table multiplication
  • 23. 23 functions Reusing the same code is required many times within a same program. Functions help us to do so. We write the things we have to do repeatedly in a function then call it where ever required. Defining a function: We use def keyword to define a function. General syntax is like def functionname(params): – statement1 – Statement2 – >>> def sum(a, b): – ... return a + b
  • 24. 24 Cont.. Practice some functions example ; Like factorial >>> def fact(n): ... if n == 0: ... return 1 ... return n* fact(n-1) ... >>> print(fact(5)) 120 How map & lambda works
  • 25. 25 classes Classes provide a means of bundling data and functionality together. We define a class in the following way : class nameoftheclass(parent_class): ● statement1 ● statement2 ● statement3 ● >>> class MyClass(object): … a = 90 … b = 88 ... >>>p = MyClass() >>>p <__main__.MyClass instance at 0xb7c8aa6c> >>>dir(p)
  • 26. 26 Cont.. __init__ method: __init__ is a special method in Python classes, it is the constructor method for a class. In the following example you can see how to use it. class Student(object): – def __init__(self, name, branch, year): ● self.name = name ● self.branch = branch ● self.year = year ● print("A student object is created.") – def print_details(self): ● print("Name:", self.name) ● print("Branch:", self.branch) ● print("Year:", self.year)
  • 27. 27 Cont.. >>> std1 = Student('Himanshu','CSE','2014') A student object is created >>>std1.print_details() Name: Himanshu Branch: CSE Year: 2014 Lets take a look another example ;