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

Core Python Notes

Python

Uploaded by

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

Core Python Notes

Python

Uploaded by

Keerthi Peravali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

By Mohammed Younus Shariff

Introduction to Python

Python is an open source, high-level programming language developed by Guido


van Rossum in the late 1980s and presently administered by Python Software
Foundation. It came from the ABC language that he helped create early on in his
career.
Python is a powerful language that you can use to create games, write GUIs, and
develop web applications.
It is a high-level language. Reading and writing codes in Python is much like
reading and writing regular English statements. Because they are not written
in machine-readable language, Python programs need to be processed before
machines can run them.
Python is an interpreted language. This means that every time a program is run,
its interpreter runs through the code and translates it into machine-readable byte
code.
Python is an object-oriented language that allows users to manage and control
data structures or objects to create and run programs. Everything in Python is, in
fact, first class. All objects, data types, functions, methods, and classes take equal
position in Python.
Programming languages are created to satisfy the needs of programmers and
users for an effective tool to develop applications that impact lives, lifestyles,
economy, and society. They help make lives better by increasing productivity,
enhancing communication, and improving efficiency. Languages die and become
obsolete when they fail to live up to expectations and are replaced and
superseded by languages that are more powerful. Python is a programming
language that has stood the test of time and has remained relevant across
industries and businesses and among programmers, and individual users. It is a
living, thriving, and highly useful language that is highly recommended as a first
programming language for those who want to dive into and experience
programming.
By Mohammed Younus Shariff

Features of Python
Simple

Python is a simple and minimalistic language. Reading a good Python


program feels almost like reading English, although very strict English! This
pseudo-code nature of Python is one of its greatest strengths. It allows you
to concentrate on the solution to the problem rather than the language
itself.
Easy to Learn

As you will see, Python is extremely easy to get started with. Python has an
extraordinarily simple syntax, as already mentioned.
Free and Open Source

Python is an example of a FLOSS (Free/Libré and Open Source Software).


In simple terms, you can freely distribute copies of this software, read it's
source code, make changes to it, use pieces of it in new free programs, and
that you know you can do these things. FLOSS is based on the concept of a
community which shares knowledge. This is one of the reasons why Python
is so good - it has been created and is constantly improved by a community
who just want to see a better Python.
High-level Language

When you write programs in Python, you never need to bother about the
low-level details such as managing the memory used by your program, etc.
Interpreted

This requires a bit of explanation.


A program written in a compiled language like C or C++ is converted from
the source language i.e. C or C++ into a language that is spoken by your
computer (binary code i.e. 0s and 1s) using a compiler with various flags
By Mohammed Younus Shariff

and options. When you run the program, the linker/loader


software copies the program from hard disk to memory and starts running
it.
Python, on the other hand, does not need compilation to binary. You
just run the program directly from the source code. Internally, Python
converts the source code into an intermediate form called bytecodes and
then translates this into the native language of your computer and then
runs it. All this, actually, makes using Python much easier since you don't
have to worry about compiling the program, making sure that the proper
libraries are linked and loaded, etc, etc. This also makes your Python
programs much more portable, since you can just copy your Python
program onto another computer and it just works!

Object Oriented

Python supports procedure-oriented programming as well as


object-oriented programming. In procedure-oriented languages, the
program is built around procedures or functions which are nothing but
reusable pieces of programs. In object-oriented languages, the program is
built around objects which combine data and functionality. Python has a
very powerful but simplistic way of doing OOP, especially when compared
to big languages like C++ or Java.
Extensive Libraries

The Python Standard Library is huge indeed. It can help you do various
things involving regular expressions, documentation generation, unit
testing, threading, databases, web browsers, CGI, ftp, email, XML,
XML-RPC, HTML, WAV files, cryptography, GUI (graphical user interfaces),
Tk, and other system-dependent stuff. Remember, all this is always
available wherever Python is installed. This is called the 'Batteries Included'
philosophy of Python.
By Mohammed Younus Shariff

Fascinating Python Applications in Real-World:


1. Artificial Intelligence and Machine Learning
AI and ML models and projects are inherently different from traditional software
models. When we talk about AI/ML projects, the tools and technologies used and
the skillset required is totally different from those used in the development of
conventional software projects. AI/ML applications require a language that is
stable, secure, flexible, and is equipped with tools that can handle the various
unique requirements of such projects. Python has all these qualities, and hence, it
has become one of the most favored languages of Data Science professionals.
Python’s simplicity, consistency, platform independence, great collection of
resourceful libraries, and an active community make it the perfect tool for
developing AI and ML applications. Some of the best Python packages for AI and
ML are:
 SciPy for advanced computing
 Pandas for general-purpose data analysis
 Seaborn for data visualization
 Keras, TensorFlow, and Scikit-learn for ML
 NumPy for high-performance scientific computing and data analysis
Apart from these libraries, there are also other Python-based libraries like NLTK,
Caffee, PyTorch, and Accord.NET, that are useful for AI and ML projects.

