Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
107 views

Blog Python Tutorial For Beginners A Complete Guide

This document provides a tutorial for learning Python programming for beginners. It discusses what Python is and what it is used for, how to install Python, why Python is a good choice for learning programming, and the differences between Python and R. It also covers popular integrated development environments for Python, how to set up and use Jupyter notebooks, and various Python programming concepts and techniques for beginners to learn.

Uploaded by

Saikiran Sn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
107 views

Blog Python Tutorial For Beginners A Complete Guide

This document provides a tutorial for learning Python programming for beginners. It discusses what Python is and what it is used for, how to install Python, why Python is a good choice for learning programming, and the differences between Python and R. It also covers popular integrated development environments for Python, how to set up and use Jupyter notebooks, and various Python programming concepts and techniques for beginners to learn.

Uploaded by

Saikiran Sn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Ho me  Business Analyt ics  Analyt ics Tut o rials  Pyt ho n Tut o rial Fo r Beginners – A Co mplet e
Guide | Learn Pyt ho n Easily

Business Analytics Analytics Tutorials Artificial Intelligence Data Science Videos Data Science Videos

DS Tutorials Machine Learning Learn Python Python Programming Language Tutorials

Python Tutorial For Beginners –


A Complete Guide | Learn
Python Easily
By G r e a t Le a r ning T e a m - Ju n 22, 20 21  49 314

1. What is Python?

2. What is Python used f or?

3. How to Install Python?

4. Why Python?

5. R vs. Python

6. Best Way to Learn Python

7. What are the top Python IDEs

8. Which is the best IDE f or Python?

9. How to power Jupyter Notebook?

10. Functionalities in a Python Notebook (Jupyter)

11. Comments

12. Variables

13. Operators

14. Arithmetic Operators

15. Assignment Operators

16. Comparison Operators

17. Logical Operators

18. Identity Operators

19. Membership Operators

20. Bitwise Operators

21. T ernary Operator

22. Lambda

23. Arrays

24. Classes

25. Inheritance

26. Iterators

27. Scope

28. Modules

29. Dates

30. Random Number Generator in Python

31. JSON

32. Regular Expression

33. PIP

34. T ry, Except


35. User Input

36. String Formatting

37. Python Data T ypes

38. Flow Control Statements

39. File Handling

40. Creating Functions in Python

41. Learn Simple Commands by Using Python as a Calculator

42. Data Manipulation with Pandas

43. Python FAQs

Learn the high demand technologies in a world-class learning platform for free

What is Python ?
Contributed by – python.learning

Python is a high-level, object-oriented programming language. Most beginners


in the development f ield pref er Python as one of the f irst languages to learn
because of its simplicity and versatility. It is also well supported by the
community and keeps up with its increasing popularity. In this Python T utorial
f or beginners, we will learn the basics of Python as a programming language,
and understand how to get started with it. We will see how to download and
install Python and use the popular IDEs to begin coding. We will also discuss
jupyter f unctionality in detail.

What is Python used for?


Next time you are browsing through Google, indulging in your daily dose of
Instagram, spending hours watching videos on Youtube, or listening to your
f avourite music on Spotif y, remember that all of them use Python f or their
programming needs. Python has various uses across applications, platf orms,
and services. Let us talk about a f ew here.

Web Development

T he large selection of pre-built Python libraries makes web development a


much simpler task. Writing a Python code is less time-consuming due to its
clean and simple syntax. T his helps with quick prototyping accelerating the ROI
of commercial products. T he built-in testing f rameworks help in shipping bug-
f ree codes. A large selection of well-supported f rameworks help in f acilitating
speedy implementation without compromising on the perf ormance of the
solution.

Internet of Things
For the sake of simplicity, let us consider the Internet of T hings to be the
‘physical objects connecting an embedded system to the internet’. It plays a
vital role in projects that involve big dat a, machine learning, dat a
analyt ics, wireless dat a net works, and cyber-physical syst ems. IoT
projects also deal with real-time analytics.

A programming language should be a bold choice keeping in mind the


af orementioned f ields of application. T his is where Python ticks of f all the
check-boxes. Additionally, Python is also scalable, expandable, portable, and
embeddable. T his makes Python system-independent and allows it to
accommodate multiple single board computers, irrespective of the operating
system or architecture.

