Core Python Notes
Core Python Notes
Introduction to Python
Features of Python
Simple
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
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
Object Oriented
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
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).
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/
The other versions may be downloaded from ( let's consider this option )
https://www.python.org/downloads/windows/
By Mohammed Younus Shariff
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
Installation:
Step 1 :
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 :
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
Step 4 :
How to verify ?
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
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).
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:
For example :
Spyder:
Jupyter Notebook :
PyCharm :
Rodeo :
A Native Python IDE best suited for Data Science related applications.
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.
$ 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
>>>
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 .
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.
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
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:
Reference counting:
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 a to None, we create a none object. Now the previous integer
object has no reference, it is deleted by the garbage collection.
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:
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
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
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.
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.
The Python Shell will display the string on the first line:
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:
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:
Python 3 turned print from a statement into a function. Hence, you must
always enclose your print parameters within the round parentheses.
Examples:
The print() function can print any number of values within the parentheses;
By Mohammed Younus Shariff
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
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, 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
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
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 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
*= 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.
The ‘floor division and’ is equivalent to the expression x = x//a and takes the form
x//=a.
Operator Meaning
== is equal to
!= is not equal to
By Mohammed Younus Shariff
Examples:
>>>8 == 6+2
True
>>>6 != 6 False
>>>7 >= 5
True
Logical Operators
Python supports 3 logical operators:
or and not
Examples:
>>>(2==2) or (9<20)
True
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.
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
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.
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
Description Operators
1 Exponentiation **
Multiplication, division, *, /, %, //
3 modulo, and floor division
9 Equality operators == !=
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.
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
n=5
Python If Statements
Syntax:
if condition:
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.
a=20
if a>50:
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):
else:
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
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.
Since the value of “i” is not divisible by two, the else statement is executed.
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):
if (condition2):
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 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
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
for j in range(i):
print("*",end=' ')
print()
*
**
***
****
*****
By Mohammed Younus Shariff
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:
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:
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
l.py
Sum of 1 until 50: 1275
By Mohammed Younus Shariff
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