2. Web Development
When it comes to web development, Python should be your go-to tool. Why?
That’s because Python offers numerous options for web development. For
instance, you have Django, Pyramid, Flask, and Bottle for developing web
frameworks and even advanced content management systems like Plone and
Django CMS. These web frameworks are packed with standard libraries and
modules which simplify tasks like content management, database interaction, and
interfacing with internet protocols like HTTP, SMTP, XML, JSON, FTP, IMAP, and
POP.
Python web frameworks are known for their security, scalability, and flexibility. To
add to that, Python’s Package Index comes with useful libraries like Requests,
BeautifulSoup, Paramiko, Feedparser, and Twisted Python.
By Mohammed Younus Shariff

3. Game Development
As we mentioned earlier, Python comes loaded with many useful extensions
(libraries) that come in handy for the development of interactive games. For
instance, libraries like PySoy (a 3D game engine that supports Python 3) and
PyGame are two Python-based libraries used widely for game development.
Python is the foundation for popular games like Battlefield 2, Frets on Fire, World
of Tanks, Disney’s Toontown Online, Vega Strike, and Civilization-IV.

4.Desktop GUI
Python not only boasts of an English-like syntax, but it also features a modular
architecture and the ability to work on multiple operating systems. These aspects,
combined with its rich text processing tools, make Python an excellent choice for
developing desktop-based GUI applications.
Python offers many GUI toolkits and frameworks that make desktop application
development a breeze. PyQt, PyGtk, Kivy, Tkinter, WxPython, PyGUI, and PySide
are some of the best Python-based GUI frameworks that allow developers to
create highly functional Graphical User Interfaces (GUIs).

5. Image Processing and Graphic Design Applications:


Alongside all the uses mentioned above, Python also finds a unique use case in
image processing and graphic design applications. The programming language is
used globally to design and build 2D imaging software like Inkscape, GIMP, Paint
Shop Pro, and Scribus. Also, Python is used in several 3D animation packages such
as Blender, Houdini, 3ds Max, Maya, Cinema 4D, and Lightwave, to name a few.

6. Web Scraping Applications


Python is a nifty tool for extracting voluminous amounts of data from websites
and web pages. The pulled data is generally used in different real-world
processes, including job listings, price comparison, R&D, etc.
BeautifulSoup, MechanicalSoup, Scrapy, LXML, Python Requests, Selenium, and
Urllib are some of the best Python-based web scraping tools.
By Mohammed Younus Shariff

Installing and running Python with Different IDEs:


Download & Python Installation Process in Windows, Unix, Linux etc.

For windows :
We can download the latest version of python for windows from
The Python needs around 26 Mb of disk space;
When installed, Python requires about an additional 90-100 Mb of disk space.

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

Following is the screen shot :