Also, Python is excellent f or managing and organising complex data. It is


particularly usef ul f or IoT systems that are data-heavy. Another reason f or
Python to be the ideal programming language f or IoT applications is its close
relation with scientif ic computing.

Everything Python
Let’s help you explore Python more!

Are you looking f or career guiding art icles in Pyt hon? 👇


Pyt hon Int erview Quest ions and Answers

Pyt hon Developer Resume Samples

Pyt hon Developer Salary In India

OR

Are you looking f or Knowledge art icles in Pyt hon?

Append in Pyt hon

Fact orial Program in Pyt hon

Fibonacci Series in Pyt hon

Pat t ern Program in Pyt hon

Palindrome in Pyt hon

Machine Learning

Machine Learning has of f ered a whole new approach to problem-solving.


Python is at the f oref ront of Machine Learning and Data Science due to the
f ollowing reasons:

Extensive open-source library support

Ef f icient and precise syntax

Easy integration with other programming languages

Python has a low entry-point

Scalable to dif f erent operating systems and architectures

Here is a Python T utorial video f or you by Great Learning.


How to Install Python?

If you are a Windows user and if you have installed Python using Anaconda
distribution package which is available at Anaconda.org, you need to go to
“Download Anaconda” and then download the latest version f or Python 3.6.

Once you download this, it is a pretty simple and straightf orward process to
f ollow, and you will have Python installed f or you. T he next step is to power up
an IDE to start coding in Python.

So once you install Python, you can have multiple IDEs or text editors on top of
your Python installation.

For text editors, you can use something like Sublime or Notepad++. If you are
comf ortable using an Integrated Development Environment, then you can use
Jupyter. Also, there are other options like Wingware, Komodo, Pycharm, and
Spyder.

T here are multiple packages available in Python. Some of the instrumental


libraries are numpy, pandas, seaborn f or visualisation and scipy f or calculations
and statistics. Others are xlrb, openpyxl, matplotlib, and io.

Why to Choose Python?


You Should Choose this because Python has become the most pref erred
programming language f or enabling data science and machine learning
applications. Of course, Python has its advantages; it is swif t as compared to
other programming languages, even R f or that matter.

We can easily say that Python is a swif t compiler. Since it is a Java-based


programming language, you will be able to extend its applications beyond
analytical research, analytical modelling, and statistical modelling. You will be
able to create web applications using Python and integrate these web
applications directly to your analytical models in the background.

Python is also very easy to integrate with other platf orms and other
programming languages. It has a common object-oriented programming
architecture wherein existing IT developers, IT analysts, and IT programmers
f ind it very easy to transition to the analytics domain.
Because the structure of coding in Python is object-oriented programing
architecture, it has excellent documentation support.

7 Reasons Why You Should Use Python

1. Readable and Maintainable Code

2. Multiple Programming Paradigms

3. Compatible with Major Platf orms and Systems

4. Robust Standard Library

5. Open Source Frameworks and T ools

6. Simplif ied Sof tware Development


7. T est-Driven Development

R vs Python?

R was developed f or statistical analysis applications; on the other hand; Python


was developed as a general-purpose programming language. Both of these are
essential f or those who work with large data-sets, solve machine learning
problems, and create complex data visualizations.

Let us have a look at the dif f erences between R and Python

Read more about the dif f erence between R and Python, and which is a better
alternative.

Best Way to Learn Python?


T he ease of learning is the main attribute behind Python’s popularity. It is a
simple and type f ree programming language and hence easy to learn. T he time
taken to learn the language depends on the level you want to achieve with
Python. Also, the learning curve could be shorter or longer depending on
individual ability.

One would require 6-8 weeks to learn the basics of Python. T his will include
learning the syntax, key-words, f unctions and classes, data types, basic coding,
and exception handling.

Advanced Python skills are not necessary f or all Python prof essionals.
Depending on the nature of your work, you can learn skills such as database
programming, socket programming, multithreading, synchronisation techniques
etc.

T he highly sophisticated Python skills include concepts of Data Analytics,


hands-on experience of the required libraries, image processing etc. Each of
the specialised skill would need around one week to master.

Read our blog on top 50 interview questions f or Python to test your knowledge.
It will give you an idea about how much you know about Python and what else is
there to learn.

What are the top Python IDEs?


T here are 7 top IDE’s f or Python
1. Spyder

2. PyCharm

3. T honny

4. Atom

5. Jupyter

6. Komodo

7. Wingware

Which is the best IDE for Python?


Jupyter is the best IDE f or Python and one of the most widely used IDE f or
Python. Let us have a look at how to set-up the Jupyter Notebook. Also, let us
see what the f unctionalities of a Jupyter Notebook.

How to Power Jupyter Notebook


Below are the guided steps to power up a Jupyter notebook:

1. Open the Anaconda prompt. T his is available to you if you have done the
installation through the Anaconda installer. 

2. Once you open the Anaconda Command Prompt, you will see a def ault path
assigned to you. T his is the username f or the computer that you are using.

3. Add the f older paths to this def ault path (e.g., cd Desktop → cd Python),
where you want to open the notebook

4. Once you set the path, add the Jupyter notebook using the command
jupyt er not ebook

5. Hit enter. T his will open the notebook in your local host, i.e., your system

6. T he path described in the Anaconda prompt will now come on your jupyter
notebook home page

7. Next step is to open a new Python Notebook. T his is your environment to


carry out all the coding. You can rename the new notebook (untitled) to
what you want and hit ‘rename’.
Keep the anaconda prompt active, the one which you used to power up your
Jupyter notebook, while you are working with your Jupyter in your local. If the
anaconda prompt is closed, the python is no longer running on your system,
and the kernel gets disconnected.

Functionalities in a Python Notebook


(Jupyter)

T here are multiple options on the toolbar, i.e., File, Edit , View, Insert , Cell,
Kernel, Widget s and Help. Let us have a look at some of the f eatures and
f unctionalities one by one.

File Options

Save and Checkpoint – Setting a Checkpoint is a f ascinating concept. T he f ile


is Autosaved at regular intervals, and by setting a check-point, you can skip
back a f ew auto-saves to the set checkpoint. T his helps in case you made a
mistake in the past couple of minutes or hours. You can always revert to a more
stable checkpoint and proceed with your code f rom there, rather than starting
f rom scratch. 

Download as – T here are dif f erent ways in which you can download a Jupyter
Notebook. First is the Classic Notebook, which is the ipynb extension. Bef ore
being called a jupyter notebook, it was an Ipython notebook. T hat is why this
extension.

T hen you have your .py extension. Save the f ile with .py extension, and you can
import the same to a dif f erent IDE f or easier use. 

Close and Halt – T his command closes whatever kernel is running at this
particular point in time and halts all the processes.

Edit Options
It includes Cut Cells, Copy Cells, Past e, Delet e, Split t ing a Cell, Moving up,
down, so on and so f orth.

So, What is a cell?

Cells are nothing but the code that you type in the dialogue box present on the
window. T his is a cell, where you type in your code — each cell when run will give
you an output.

T o run this particular piece of code, you can either click the specif ic option
which says, Run cell or the shortcut key f or the same is Shift + Ent er. 

If you want to explore the other available shortcut options, you can get under
Help in Keyboard Short cut s. 

You can cut these cells, paste them later on. You can merge, split, so
on and so forth. T hese are simple items.

View Options

You can T oggle your Headers, T oolbars, and Line numbers as well. 

Insert Options

T hese are basic insert operations. You can insert a cell above or below as per
the requirement of your code. 

Cell Options

If you hit Run All, it runs all the cells that are present in this entire workbook.
When you click ‘Run All Above’, it runs all the cells above the selected cell.
Similarly, if you click ‘Run All Below’, it runs all the cells that are below the
selected cell.

T he dif f erent types of cells, i.e., Code, Markdown and Raw Convert Files.

One exciting f eature that we will be using much in our code f iles is something
called Markdown f ile. A markdown is nothing but converting whatever you have
typed in a cell into a text message.

T he cells that you have converted as a Markdown will not be run or considered
as a line of code. When you run this cell, it is taken as a text f ield, and the
output is text too. No computation is carried out on this cell.