The other versions may be downloaded from ( let's consider this option )

https://www.python.org/downloads/windows/
By Mohammed Younus Shariff

Following is the screen shot :

Let’s click on the Download Windows x86-64 executable installer link under the
top-left Stable Releases. ( Your choice may depend on the 32 / 64 Bit OS you are
using )
By Mohammed Younus Shariff

The following window will appear

Installation:

Step 1 :

Double-click the icon labeling the file python-3.8.5-amd64.exe.

A Python 3.8.5 (64-bit) Setup pop-up window will appear.


By Mohammed Younus Shariff

Screen Shot

Make sure that the Install launcher for all users (recommended) and the Add
Python 3.8 to PATH checkboxes are ticked.

If this Installer gets an earlier version of Python on the computer, the message
might appear as Upgrade Now (and the checkboxes may not appear).

Step 2 :

Click on Install Now (or Upgrade Now) message,


By Mohammed Younus Shariff

When run, a User Account Control message may appear on the computer. it may
asksfor , Do you want to allow this application to make changes to your device?''

Click on yes

Step 3 :

A new Python 3.8.5(64-bit) Setup pop-up window will appear with a Setup
Progress message and a progress bar as follows.

While installation proceeds, it will show the various components getting installed
and move the progress bar towards completion. Soon, a new Python 3.8.5 (64-bit)
Setup pop-up window will appear with a Setup was successfully message.
By Mohammed Younus Shariff

Click the Close button.

Step 4 :

Python should now be installed

How to verify ?

 Navigate to the directory


C:\Users\Sharma\AppData\Local\Programs\Python\Python38 (or to
whatever directory Python was installed: for mine see the screen shot
when the “install now “ button appeared).

 Double-click the icon/file python.exe.


The following pop-up window will appear.
By Mohammed Younus Shariff

A pop-up window with the title


C:\Users\Sharma\AppData\Local\Programs\Python\Python38 appears, and inside
the window; on the first line is the text Python 3.8.5 , 64 bit.

Great we are done !

For Linux :

Ubuntu :

Most probably your Linux operating system has Python installed already, but
won’t be the latest version, and it may be Python 2 in place of Python 3.

To check what version(s) you have, open a terminal window and use the below
commands:

 python --version
 python2 --version
 python3 --version
By Mohammed Younus Shariff

One or more of these commands should respond with a version, as below:

In case it shows Python 2.x.x , then we can install the most recent version. The
steps for doing this will depend on the Linux distribution you are running ( But it’s
mostly the same).

Let’s consider Ubuntu ( Most widely used in educational institutions and famous
among students )

You can determine your local Ubuntu version by running the following command:

Ubuntu 17.10, Ubuntu 18.04 (or above) have Python 3.6.x by default. We can
run it with the command python3.
By Mohammed Younus Shariff

Ubuntu 16.10 and 17.04 don't come with Python 3 by default, but it is
available in the Universe repository. we can install it with the following
commands:

If we have Ubuntu 14.04 or 16.04, Python 3.8.5 is not in the Universe repository,
and we need to get it from a Personal Package Archive (PPA).

For example, to install Python from the “deadsnakes” PPA, as follows:

Linux Mint : Follow the same steps

Install Python from the “deadsnakes” PPA, as follows:


By Mohammed Younus Shariff

Debian :
In debian , sudo command also needs to be installed first

next, open the /etc/sudoers file using the sudo vim command
append the following line of text to the end of the file, replacing your_username
with your actual username:

your_username ALL=(ALL) ALL

Python Real-time IDEs

IDE stands for integrated development environment,


An IDE provides various features / facilities to software developers.
By Mohammed Younus Shariff

An IDE typically consists of:


Source code editor:
Debugger:
Syntax Highlighting:
Autocomplete:

For example :

Spyder:

Spyder is an environment used for scientific and engineering applications


It supports advanced editing, analysis, debugging, and profiling features of a
comprehensive development tool with the data exploration, interactive
execution, deep inspection, and beautiful visualization capabilities.
By Mohammed Younus Shariff

Jupyter Notebook :

The Jupyter Notebook is an open-source web based application that lets us to


make and share documents that contain live code, equations, visualizations and
narrative text.

Its Usages include : data cleaning and transformation, numerical simulation,


statistical modeling, data visualization, machine learning, and much more.

PyCharm :

It supports code analysis, graphical debugging, integrated unit testing, integration


with version control systems (VCSes), and web development with Django as well
as Data Science with Anaconda. PyCharm is available for Windows, macOS and
Linux versions.
By Mohammed Younus Shariff

Rodeo :

A Native Python IDE best suited for Data Science related applications.

Visual Studio Code :

Visual Studio code has Microsoft Python extension,which is simple, fun, and
productive.its works on any operating system with a variety of Python
interpreters. It supports autocomplete and IntelliSense, linting, debugging, and
unit testing, along with the ability to easily switch between Python environments,
including virtual and conda environments.
By Mohammed Younus Shariff

ATOM:

Atom does not have features in the traditional sense, it makes packages that add
to its hackable core. These packages support various features like auto-complete,
code lines, and code highlighters.Its available for all major operating systems.

Installing and Managing Python Packages Using pip


With Python, you can build just about anything, from simple scripts to full
applications. The Python language, however, doesn’t come pre-installed with all
of the fancy features you might want (or require). When you need particular
functionality, you can look toward Python packages. A package structures
Python modules, which contain pre-written code that other developers have
created for you. Modules are handy when you are looking for specific
functionality.
You can use pip, Python’s package manager, to install and manage Python
packages.
If your Python 3 version is greater than or equal to 2.7.9, no need to worry, you
have pip pre-installed!
By Mohammed Younus Shariff

You can use pip to install packages, like so:


pip install numpy
In the example above, pip will install the Scrapy package, a popular package
(among many) used for scraping information from websites.

Launch an interactive Python shell


By executing (running) the python command in your terminal, you are presented
with an interactive Python shell. This is also known as the Python Interpreter or a
REPL (for 'Read Evaluate Print Loop').

$ python3
Python 3.6.0 (default, Jan 13 2017, 00:00:00)
[GCC 6.1.1 20160602] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print('Hello, World')
Hello, World
>>>

There are multiple ways to close the Python shell:


>>> exit()
or
>>> quit()
Alternatively, CTRL + D will close the shell and put you back on your terminal's
command line.
By Mohammed Younus Shariff

If you want to cancel a command you're in the middle of typing and get
back to a clean command prompt, while
staying inside the Interpreter shell, use CTRL + C .

IDLE - Python GUI


IDLE is Python’s Integrated Development and Learning Environment and is an
alternative to the command line. As the name may imply, IDLE is very useful for
developing new code or learning python. On Windows this comes with the Python
interpreter, but in other operating systems you may need to install it through
your package manager. The main purposes of IDLE are: Multi-window text editor
with syntax highlighting, autocompletion, and smart indent Python shell with
syntax highlighting Integrated debugger with stepping, persistent breakpoints,
and call stack visibility Automatic indentation (useful for beginners learning about
Python's indentation) GoalKicker.com – Python® Notes for Professionals 20 Saving
the Python program as .py files and run them and edit them later at any them
using IDLE. In IDLE, hit F5 or run Python Shell to launch an interpreter. Using IDLE
can be a better learning experience for new users because code is interpreted as
the user writes.
By Mohammed Younus Shariff

Memory Management And Garbage Collection In Python:

Python Is a Dynamically Typed Language.

We don’t declare the type of a variable when we assign a value to the variable in
Python. It states the kind of variable in the runtime of the program. Other
languages like C, C++, Java, etc.., there is a strict declaration of variables before
assigning values to them.

As you can see below, we just assign a variable to an object and Python detects
the type of the object.

How are Python objects stored in memory?

In C, C++, and Java we have variables and objects. Python has names, not
variables. A Python object is stored in memory with names and references. A
name is just a label for an object, so one object can have many names. A reference
is a name(pointer) that refers to an object.
By Mohammed Younus Shariff

Every Python object has 3 things.

Python objects have three things: Type, value, and reference count. When we
assign a name to a variable, its type is automatically detected by Python as we
mentioned above. Value is declared while defining the object. Reference count is
the number of names pointing that object.

Garbage Collection:

Garbage collection is to release memory when the object is no


longer in use. This system destroys the unused object
and reuses its memory slot for new objects. You can imagine this
as a recycling system in computers.

Python has an automated garbage collection. It has an algorithm


to deallocate objects which are no longer needed. Python has
many ways to delete the unused objects from the memory.
By Mohammed Younus Shariff

Reference counting:

The references are always counted and stored in memory.

In
the

example below, we assign c to 50. Even if we assign a new variable, the object is
the same, the reference count increases by 1! Because every object has its own ID,
we print the IDs of objects to see if they are the same or different.

When we change the value of a like in below, we create a new object.


Now, a points to 60, b and c point to 50.

When we change a to None, we create a none object. Now the previous integer
object has no reference, it is deleted by the garbage collection.

We assign b to a boolean object. The previous integer object is not deleted


because it still has a reference by c.
By Mohammed Younus Shariff

Now we delete c. We decrease the reference count to c by one.


By Mohammed Younus Shariff

Python Syntax

Python syntax refers to the set of rules that defines how human users and the
system should write and interpret a Python program. If you want to write and run
your program in Python, you must familiarize yourself with its syntax.

Keywords
Python keywords are reserved words in Python that should not be used as
variable, constant, function name, or identifier in your code. Take note of these
keywords if you don’t want to run into errors when you execute your program:

Python Identifiers
A Python Identifier is a name given to a function, class, variable, module, or other
objects that you’ll be using in your Python program. Any entity you’ll be using in
Python should be appropriately named or identified as they will form part of your
program.
By Mohammed Younus Shariff

Here are Python naming conventions that you should be aware of:

 An identifier can be a combination of uppercase letters, lowercase letters,


underscores, and digits (0-9). Hence, the following are valid identifiers:
myClass, my_variable, var_1, and print_hello_world.
 Special characters such as %, @, and $ are not allowed within identifiers.
 An identifier should not begin with a number. Hence, 2variable is not valid,
but variable2 is acceptable.
 Python is a case-sensitive language and this behavior extends to identifiers.
Thus, Labor and labor are two distinct identifiers in Python.
 You cannot use Python keywords as identifiers.
 Class identifiers begin with an uppercase letter, but the rest of the
identifiers begin in lowercase.
 You can use underscores to separate multiple words in your identifier.
 You should always choose identifiers that will make sense to you even after
a long gap. Hence, while it is easy to set your variable to c = 2, you might
find it more helpful for future reference if you use a longer but more
relevant variable name such as count = 2.

Using Quotations

Python allows the use of quotation marks to indicate string literals. You can use
single, double, or triple quotes but you must start and end the string with the
same type. You would use the triple quotes when your string runs across several
lines.

Python Statements
Statements are instructions that a Python interpreter can execute. When you
assign a value to a variable, say my_variable = “dog”, you’re making an
By Mohammed Younus Shariff

assignment statement. An assignment statement may also be as short as


c = 3. There are other kinds of statements in Python,
like if statements, while statements, for statements, etc.

Multi-line statements

A statement may span over several lines. To break a long statement over multiple
lines, you can wrap the expression inside parentheses, braces, and brackets. This
is the preferred style for handling multi-line expressions. Another way to wrap
multiple lines is by using a backslash (\) at the end of every line to indicate line
continuation.

Indentation

While most programming languages such as Java, C, and C++ use braces to denote
blocks of code, Python programs are structured through indentation. In Python,
blocks of codes are defined by indentation not as a matter of style or preference
but as a rigid language requirement. This principle makes Python codes more
readable and understandable.

A block of code can be easily identified when you look at a Python program as
they start on the same distance to the right. If it has to be more deeply nestled,
you can simply indent another block further to the right. For example, here is a
segment of a program defining car_rental_cost:

def car_rental_cost(days):
cost = 35 * days
if days >= 8:
By Mohammed Younus Shariff

cost -= 70
elif days >= 3:
cost -= 20
return cost
You have to make sure that the indent space is consistent within a block. When
you use IDLE and other IDEs to input your codes, Python intuitively provides
indentation on the subsequent line when you enter a statement that requires
indentation. Indentation, by convention, is equivalent to 4 spaces to the right.

Comments

When writing a program, you’ll find it helpful to put some notes within your code
to describe what it does. A comment is very handy when you have to review or
revisit your program. It will also help another programmer who might need to go
over the source code. You can write comments within your program by starting
the line with a hash (#) symbol. A hash symbol tells the Python interpreter to
ignore the comment when running your code.

For multi-line comments, you can use a hash symbol at the beginning of each line.
Alternatively, you can also wrap multi-line comment with triple quotes.
By Mohammed Younus Shariff

Python’s Built-in Functions

Functions provide efficiency and structure to a programming language.


Python has many useful built-in functions to make programming easier,
faster, and more powerful.

The input() Function

Programs usually require input that can come from different sources:
keyboard, mouse clicks, database, another computer’s storage, or the
internet. Since the keyboard is the most common way to gather input,
Python provided its users the input() function. This function has an
optional parameter called the prompt string.

Once the input function is called, the prompt string will be displayed on the
screen and the program flow stops until the user has entered an input. The
input is then interpreted and the input() function returns the user’s input
as a string.

To illustrate, here is a sample program that collects keyboard input for


name and age:

name = input(“May I know your name? “)


print(“It’s a pleasure to meet you ” + name + “!”)
age = input(“Your age, please? “)
By Mohammed Younus Shariff

print(“So, you’re ” + age + ” years old, ” + name + “!”)

Before you save the code, take a close look at the string to be printed on
the second line. You’ll notice that there is a blank space after ‘you’ and
before the double quote. This space ensures that there will be a space
between ‘you’ and the ‘name’ input when the print command is executed.
The same convention can be seen on the 4th line with the print command
where ‘you’re’ is separated by a single space from the ‘age’ input and ‘old’
is separated by a space from the ‘name’ input.

Save the code as info_input.py and run it.

The Python Shell will display the string on the first line:

May I know your name?


By Mohammed Younus Shariff

A response is needed at this point and the program stops executing until a
keyword input is obtained. Let’s type and enter the name Younus to see
what happens:

It’s a pleasure to meet you Younus!


Your age, please?

The program has now proceeded to the next input function and is waiting
for the keyboard input. Let’s enter 22 as Younus age and see what the
program does next:

So, you’re 22 years old, Younus!

The print() Function

Python 3 turned print from a statement into a function. Hence, you must
always enclose your print parameters within the round parentheses.

Examples:

print(“This is Python 3 print function)


print(s)
print(5)

The print() function can print any number of values within the parentheses;
By Mohammed Younus Shariff

they must be separated by commas. For example:

a = 3.14
b = “age”
c = 32

print(“a = “, a, b, c)

The result:

a = 3.14 age 32
The Python shell displayed values with blank spaces between them.
By Mohammed Younus Shariff

Python Basic Operators

Python operators allow programmers to manipulate data or operands. Here are


the types of operators supported by Python:

 Arithmetic Operators
 Assignment Operators
 Relational or Comparison Operators
 Logical Operators
 Identity Operators
 Bitwise Operators
 Membership Operators

Arithmetic Operators

Python does a good job of processing mathematical expressions with its basic
arithmetic
operators. You can easily make programs to automate tasks such as computing
tax, tips, discounts, or rent.

+ Addition adds the value of the left and right operands

subtracts the value of the right operand from the


- Subtraction value of the left operand

* Multiplication multiplies the value of the left and right operand

divides the value of the left operand by the right


/ Division operand

** Exponent performs exponential calculation


By Mohammed Younus Shariff

returns the remainder after dividing the left operand


% Modulus with the right operand

Floor division of operands where the solution is a quotient


// Division left after removing decimal numbers

Addition, subtraction, multiplication, and division are the most basic operators
and are invoked by entering the following expressions:

Addition:

>>>1 + 3
4

Subtraction:

>>>10 – 4
6

Multiplication:
>>>4 * 2
8
By Mohammed Younus Shariff

Division:
>>>10 / 2 =>5.0
Exponent

Exponential calculation is invoked by raising the first number to the power


defined by the number after the ** operator:

>>>2**32 raised to the power of 3


8

Modulus The modulus operator gives the remainder after performing division:

>>>17 % 5
2
Floor Division

Floor division, on the other hand, returns the quotient after removing fractional
numbers:

>>>17 // 5
3

Assignment Operators These operators are useful when assigning values to


variables:

= assigns the value of the right operand to the left operand


By Mohammed Younus Shariff

adds the value of the right and left operand and assigns the
+= total to the left operand

-= deducts the value of the right operand from the value of the
left operand and assigns the new value to the left operand

*= multiplies the left and right operand and assigns the product
to the left operand

/= divides the left operand with the value of the right operand
and assigns the quotient to the left operand

**= performs exponential operation on the left operand and


assigns the result to the left operand

//= performs floor division on the left operand and assigns the
result to the left operand

= Operator

You have seen this operator at work in previous chapters when you have assigned
different values to variables. Examples:

a=c
a=b+c
a=8
By Mohammed Younus Shariff

a=8+6
s = “I love Python.”
+= add and
The ‘add and’ (+=) operator is simply another way to express x = x + a so that
you’ll end up with the statement x += a.

-= subtract and

The ‘subtract and’ (-=) operator is equivalent to the expression x = x – a and is


expressed with the statement x-=a

*= multiply and

The ‘multiply and’ (*=) operator is the equivalent of the statement x = x * a and is
expressed with x*=a.

/= divide and

The ‘divide and’ (/=) operator is like saying x = x/a and is expressed with the
statement x/=a.
By Mohammed Younus Shariff

%= modulus and

The ‘modulus and’ (%=) operator is another way to say x = x % a where you’ll end
up instead with the expression x%=a.

//= floor division and

The ‘floor division and’ is equivalent to the expression x = x//a and takes the form
x//=a.

Relational or Comparison Operators


Relational operators evaluate values on the left and right side of the operator and
return the relation as either True or False.

Here are the relational operators in Python:

Operator Meaning

== is equal to

< is less than

> is greater than

<= is less than or equal to

>= is greater than or equal to

!= is not equal to
By Mohammed Younus Shariff

Examples:

>>>8 == 6+2
True

>>>6 != 6 False

>>>-1 > 0 False

>>>7 >= 5
True

Logical Operators
Python supports 3 logical operators:
or and not

x or y If the first argument, x, is false, then it evaluates the second


argument, y. Else, it evaluates x.

x and y If x is false, then it evaluates x. Else, if x is true, it evaluates y.

not x If x is false, then it returns True. If x is true, it returns False.


By Mohammed Younus Shariff

Examples:

>>>(8>9) and (2<9) False

>>>(2>1) and (2>9) False

>>>(2==2) or (9<20)
True

>>>(3!=3) or (9>20) False

Bitwise operators
Bitwise operations alter binary strings at the bit level. These operations are
incredibly basic and are directly supported by the processor. These few
operations are necessary in working with device drivers, low-level graphics,
cryptography, and network communications. This section provides useful
knowledge and examples of Python's bitwise operators.

For example, 2 is 10 in binary and 7 is 111.


By Mohammed Younus Shariff

In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000


0100 in binary)
Operator Meaning Example

& Bitwise AND x & y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x >> 2 = 2 (0000 0010)

<< Bitwise left shift x << 2 = 40 (0010 1000)

Special operators

Python language offers some special types of operators like the identity operator
or the membership operator. They are described below with examples.

Identity operators

is and is not are the identity operators in Python. They are used to check if two
values (or variables) are located on the same part of the memory. Two variables
that are equal does not imply that they are identical.
By Mohammed Younus Shariff

Operator Meaning Example

True if the operands are identical (refer


is x is True
to the same object)

True if the operands are not identical x is not


is not
(do not refer to the same object) True

Example 4: Identity operators in Python

x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]

# Output: False
print(x1 is not y1)

# Output: True
print(x2 is y2)

# Output: False
print(x3 is y3)

Output

False
True
False
By Mohammed Younus Shariff

Here, we see that x1 and y1 are integers of the same values, so they are
equal as well as identical. Same is the case with x2 and y2 (strings).
But x3 and y3 are lists. They are equal but not identical. It is because the
interpreter locates them separately in memory although they are equal.

Membership operators

in and not in are the membership operators in Python. They are used to test
whether a value or variable is found in a sequence
(string, list, tuple, set and dictionary).
In a dictionary we can only test for presence of key, not the value.

Operator Meaning Example

True if value/variable is found in the


in 5 in x
sequence

True if value/variable is not found in the 5 not in


not in
sequence x

Example #5: Membership operators in Python

x = 'Hello world'
y = {1:'a',2:'b'}

# Output: True
print('H' in x)
By Mohammed Younus Shariff

# Output: True
print('hello' not in x)

# Output: True
print(1 in y)

# Output: False
print('a' in y)

Output

True
True
True
False

Here, 'H' is in x but 'hello' is not present in x (remember, Python is case


sensitive). Similarly, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in
y returns False.

Precedence of Python Operators

Python operators are evaluated according to a set order or priority:

Description Operators

1 Exponentiation **

Ccomplement, unary plus, ~, +, -


2 and minus
By Mohammed Younus Shariff

Multiplication, division, *, /, %, //
3 modulo, and floor division

4 addition and subtraction +-

5 Right and left bitwise shift >>, <<

6 Bitwise ‘AND’ &

Regular `OR’ and Bitwise |, ^


7 exclusive ‘OR’

8 Comparison operators <= < > >=

9 Equality operators == !=

10 Assignment operators =, +=, -=, *-, /=, %= //= **=

11 Identity operators is, is not

12 Membership operators in, not in

13 Logical operators or, and, not


By Mohammed Younus Shariff

Conditional Statements

Conditional expressions, involving keywords such as if, elif, and else, provide
Python programs with the ability to perform different actions depending on a
boolean condition: True or False. This section covers the use of Python
conditionals, boolean logic, and ternary statements.

Conditional Expression (or "The Ternary Operator")

The ternary operator is used for inline conditional expressions. It is best used in
simple, concise operations that are easily read.

The order of the arguments is different from many other languages (such as C,
Ruby, Java, etc.), which may lead to bugs when people unfamiliar with Python's
"surprising" behaviour use it (they may reverse the order).

Some find it "unwieldy", since it goes contrary to the normal flow of thought
(thinking of the condition first and then the effects).

n=5

"Greater than 2" if n > 2 else "Smaller than or equal to 2"

# Out: 'Greater than 2'


By Mohammed Younus Shariff

The result of this expression will be as it is read in English - if the conditional


expression is True, then it will evaluate to the expression on the left side,
otherwise, the right side.

Ternary operations can also be nested, as here:

n=5

"Hello" if n > 10 else "Goodbye" if n > 5 else "Good day"

They also provide a method of including conditionals in lambda functions.

Python If Statements

Python if Statement is used for decision-making operations. It contains a body of


code which runs only when the condition given in the if statement is true.

It uses the if keyword, followed by the condition.

Syntax:

if condition:

#statement to execute if the condition is true

Below is the entire workflow of how if statements work:


By Mohammed Younus Shariff

First, the test expression is checked. If the expression is true, the body of the if the
statement is executed. If it is false, the statement present after the if statement is
executed. In either case, any line of code present outside if the statement is evaluated
by default.

To understand this better, we’ll use an example:

a=20

if a>50:

print("This is the if body")

print("This is outside the if block")

Since 20 is not greater than 50, the statement present inside the if block will not
execute. Instead, the statement present outside the if block is executed.
By Mohammed Younus Shariff

In the code below, both the print statements will be executed since a is greater
than 50.

So far, we could specify the statements that will be executed if a condition is true. Now,
if you want to evaluate statements that determine whether a condition is actual and if a
separate set of statements is false, you can use the if-else conditional statement.

If-else Statement

The if-else statement is used to execute both the true part and the false part of a given
condition. If the condition is true, the if block code is executed and if the condition is
false, the else block code is executed.

Syntax:

if(condition):

#Executes this block if the condition is true

else:

#Executes this block if the condition is false

You should note here that Python uses indentation in both the blocks to define the
scope of the code. Other programming languages often use curly brackets for this
purpose.
By Mohammed Younus Shariff

Below is the entire workflow of how the if-else statement works.

First, the test expression is checked. If it is true, the statements present in the body of
the if block will execute. Next, the statements present below the if block is executed. In
case the test expression has false results, the statements present in the else body are
executed, and then the statements below the if-else are executed.

The following is an example that better illustrates how if-else works:


By Mohammed Younus Shariff

Since the value of “i” is divisible by two, the if statement is executed.

Since the value of “i” is not divisible by two, the else statement is executed.

Let us now look at what a nested IF statement is and how it works.

Nested IF Statement
When an if a statement is present inside another if statement, it is called a nested IF
statement. This situation occurs when you have to filter a variable multiple times.

Syntax:

if (condition1):

#Executes if condition1 is true

if (condition2):

#Executes if condition2 is true

#Condition2 ends here

#Condition1 ends here


By Mohammed Younus Shariff

In nested IF statements, you should always take care of the indentation to


define the scope of each statement. You can have as many levels of nesting as
required, but it makes the program less optimized, and as a result, can be more
complex to read and understand. Therefore, you should always try to minimize the use
of nested IF statements.

The workflow below demonstrates how nested IF statements work:

The following is another example that shows how nested IF works: We have a number,
and we’re going to check if the number is greater or less than 25. If the number is less
than 25, we’ll check if it is an odd number or an even number. If the number is greater
than 25, we will print that the number is greater than 25.
By Mohammed Younus Shariff

So far, with IF and if-else, we have only seen a binary approach. Suppose we have a
problem that has multiple conditions. In this scenario, the if-elif-else statement comes to
the rescue.

If-Elif-Else Statement

It checks the if statement condition. If that is false, the elif statement is evaluated. In
case the elif condition is false, the else statement is evaluated.
By Mohammed Younus Shariff

Syntax:

if (condition):

statement

elif (condition):

statement

else:

Statement

Below is a flowchart that shows how the if-elif-else ladder works. The Test Expression1
is checked. If that proves true, the body of if is evaluated. If it is false, then the control
moves to the proceeding Test Expression2. If it’s true, the body of elif1 is executed. If
it’s false, the test expression3 is checked. If true, the body of elif2 is executed. If it is
false, the body of else is evaluated. Any statement below in if-elif is then checked.
By Mohammed Younus Shariff

The program below uses the if-elif-else ladder to check if a letter is a vowel or a
consonant.
By Mohammed Younus Shariff

Loops

A loop is a programming construct that enables repetitive processing of a


sequence of statements. Python provides two types of loops to its users: the ‘for
loop’ and the ‘while loop’. The ‘for’ and ‘while’ loops are iteration statements that
allow a block of code (the body of the loop) to be repeated a number of times.

The While Loop

A Python ‘while loop’ repeatedly carries out a target statement while the
condition is true.
The loop iterates as long as the defined condition is true. When it ceases to be
true and becomes false, control passes to the first line after the loop

The ‘while loop’ has the following syntax:


while condition statement
statement
Here is a simple ‘while loop’:
counter = 0
while (counter < 10):
print(‘The count is:’ , counter)
counter = counter + 1
print(“Done!”)

If you run the code, you should see this output:


By Mohammed Younus Shariff

l.py
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
The count is: 9
Done!
An Infinite Loop
Be careful while using a while loop. Because if you forget to increment the
counter variable in python, or write flawed logic, the condition may never
become false. In such a case, the loop will run infinitely, and the conditions after
the loop will starve. To stop execution, press Ctrl+C. However, an infinite loop
may actually be useful. This in cases when a semaphore is needed, or for
client/server programming. A semaphore is a variable used solely for
synchronization in accessing shared resources.
By Mohammed Younus Shariff

The Python for Loop


Of the loop types listed above, Python only implements the last: collection-based
iteration. At first blush, that may seem like a raw deal, but rest assured that
Python’s implementation of definite iteration is so versatile that you won’t end up
feeling cheated!
Shortly, you’ll dig into the guts of Python’s for loop in detail. But for now, let’s
start with a quick prototype and example, just to get acquainted.
Python’s for loop looks like this:
for <var> in <iterable>:
<statement(s)>
<iterable> is a collection of objects—for example, a list or tuple.
The <statement(s)> in the loop body are denoted by indentation, as with all
Python control structures, and are executed once for each item in <iterable>. The
loop variable <var> takes on the value of the next element in <iterable> each time
through the loop.
Here is a representative example:
>>> a = ['foo', 'bar', 'baz']
>>> for i in a:
... print(i)
...
foo
bar
baz
In this example, <iterable> is the list a, and <var> is the variable i. Each time
through the loop, i takes on a successive item in a, so print() displays the
values 'foo', 'bar', and 'baz', respectively. A for loop like this is the Pythonic way to
process the items in an iterable.
But what exactly is an iterable? Before examining for loops further, it will be
beneficial to delve more deeply into what iterables are in Python.
By Mohammed Younus Shariff

Nested for Loops Python


You can also nest a loop inside another. You can put a for loop inside a while, or a
while inside a for, or a for inside a for, or a while inside a while. Or you can put a
loop inside a loop inside a loop. You can go as far as you want.

>>> for i in range(1,6):

for j in range(i):

print("*",end=' ')

print()

*
**
***
****
*****
By Mohammed Younus Shariff

Loop Control Statements in Python

Using a break statement

A Python break statement ends the present loop and instructs the interpreter to
starts executing the next statement after the loop. It can be used in both ‘for’ and
‘while’ loops. Besides leading the program to the statement after the loop, a
break statement also prevents the execution of the ‘else’ statement.

To illustrate, a break statement may be placed right after the print function of the
‘if statement’:

pizza = [“New York Style Pizza”, “Pan Pizza”, “Thin n Crispy Pizza”, “Stuffed Crust
Pizza”]
for choice in pizza:
if choice == “Pan Pizza”:
print(“Please pay $16. Thank you!”)
break
print(“Delicious, cheezy ” + choice)
else:

print(“Cheezy pan pizza is my all-time favorite!”) print(“Finally, I’m full!”)

The Python Shell will now show:

Delicious, cheezy New York Style Pizza


By Mohammed Younus Shariff

Please pay $16. Thank you!


Finally, I’m full!

Using Continue Statement

The continue statement brings back program control to the start of the loop. You
can use it for both ‘for’ and ‘while’ loops.

To illustrate, the continue statement may be placed right after the print function
of the ‘for loop’ to replace the break statement:

pizza = [“New York Style Pizza”, “Pan Pizza”, “Thin n Crispy Pizza”, “Stuffed Crust
Pizza”]
for choice in pizza:

if choice == “Pan Pizza”: print(“Please pay $16. Thank you!”) continue


print(“Delicious, cheesy ” + choice) else:
print(“Cheesy pan pizza is my all-time favorite!”) print(“Finally, I’m full!”)
The output will be:
Delicious, cheesy New York Style Pizza
Please pay $16. Thank you!
Delicious, cheesy Thin n Crispy Pizza
Delicious, cheesy Stuffed Crust Pizza
Cheesy pan pizza is my all-time favorite!
Finally, I’m full!
By Mohammed Younus Shariff

Using the range() Function with the for Loop

The range() function can be combined with the ‘for loop’ to supply the numbers
required by the loop. In the following example, the range(1, x+1) provided the
numbers 1 to 50 needed by the ‘for loop’ to add the sum of 1 until 50:

x = 50

total = 0
for number in range(1, x+1):
total = total + number

print(“Sum of 1 until %d: %d” % (x, total))

The Python Shell will display:

l.py
Sum of 1 until 50: 1275
By Mohammed Younus Shariff

Using Pass Statement

The pass statement tells the Python interpreter to ‘do nothing’. The interpreter
simply continues with the program’s execution whenever the pass statement is
encountered. This attribute makes it a good placeholder whenever Python
syntactically requires a line but the program itself does not require action. It can
be very useful when you’re creating a program and you need to focus on specific
areas of your code, but you still want to reserve some loops or test run the
incomplete code.

Here is how you would use a pass statement to fill gaps within a code:

def function_name(x):
pass

You might also like