Help Options

Here you can see the usual libraries and packages that are available.

You can click on these options, and it will open a guidebook or the ref erence
book, where you can have a look at the various methods that are available
within the selected package.
T here are various other options you can experiment with when you are working
with Jupyter.

Comments
Comments are usef ul to describe the program logic and purpose of various
modules.  People other than the coder can understand the code by looking into
the meaningf ul comments.

While testing the program, comments can be used to disable portions of code
and are excluded f rom execution.

Python comment starts with the # symbol.  T he comment may be its own or
the comment may start af ter a code in the same line.  Both cases are explained
in the below image.

# comment in separate line


x=x*5

x = x * 5 # multiply by 5; comment in same line

# this f unction is going to divide two variables

# the second value should not be zero

# if it is zero, error is thrown

def divide(f irst, second):

T here is no dif f erent way to mention multiline comments.  # can be added to


dif f erent lines.

When # is placed inside quotes, then it is part of the string and not a comment.

For example,

str = "# hello world"

Variables
Python variables are containers to hold data.  T hese assigned data value to a
variable can be changed at a later stage.

T he f irst assignment of value to a variable creates the variable.  T here is no


explicit declaration of variable.

numOf Boxes = 7
ownerName = "Karthik"

print("numOf Boxes= ", numOf Boxes)

print("ownerName= ", ownerName)

In the above example, two variables with numeric and string data are created. 
Print statements are used to display those variables.

Variable names f ollow these conventions.

Variable name begins with letter or underscore character

Alpha-numeric and underscores are allowed in the rest of name

Variable names are case-sensitive

# valid names

numOf Boxes = 7
_num_of _boxes = 10 # this is a dif f erent variable than numOf Boxes

_NUM_OF_BOXES = 15 # a dif f erent variable as names are case sensitive

ownerName = "Karthik"

ownerName2 = "Charan" # dif f erent, valid variable

# invalid names

2ownerName = "David" # cannot start with number.

# Only letter or underscore in the beginning


owner-name = "Ram" # no hypen

owner name = "Krish" # no space allowed

# only alpha numeric and underscore

Here we have listed out some of the possible variable names and f ew invalid
names.

In python, you can assign multiple values to many variables.  Also assign the
same value to multiple variables. Please see this example.

# dif f erent values assigned to many variables

length, width, depth = 5, 8, 7


print(length)

print(width)

print(depth)

# same value assigned to many variables

length = width = depth = 5


print(length)

print(width)

print(depth)

Operators
Contributed by – papaprogrammer

Operators help in processing variables and values.  For example, if we can two
numeric variables, they can be added or subtracted, multiplied or divided. 
T hese operations change the value and give out new values.

Python supports the f ollowing categories of operators.

Arithmetic operators

Assignment operators

Comparison operators

Logical operators

Identity operators

Membership operators

Bitwise operators

 Arithmetic operators
Mathematical operations like addition, subtraction are perf ormed using
arithmetic operators.  Let us go through them.

a = 10
b= 6

print (a + b) # addition

print (a - b) # subtraction

print (a * b) # multiplication
print (a / b) # division

print (a % b) # modulus
print (a ** b) # exponentiation

print (a // b) # f loor division

All the operations are easy to understand.  Modulus operation returns the
remainder of dividing two numbers (in our example, 4 is the reminder).  Similarly,
f loor division is integer division, which returns the result of division as whole
integer (10 // 6 = 1).

Assignment operators
Values or variable content can be assigned to another variable using
assignment operators.  T he right-hand side can also be an expression
(assignment to c in the f ollowing example). Here are a f ew examples.

a = 7 # assign value to a
b = a # assign value of a into b

c = a + b -2 # calculate an expression and place result into c

b += 2 # equivalent to b = b + 2
b -= 2 # equivalent to b = b - 2

b *= 2 # equivalent to b = b * 2
b /= 2 # equivalent to b = b / 2

b %= 2 # equivalent to b = b % 2
b //= 2 # equivalent to b = b // 2

b **= 2 # equivalent to b = b ** 2

b &= 2 # equivalent to b = b & 2


b |= 2 # equivalent to b = b | 2

b ^= 2 # equivalent to b = b ^ 2

b >>= 2 # equivalent to b = b >> 2

b <<= 2 # equivalent to b = b << 2

T he last f ive operators will be explained in the later section below.

Comparison operators
T wo values are compared and the result is a Boolean value T rue or False.  Used
in if and loop statements to make decisions.

a= 3

b= 7

print(a == b) # true if a and b are equal


print(a != b) # true if a and b are not equal
print(a > b) # true if a is greater than b

print(a < b) # true if a is less than b

print(a >= b) # true if a is greater than or equal to b

print(a <= b) # true if a is less than or equal to b

Let us see an example of comparison in action.  Here we check if a is less than b.


IF this condition is true, execute a statement.  Otherwise execute a dif f erent
statement.

a= 3

b= 7

if (a < b):
print("f irst number is less than second one");
else:

print("f irst number is greater than or equal to second one")

Logical operators
T wo or more comparison operations can be combined using logical operators. 
T hese logical operators return Boolean value.

a= 5

b= 8

# T rue if both conditions are true


print(a > 3 and a < 7)

# T rue if one condition is true

print(a > 6 or b < 7)

# T rue if given condition is f alse (inverse of given condition)

print(not(a > 3))

Identity operators
Identity operators compare if two objects are the same.  T hey need to point to
the same location.

a = ["hello", "world"]
b = ["hello", "world"]
c=a

# prints true as both are same element


print(a is c)

# prints f alse as they are two dif f ent values

# content may be same, but value locations are dif f erent

print(a is b)

# comparing the values gives true

print(a == b)

# not negates the comparison result

# if two variables are not same, then result is true

print(a is not c)

print(a is not b)

Membership operators
Checks if an element is present in a given list.

a = ["hello", "world"]

# checks if given element is present in the a list


print("world" in a)

# checks if given element is not present in the a list


print("world" not in a)

Bitwise operators
While dealing with binary numbers, we need bitwise operators to manipulate
them.  Binary numbers are zeros and ones, which are named as bits.

a = 1 # binary equivalent of 1 is 1
b = 2 # binary equivalent of 2 is 10

# In case of AND(&) operation, if both bits are 1, set result to one

# in our case, two corresponding bits are not 1

# so, corresponding result is 0

print(a & b)

# OR operation (|), gives 1 if either operands are 1

# T he reult of 0 and 1 is 1, 1 and 0 is 1

# hence, a | b gives binary 11 or decimal equivalent of 3

print(a | b)

# XOR (^) returns 1 if only one of the operands is 1

# 1 ^ 1 = 0, 0 ^ 0 = 0, 1 ^ 0 = 1, 0 ^ 1 = 1

# considering a and b, they have only ones in each bit position

print(a ^ b)

# NOT operation negates the bit value

# NOT 0 = 1, NOT 1 = 0
# while negating b, all preceeding zeros are turned to one
# this leads to a negative number

print(~ b)

# zero f ill lef t shif t (<<)

# zeros are f illed f rom right, bits are shif ted to lef t

# lef t most bits f all of f

# in this example, we shif t the bits of b twice

# 10 (b) shif ted twice is 1000 (which is decimal 8)

print(b << 2)

# signed right shif t (>>)

# shif t the bits to the right, copy lef tmost bits to the right
# right most bits f all of f
# when we shif t b (10) once to the right, it becomes 1
print(b >> 1)

Ternary Operator
Int roduct ion Pyt hon T ernary Operat or

We all know the dif f erent operators in python, i.e., Unary operators and Binary
operators.

An operator that can be used to negate a positive value with one operand is
called the unary operator; f or example, x = -4, here we are negating a value 4
with operator –, so operator —  acts as a unary operator.

An operator who works with two operands is called a binary operator; f or


example, x =, 3+7, the operator + acts as a binary operator.

T he operator +,- acts as both Unary and Binary operators.

Now we know what the Unary and Binary operator is, so what is this ternary
operator? Guess what? Yes, you are correct; an operator that works with three
operands (components) is called a ternary operator.

T he dictionary meaning of ternary is “composed of three items”, the operator


evaluates something based on a condition, and the result is the true_value if
the condition evaluates to T RUE else the result is the f alse_value.

T he three components are (1) A condition (2) T rue value (3) False value.

Let’s write a simple if condition that evaluates a person’s age and tells whether
the person is major or minor.
Age = 21
if (Age > 18):

print("Major")

else:

print("Minor")

We declared Age variable equal to 21; we then have an if /else statement that
evaluates the Age value if age is greater than 18 then prints ”Major” else
“Minor”.

T o evaluate a simple condition, we have written 5 lines of code. Can we write


the same code in a lesser number of lines? 

Yes, with the help of a ternary operator we can achieve this. T his operator is
available f rom Python version 2.4.

Synt ax of Pyt hon T ernary Operat or

As I said above, the ternary operator requires 3 components and the structure
of these components as below:

So, the f ollowing code shows how can we transf orm the above lengthy code
into a lesser number of lines using the ternary operator:

Age = 21
"Major" if (Age > 18) else "Minor"

#'Major'
Age = 15
"Major" if (Age > 18) else "Minor"

#'Minor'

T hat’s it! Component 2 is our condition ( if (Age > 18) ), which is evaluated f irst. If
it evaluates to T rue, then “Major” is the output; otherwise, “Minor” is the output.
In this case, Age > 18 evaluates to T RUE, so the output is “Major”.

Let’s decompose our improved code to match the structure of the ternary
operator:

(1) A condition →if (Age > 18)

(2) T rue value →“Major”

(3) False value → “Minor”

Pyt hon T ernary operat or in t he ret urn st at ement

We can use ternary operators in the f unction’s return statement. For example,
writing a f unction that expects a person’s Age as input and returns the person
is either “Major” or “Minor”.

def is_major(Age):

return 'Major' if Age > 18 else 'Minor'

is_major(21)
# 'Major'

is_major(15)
'Minor'

T he above code shows how we can use the ternary operator in a return
statement; we have used the ternary operator structure directly in the return
statement.
Short Hand T ernary operat or

We also have a shorthand f orm of the ternary operator that we discussed


above, which will quickly test a f unction’s output. T his type of syntax
introduced in Python 2.5 and can be used in python 2.5 or greater.

T rue or NULL
# T rue

False or 1

#1

T he f irst statement (T rue or “NULL”) will return T rue, and the second statement
(False or “1”) will return 1.

You can use this syntax to test a variable value:

known_number = None

msg = known_number or "Unknown number"

print(msg)

#Unknown number

known_number = 5634

msg = known_number or "Unknown number"

print(msg)

# 5634

T his will be usef ul when you quickly test a user input in a f unction:

def choice_name(person_name, person_nick_name):

display_name = person_name or person_nick_name

print(display_name)

# f unction call with name and nick name as none

choice_name(person_name ="Jospeh",person_nick_name =None)

#Jospeh

# f unction call with name as none and nick name

choice_name(person_name = None,person_nick_name ='Joe')

# Joe

T he above f unction takes the person name and nickname as arguments and
use the shorthand ternary operator syntax and results in displaying the
person’s name; this will become handier to test the two variables and results in
the only T RUE values.

T ernary operat or wit h if-else-if st at ement

Let’s write a f unction that evaluates multiple if conditions and return the result.

f loors = 12

if (f loors <= 3):

print('Low rise building')

elif (f loors >3 and f loors <=7):

print('Mid-rise building')

else:

print('High rise building')

#High rise building

T he above If …elif code evaluates a number of f loors value and result is the
category of building, i.e., if the f loors are greater less than or equal to three
f loors, then it is categorized a “Low rise building” else if the f loors are greater
than three but less than or equal to 7 then its is categorized as “Mid-rise
building ” else it is categorized as “High rise building”.

With the help of a ternary operator, we can write this code in a small number of
lines, But how? T he ternary operator structure says only 3 components, but
here we have multiple conditions, don’t worry, we also nest the ternary
operator just like nested if . 

f loors = 12

'Low rise building' if (f loors <= 3) else 'Mid-rise building' if (f loors >3 and f loors
<=7) else 'High rise building'

#'High rise building'

f loors = 7

'Low rise building' if (f loors <= 3) else 'Mid-rise building' if (f loors >3 and f loors
<=7) else 'High rise building'

#'Mid-rise building'

f loors = 2

'Low rise building' if (f loors <= 3) else 'Mid-rise building' if (f loors >3 and f loors
<=7) else 'High rise building'

# Low rise building

Lambda
Earlier we saw f unction def inition and f unction calls. Lambdas are anonymous,
small f unctions.  T he body of the lambda can have only one expression. Lambda
can take any number of arguments.

# a lambda f unction with the name growth is created

# it takes one argument and increase it by 2

growth = lambda givenLength : givenLength + 2

print(growth(25)) # prints 27
Let us take another example with many parameters:

# lambda with the name area is created


# two parameters are passed, who area is calculated

area = lambda length, breadth: length * breadth

print(area(4, 7)) # prints 28

T he lambdas are usef ul when nested within another f unction.  T he f unction


becomes a template to create a f unction.

# the growth lambda we wrote earlier

def growth(n):
return lambda a : a + n

# create a f unction that would increase by 2

strechT wo = growth(2)

# create a f unction that would increase by 3

strechT hree = growth(3)

print(strechT wo(7))

print(strechT hree(7))

In the above example, using the same f unction growth, we spawn dif f erent
f unctions strechT wo and strechT hree.  T his is possible with the lambda
f unction declared inside the growth f unction. We get the output 9 and 10 by
running this code.

Arrays
Arrays are used to store a list of values in a variable.  Here is the syntax to
create an array. Square brackets are used to def ine a list.

f ruits = ["mango", "apple", "grapes"]

print (f ruits)
Arrays allow us to access the array elements using index.  T he index are zero
based, they start f rom zero.

f ruits = ["mango", "apple", "grapes"]

f irstFruit = f ruits[0]
print (f irstFruit)

Similar to accessing the element, we can modif y the element using index.

f ruits = ["mango", "apple", "grapes"]

f ruits[0] = "melon"

print (f ruits)

T he number of elements in an array can be known by using the len() method.

f ruits = ["mango", "apple", "grapes"]

print (len(f ruits)) # prints 3

f or statement is used to loop through the array elements.  We can process


individual elements inside the loop.

f ruits = ["mango", "apple", "grapes"]

f or f ruit in f ruits:

print(f ruit)

append() method adds a new element to the end of the array.

f ruits = ["mango", "apple", "grapes"]

f ruits.append("guava")
print(f ruits)

T wo methods are usef ul to remove elements f rom the array.  pop() method
takes the array index and removes the element in the particular position
(remember the elements are zero based).  remove() accepts the value of the
element and removes it. Let us see these two methods in action.

f ruits = ["mango", "apple", "grapes"]

f ruits.pop(1)

print(f ruits)

f ruits.remove("grapes")

print(f ruits)

Classes
Objects are entities that possess properties and methods.  T hese objects can
be created by declaring classes. Classes are blueprints of objects.

In this example, we see how to def ine a class, create objects out of the class
and access the property of the object.

# create a class with "class" keyword

class Fruit:

# a property, "name" is created

# the property is assigned with the value "mango"

name="mango"

# let us create an object, "oneFruit" using the above class

oneFruit = Fruit()

# the property of the object "oneFruit" is accessed like this

print(oneFruit.name)

All classes have an inbuilt f unction, __init__()


T his f unction is called when a new object is created f rom the class.  T his
f unction is called automatically when the object is created.

We can write usef ul initialization code in this f unction, so that variables are set
at the time of object instantiation. 

# create a class with "class" keyword

class Fruit:

# def ine the init f unction


def __init__(self , name, color):

self .name = name

self .color = color


# let us create an object, "oneFruit" using the above class

# values are passed to the class

oneFruit = Fruit("mango", "yellow")

# the property of the object "oneFruit" is accessed like this

print(oneFruit.name)

print(oneFruit.color)

In the above example, we used a parameter “self ”.  T here are three parameters
def ined in the init f unction, however we passed only two arguments in the class
invocation.  T he self -parameter is automatically passed to the class’s method.
T he name “self ” is not f ixed, you may use any name. It has to be the f irst
parameter. 

Apart f rom the inbuilt methods, the class can have other user def ined
methods.  Let us create a makeJuice() method inside the class.

# create a class with "class" keyword

class Fruit:

# def ine the init f unction


def __init__(self , name, color):

self .name = name

self .color = color


def makeJuice(self ):

print("Made " + self .name + " juice. It will be in " +

self .color + " color.")

# let us create an object, "oneFruit" using the above class

# values are passed to the class

oneFruit = Fruit("mango", "yellow")

# invode object's method

oneFruit.makeJuice()

T he property of the object can be modif ied like this:

oneFruit.color = "red"

Inheritance
Inheritance is a concept where we extend the f unctionality of a class to create
new classes.  T here are many benef its of doing this. Foremost is to reuse
existing code.

T he existing class has generic code that can be reused.  T his class is called
parent or base class.

We create a child class that would receive the def inition f rom the parent class.
Let us consider a parent class, Vehicle.  T his has properties and methods
suitable to describe any vehicle.

class Vehicle:
def __init__(self , make, color):

self .make = make

self .color = color


def display(self ):
print("make= " + self .make + " color= " + self .color)

v = Vehicle("2015", "green")

v.display()

T wo properties, make and color, are def ined in the Vehicle property.

Let us extend a child class, Car, f rom the Vehicle class.

class Vehicle:
def __init__(self , make, color):

self .make = make

self .color = color


def display(self ):
print("make= " + self .make + " color= " + self .color)

# v = Vehicle("2015", "green")
# v.display()

class Car(Vehicle):

def __init__(self , make, color, numOf Seats):

super().__init__(make, color)

self .numOf Seats = numOf Seats

def display(self ):
super().display()

print("number of seats= " + str(self .numOf Seats))

def wipeWindshield(self ):

print("turned on wiper")

newCar = Car("2019", "orange", 5)

newCar.display()

newCar.wipeWindshield()

T here are many points to be noted in this code.

Line 12 def ines a class, Car.  T his is an extended Vehicle (mentioned in the
paranthesis).

Line 13 is the constructor of Car.  T hree parameters are accepted.

Line 14 invokes the constructor of the parent, Vehicle class.  T wo parameters


are passed to the parent’s constructor.

Line 15 initializes an object property, numOf Seats.  T his property belongs to Car
and does not exist in Vehicle class.

Line 17 redef ines the method display().  In the method’s code, parent method is
called, as well as code is there to express f unctionality of the Car object.

Line 21 def ines a method that belongs to the Car class.

Line 24 to 26 creates a Car object, handles Car properties and invokes various
methods.
Iterators
Iterator is a container of values, with which we can traverse through all the
values.

In Python, an iterator is an object that implements __iter__() and __next__().

Lists, tuples, dictionaries, and sets are iterable and implement an iterator
protocol.  T hese containers have iter() method that are used to traverse the
values.

Here is an example.

f ruitT uple = ("mango", "apple", "grapes")

f ruitIter = iter(f ruitT uple)

print(next(f ruitIter))
print(next(f ruitIter))
print(next(f ruitIter))

A string can be iterated using iter() method.

f ruitStr = "mango"

f ruitIter = iter(f ruitStr)


print(next(f ruitIter))
print(next(f ruitIter))
print(next(f ruitIter))
print(next(f ruitIter))
print(next(f ruitIter))
print(next(f ruitIter)) # last call throws error

Note that the f irst f ive next () call print each character of “mango”.  T he f inal
next () throws an error saying the iteration has stopped.

T he iterable object can be iterated with the f or in loop.

f ruitT uple = ("mango", "apple", "grapes")

f ruitIter = iter(f ruitT uple)

f or f ruit in f ruitT uple:

print(f ruit)

We can create our own iterator class.  We need to implement __iter__() and
__next__() methods.

Remember __init__() we saw in class def inition?  T he iterator method and


protocols are similar to init of the class.

Let us consider an example that would create an iterator.  T he iterator is a


Fibonacci series starting f rom 1, 2.

class Fibonacci:

def __iter__(self ):

# def ine f irst two numbers


self .f irst = 1
self .second = 2

return self

def __next__(self ):

curr = self .f irst + self .second # f ind new number

self .f irst = self .second # shif t the previous two numbers

You might also like