You are on page 1of 90

Python Programing

Future Of Python Programming


● It is one of the fastest growing language and has
undergone a successful span of more than 25 years.
● It is used for application development, web
development, game development, system
administration, scientific and numeric computing, GIS
and Mapping etc.
● Python is high-level programming language and easy
to learn as well as it reduces the coding effort
compare to other programming languages.

Source : www.w3trainingschool.com for education purpose only.


Source : https://data-flair.training/ for education purpose only.
Source : https://data-flair.training/ for education purpose only.
Source : https://data-flair.training/ for education purpose only.
Source : https://data-flair.training/ for education purpose only.
Python Skills

● Core Python (Basic knowledge between Python 2 and Python 3


is sufficient, complete knowledge of all modules is not required)
● Web Frameworks (Learn common Python frameworks such as
Django or Pandas)
● Object-relational mappers (Ability to connect to the database
with the help of ORM rather than SQL )
● Understand Multiprocess Architecture (Ability to write and
manage threads for high-performance)
● Building Python Applications (One should know how to package
up a code and deployment and release)
Python
 

Unit 1
Programs and Programming
• A program is a set of instructions.
• When you write down directions to your house for a
friend, you are writing a program. Your friend “executes”
that program by following each instruction in turn.
• Every program is written in terms of a few basic operations
that its reader already understands. For example, the set
of operations that your friend can understand might
include the following: “Turn left at Darwin Street,” “Go
forward three blocks,” and “If you get to the gas station,
turn around—you’ve gone too far.”
• Computers are similar but have a different set of
operations. Some operations are mathematical,
like “Add 10 to a number and take the square
root,” while others include “Read a line from the
file named data.txt,” “Make a pixel blue,” or
“Send email to the authors of this book.
• The most important difference between a
computer and an oldfashioned calculator is that
you can “teach” a computer new operations by
defining them in terms of old ones
• For example, you can teach the computer that
“Take the average” means “Add up the numbers
in a set and divide by the set’s size.”
• Defining new operations, and combining
them to do useful things, is the heart and
soul of programming
Prof. Jeannette Wing wrote computational
thinking is about the following:
• • Conceptualizing, not programming. Computer science is not
computer programming. Thinking like a computer scientist
means more than being able to program a computer. It
requires thinking at multiple levels of abstraction. •
• A way that humans, not computers, think. Computational
thinking is a way humans solve problems; it is not trying to get
humans to think like computers. Computers are dull and boring;
humans are clever and imaginative. We humans make
computers exciting. Equipped with computing devices, we use
our cleverness to tackle problems we would not dare take on
before the age of computing and build systems with
functionality limited only by our imaginations.
• • For everyone, everywhere. Computational thinking will be a
reality when it is so integral to human endeavors it disappears as
an explicit philosophy.
We choose Python for several reasons:

• It is free and well documented. In fact,


Python is one of the largest and best-
organized open source projects going.
• It runs everywhere. The reference
implementation, written in C, is used on
everything from cell phones to supercomputers,
and it’s supported by professional-quality
installers for Windows, Mac OS, and Linux
• It has a clean syntax. Yes, every language makes this claim, but
in the four years we have been using it at the University of
Toronto, we have found that students make noticeably fewer
“punctuation” mistakes with Python than with C-like languages.
• • It is relevant. Thousands of companies use it every day; it is
one of the three “official languages” at Google, and large
portions of the game Civilization IV are written in Python. It is
also widely used by academic research groups.
• • It is well supported by tools. Legacy editors like Vi and Emacs
all have Python editing modes, and several professional-quality
IDLEs are available
Python Overview

• Python is Interpreted: Python is processed at runtime by


the interpreter. You do not need to compile your program
before executing it. This is similar to PERL and PHP.
• Python is Interactive: You can actually sit at a Python
prompt and interact with the interpreter directly to write
your programs.
• Python is Object-Oriented: Python supports Object-
Oriented style or technique of programming that
encapsulates code within objects.
• Python is a Beginner's Language: Python is a great
language for the beginner-level programmers and supports
the development of a wide range of applications from
simple text processing to WWW browsers to games.
Two kinds of programs process high-level languages into low-level
languages:
Interpreters and compilers.

Interpreter

Compiler
● high-level program is called the source code, and the translated
program is called the object code or the executable.
● Once a program is compiled, you can execute it repeatedly without
further translation.
● There are two ways to use the interpreter: interactive mode and
script mode.
● In interactive mode, you type Python programs and the interpreter
displays the result:

● The chevron, >>> , is the prompt the interpreter uses to indicate that it
is ready.
● Alternatively, you can store code in a file and use the interpreter to
execute the contents of the file, which is called a script.
● By convention, Python scripts have names that end with “.py”
● To execute the script, you have to tell the interpreter the name of the file.
● If you have a script named “hello.py” and you are working in a UNIX
command window, you type “$python hello.py” .
● In other development environments, the details of executing scripts are
different.
History of Python
• Python was developed by Guido van Rossum in the late
eighties and early nineties at the National Research Institute
for Mathematics and Computer Science in the Netherlands.
• Python is derived from many other languages, including
ABC, Modula-3, C, C++,Algol-68, SmallTalk, Unix shell, and
other scripting languages.
• Python is copyrighted. Like Perl, Python source code is now
available under the GNU General Public License (GPL).
• Python is now maintained by a core development team at
the institute, although Guido van Rossum still holds a vital
role in directing its progress.
Python Features
• Easy-to-learn: Python has few keywords,
simple structure, and a clearly defined syntax.
This allows the student to pick up the
language quickly.
•  Easy-to-read: Python code is more clearly
defined and visible to the eyes.
•  Easy-to-maintain: Python's source code is
fairly easy-to-maintain.
• A broad standard library: Python's bulk of the library is
very portable and cross-platform compatible on UNIX,
Windows, and Macintosh.
•  Interactive Mode: Python has support for an
interactive mode which allows interactive testing and
debugging of snippets of code.
•  Portable: Python can run on a wide variety of
hardware platforms and has the same interface on all
platforms.
•  Extendable: You can add low-level modules to the
Python interpreter. These modules enable programmers
to add to or customize their tools to be more efficient.
• Databases: Python provides interfaces to all major
commercial databases.
•  GUI Programming: Python supports GUI
applications that can be created and ported to
many system calls, libraries, and windows
systems, such as Windows MFC, Macintosh, and
the X Window system of Unix.
•  Scalable: Python provides a better structure and
support for large programs than shell scripting.
Installing Python(Windows)
• 1. Open a Web browser and go to http://www.python.org.
• 2. Click the “Download” link.
• 3. You should see several links here, with names such as
“Python 2.4” and “Python 2.4Windows installer”. Click the
“Windows installer” link—it should give you the installer file
directly.
• 4. Run the downloaded file by double-clicking it in Windows
Explorer. This brings up the Python install wizard, which is
really easy to use. Just accept the default settings, wait until
the install is finished, and you’re ready to roll!
IDLE (Integrated Development and Learning
Environment)
• Assuming that the installation went well, you now have a
new program in your Windows
• Start menu. Run the Python Integrated Development
Environment (IDLE) by selecting Start ➤Programs ➤ Python2
➤ IDLE (Python GUI).
• If you feel a bit lost, simply select Help ➤ IDLE Help from the
menu, and you get a simple description of the various menu
items and basic usage. For more documentation on IDLE,
check out http://www.python.org/idle.
• If you press F1, or select Help ➤ Python Docs from the
menu, you will get the full Python documentation. (The
document there of most use to you will probably be
the“Library Reference.”) All the documentation is searchable.
The Difference Between Brackets, Braces, and Parentheses:
( ) → Parentheses
[ ] → Brackets
{ } → Braces
● Braces are used for different purposes. If you just want a list to
contain some elements and organize them by index numbers
(starting from 0), just use the [] and add elements as necessary.
● {} are special in that you can give custom id's to values like a =
{"John": 14}. Now, instead of making a list with ages and
remembering whose age is where, you can just access John's age by
a["John"].
● The [ ] is called a list and { } is called a dictionary (in Python).
● Dictionaries are basically a convenient form of list which allow you
to access data in a much easier way.
● ( ) parentheses is used to enclose method parameters; like print
(“hello”)
Values and Types:

●A value is one of the fundamental things—like a


letter or a number—that a program manipulates.
●The values we have seen so far are 2 (the result
when we added 1 + 1), and “Hello, World!”.
● These values belong to different types: 2 is an
integer, and “Hello, World!” is a string.
●You (and the interpreter) can identify strings
because they are enclosed in quotation marks.
●The print statement also works for integers.
Variables:
• One of the most powerful features of a
programming language is the ability to manipulate
variables.
• A variable is a name that refers to a value.
• The assignment statement creates new variables
and assigns them values:
State Diagram
● A common way to represent variables on paper is to write the name with
an arrow pointing to the variable’s value.
● This kind of figure is called a state diagram because it shows what state
each of the variables is in.
Rules for wrinting Variable names
● Programmers generally choose names for their variables that are meaningful—
they document what the variable is used for.
● Variable names can be arbitrarily long.
● They can contain both letters and numbers, but they have to begin with a letter.
● Although it is legal to use uppercase letters, by convention we don’t. If you do,
remember that case matters.
● For eg : Bruce and bruce are different variables.

● The underscore character ( _ ) can appear in a name. It is often used in names


with multiple words, such as my_name or price_of_tea_in_india.
● If you give a variable an illegal name, you get a syntax error:
Keywords

Keywords define the language’s rules and structure, and they cannot
be used as variable names. Python has thirty-one keywords:
Built-in Data Types
● In programming, data type is an important concept.
● Variables can store data of different types, and different types can do
different things.
● Since everything is an object in Python programming, data types are
actually classes and variables are instance (object) of these classes.
● Python has the following data types built-in by default, in these categories:
● Text Type: str
● Numeric Types: int, float, complex
● Sequence Types: list, tuple,
● Mapping Type: dict
● Set Types: set
● Boolean Type: bool
Python Numbers

● Integers, floating point numbers and complex numbers fall under Python numbers category.

They are defined as int, float and complex classes in Python.


● the isinstance() function is used to check if an object belongs to a particular class.

>>>a = 5
>>>print(a, "is of type", type(a))
>>>a = 2.0
Output
>>>print(a, "is of type", type(a))
5 is of type <class 'int'>
>>>a = 1+2j
2.0 is of type <class 'float'>
print(a, "is complex number?", isinstance(1+2j,complex))
(1+2j) is complex number?
True
● Integers can be of any length, it is only limited by the memory available.
● A floating-point number is accurate up to 15 decimal places. Integer and floating points

are separated by decimal points. 1 is an integer, 1.0 is a floating-point number.


● Complex numbers are written in the form, x + yj, where x is the real part and y is the

imaginary part. Here are some examples.


● >>> a = 1234567890123456789
● >>> a
● 1234567890123456789
● >>> b = 0.1234567890123456789
● >>> b
● 0.12345678901234568
● >>> c = 1+2j
● >>> c
● (1+2j)
Python List

● List is an ordered sequence of items. It is one of the most used datatype in Python and is

very flexible. All the items in a list do not need to be of the same type.
● Declaring a list is pretty straight forward. Items separated by commas are enclosed

within brackets [ ].

>>>a = [1, 2.2, 'python']


● Lists are mutable, meaning, the value of elements of a list can be altered.

>>>a = [1, 2, 3]
>>>a[2] = 4
>>>print(a)

[1, 2, 4]
Python Strings

● String is sequence of Unicode characters. We can use single quotes or double quotes to

represent strings. Multi-line strings can be denoted using triple quotes, ''' or """.

>>>s = "This is a string"


Output
print(s)
>>>s = '''A multiline This is a string

string''' A multiline

print(s) string

● Strings are immutable.


Python Set

● Set is an unordered collection of unique items. Set is defined by values separated by comma

inside braces { }. Items in a set are not ordered.

>>>a = {5,2,3,1,4}
# printing set variable
Output
>>>print("a = ", a)
a = {1, 2, 3, 4, 5}
# data type of variable a
<class 'set'>
>>>print(type(a))
● Sets have unique values. They eliminate duplicates.

>>>a = {1,2,2,3,3,3}

>>print(a)

Output

{1, 2, 3}
Type conversion:
● Sometimes, you may need to perform conversions between the built-in types. To
convert between types, you simply use the type-name as a function.
● Like int(), float(), str(), etc.
● There are several built-in functions to perform conversion from one data type to
another.

>>> float(5)
5.0
Conversion from float to int will truncate the value (make it closer to zero).

>>> int(10.6)
10
>>> int(-10.6)
-10
-----------------------------------------------------------------------------------------------

● Conversion to and from string must contain compatible values.

>>> float('2.5')
2.5
>>> str(25)
'25'
>>> int('1p')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1p'
---------------------------------------------------------------------

We can even convert one sequence to another.

● >>> set([1,2,3])
● {1, 2, 3}
● >>> tuple({5,6,7})
● (5, 6, 7)
● >>> list('hello')
● ['h', 'e', 'l', 'l', 'o']
To convert to dictionary, each element must be a pair:
>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
{3: 26, 4: 44}
• Operators and Operands:
• Operators are special symbols that represent computations like addition and
multiplication. The values the operator uses are called operands.
• Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators For example:
● Identity operators >>> 2+3
● Membership operators 5
● Bitwise operators
Here, + is the operator that performs addition. 2
and 3 are the operands and 5 is the output of the
operation.
Arithmetic operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication,
etc.

Opera Meaning Example


tor

+ Add two operands or unary plus x + y+ 2

- Subtract right operand from the left or unary x - y- 2


minus

* Multiply two operands x*y

/ Divide left operand by the right one (always x/y


results into float)

% Modulus - remainder of the division of left x%y


operand by the right (remainder
of x/y)

// Floor division - division that results into whole x // y


Assignment operators
● Assignment operators are used in Python to assign values to variables.
● a = 5 is a simple assignment operator that assigns the value 5 on the

right to the variable a on the left.


● There are various compound operators in Python like a += 5 that adds to

the variable and later assigns the same. It is equivalent to a = a + 5.


Operator Example Equivalent to

= x=5 x=5

+= x += 5 x=x+5

-= x -= 5 x=x-5

*= x *= 5 x=x*5

/= x /= 5 x=x/5

%= x %= 5 x=x%5

//= x //= 5 x = x // 5
Comparison operators

Comparison operators are used to compare values. It returns either True or False according to the condition.

Operato Meaning Exampl


r e

> Greater than - True if left operand is greater than the right x>y

< Less than - True if left operand is less than the right x<y

== Equal to - True if both operands are equal x == y

!= Not equal to - True if operands are not equal x != y

>= Greater than or equal to - True if left operand is greater than or x >= y
equal to the right

<= Less than or equal to - True if left operand is less than or equal x <= y
to the right
Logical operators

Logical operators are the and, or, not operators.

Operator Meaning Example

and True if both the operands are true x and y

or True if either of the operands is true x or y

not True if operand is false (complements the operand) not x


Bitwise operators
Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.

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

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)


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.

Opera Meaning Example


tor

is True if the operands are identical (refer to the same x is True


object)

is not True if the operands are not identical (do not refer to x is not
# Output: False
x1 = 5 the same object) True
print(x1 is not y1)
y1 = 5
x2 = 'Hello' # Output: True
y2 = 'Hello' print(x2 is y2)
x3 = [1,2,3]
# Output: False
y3 = [1,2,3]
print(x3 is y3)
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

in True if value/variable is found in the sequence 5 in x

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


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

# Output: True
print('H' in x)

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

# Output: True
print(1 in y)

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

● A statement is an instruction that the Python interpreter can


execute. We have seen two kinds of statements: print and
assignment.
● When you type a statement on the command line, Python
executes it and displays the result, if there is one. The
result of a print statement is a value. Assignment
statements don't produce a result.
● A script usually contains a sequence of statements. If there
is more than one statement, the results appear one at a
time as the statements execute
● For example, the script
● print 1
x=2
print x

● produces the output


● 1
2

● Again, the assignment statement produces no output.


Evaluating expressions
● An expression is a combination of values, variables, and operators. If you
type an expression on the command line, the interpreter evaluates it and
displays the result:
● >>> 1 + 1
2

● Although expressions contain values, variables, and operators, not every


expression contains all of these elements. A value all by itself is
considered an expression, and so is a variable.
● >>> 17
17
>>> x
2
● Confusingly, evaluating an expression is not quite the same thing
as printing a value.
● >>> message = 'Hello, World!'
>>> message
'Hello, World!'
>>> print message
Hello, World!

● When the Python interpreter displays the value of an expression, it


uses the same format you would use to enter a value. In the case of
strings, that means that it includes the quotation marks. But if you
use a print statement, Python displays the contents of the string
without the quotation marks.
● In a script, an expression all by itself is a legal statement,
but it doesn't do anything. The script
● 17
3.2
'Hello, World!'
1+1

● produces no output at all.


• Interactive Mode and ScriptMode:
● Interactive Mode Programming
● Invoking the interpreter without passing a script file as a parameter brings up the
following prompt-
• Script Mode Programming
• Invoking the interpreter with a script parameter begins execution
of the script and continues until the script is finished. When the
script is finished, the interpreter is no longer active.
• Let us write a simple Python program in a script. Python files have
the extension.py. Type the following source code in a test.py file-
Python Input
● Up until now, our programs were static. The value of variables was
defined or hard coded into the source code.
● To allow flexibility, we might want to take the input from the user. In
Python, we have the input() function to allow this. The syntax
for input() is:
● input([prompt])
● where prompt is the string we wish to display on the screen. It is
optional.
● >>> num = input('Enter a number: ')
● Enter a number: 10
● >>> num
● '10‘
● Here, we can see that the entered value 10 is a string, not a
number. To convert this into a number we can
use int() or float() functions
Python Output Using print() function

● . We use the print() function to output data to the standard output device


(screen). We can also output data to a file, but this will be discussed
later.
● An example of its use is given below.
● print('This sentence is output to the screen')
● Output
● This sentence is output to the screen
● Another example is given below:
● a=5
● print('The value of a is', a)
● Output
● The value of a is 5
● he sep separator is used between the values. It defaults
into a space character.
● After all values are printed, end is printed. It defaults into
a new line.
● Print(1, 2, 3, 4)
● print(1, 2, 3, 4, sep='*')
● print(1, 2, 3, 4, sep='#', end='&')
● Output
● 1234
● 1*2*3*4
● 1#2#3#4&
Built-In Functions 

● 1. abs()
● The abs() is one of the most popular Python built-in functions, which returns
the absolute value of a number. A negative value’s absolute is that value is
positive.
● >>> abs(-7)
● 7
● >>> abs(7)
● 7
● 2. chr()
● chr() Built In function returns the character in python for an ASCII
value.
● >>> chr(65)
● ‘A’
● >>> chr(97)
● ‘a’
● >>> chr(9)
● ‘\t’
● >>> chr(48)
● ‘0’
● 3.  float()
● This Python Built In function converts an int or a
compatible value into a float.
● >>> float(2)
● 2.0
● >>> float('3')
● 3.0
● 4. int()
● int() converts a value to an integer.
● >>> int('7')
● 7

● 5.  len()
● We’ve seen len() so many times by now. It returns the
length of an object.
● >>> len({1,2,2,3})
● 3
● 6. list()
● list() creates a list from a sequence of values.
● >>> list({1,3,2,2})
● [1, 2, 3]

● 7. max()
● A no-brainer, max() returns the item, in a sequence, with
the highest value of all.
● >>> max(2,3,4)
● 4
● >>> max([3,5,4])
● 5
● 8. min()
● min() returns the lowest value in a sequence.
● >>> min(3,5,1)
● 1

● 9. oct()
● oct() converts an integer to its octal representation.
● >>> oct(7)
● ‘0o7’
● >>> oct(8)
● ‘0o10’
● 10 .pow()
● pow() takes two arguments- say, x and y. It then returns
the value of x to the power of y.
● >>> pow(3,4)
● 81
● >>> pow(7,0)
● 1
● 11. round()
● round() rounds off a float to the given number of digits
(given by the second argument).
● >>> round(3.777,2)
● 3.78
● 12.  set()
● Of course, set() returns a set of the items passed to it.
● >>> set([2,2,3,1])
● {1, 2, 3}
● 13. sorted()
● Like we’ve seen before, sorted() prints out a sorted
version of an iterable. It does not, however, alter the
iterable.
● >>> sorted([1,3,2])
● [1, 2, 3]
● 14. str()
● str() takes an argument and returns the string equivalent
of it.
● >>> str('Hello')
● ‘Hello’
● >>> str(7)
● ‘7’
● >>> str(8.7)
● ‘8.7’
● 15. help()
● To get details about any module, keyword, symbol, or
topic, we use the help() function.

● 16. dict()
● dict(), as we have seen it, creates a python dictionary.
● >>> dict()
● {}
● >>> dict([(1,2),(3,4)])
● {1: 2, 3: 4}
● 17.complex()
● complex() function creates a complex number. We have
seen this is our article on Python Numbers.
● >>> complex(3)
● (3+0j)
● >>> complex(3.5)
● (3.5+0j)
● >>> complex(3+5j)
● (3+5j)
● 18. bool()
● bool() converts a value to Boolean.
● >>> bool(0.5)
● True
● >>> bool('')
● False
● 19. all()
● The all() function takes a container as an argument. This
Built in Functions returns True if all values in a python
iterable have a Boolean value of True. An empty value
has a Boolean value of False.
● >>> all((1,0,0))
● False
● >>> all((1,1,1))
● True
● 20. any()
● Like all(), it takes one argument and returns True if, even
one value in the iterable has a Boolean value of True.
● >>> any((1,0,0))
● True
Delete Statement

● The del keyword is used to delete objects. In Python


everything is an object, so the del keyword can also be
used to delete variables, lists, or parts of a list etc.
● More Examples
● Example
● Delete a variable:
● x = "hello"

del x

print(x)
● Delete the first item in a list:
● x = ["apple", "banana", "cherry"]

del x[0]

print(x)

● you can delete an entire tuple or string.


● my_tuple = (1, 2, 3) # deleting tuple
● del my_tuple
operator precedence

● When we group a set of values, variables, operators or function calls


that turn out as an expression. And once you execute that expression,
Python interpreter evaluates it as a valid expression.
● See a simple example given below.
● >>> 3 + 4
● 7
● Here, the ‘3 +4’ is a Python expression. It contains one operator and
two operands. However, a more complex statement can include
multiple operators.
● To evaluate complex expressions, Python lays out the rule of
precedence. It governs the order in which the operations take place.
● See the below example which combines multiple
operators to form a compound expression.
● # Multiplication get evaluated before # the addition
operation # Result: 17
● 5+4*3
● However, it is possible to alter the evaluation order with
the help of parentheses (). It can override the precedence
of the arithmetic operators.
● # Parentheses () overriding the precedence of the
arithmetic operators # Output: 27
● (5 + 4) * 3
Highest precedence at the top and
Lowest at the bottom.

● {} Parentheses (grouping)
● f(args…) Function call
● x[index:index] Slicing
● x[index] Subscription
● x.attribute Attribute reference
● ** Exponent
● ~x Bitwise not
● +x, -x Positive, negative
● *, /, % Product, division, remainder
● +, – Addition, subtraction
● <<, >> Shifts left/right
● & Bitwise AND
● ^ Bitwise XOR
● | Bitwise OR
● in, not in, is, is not, <, <=, >, >=,
● <>, !=, == Comparisons, membership, identity
● not x Boolean NOT
● and Boolean AND
● or Boolean OR
● lambda Lambda expression
Comments in Python

● Comments can be used to explain Python code.


● Comments can be used to make the code more readable.
● Comments can be used to prevent execution when
testing code.
● Creating a Comment
● Comments starts with a #, and Python will ignore them:
● Example
● #This is a comment
print("Hello, World!")
● Comments can be placed at the end of a line, and Python
will ignore the rest of the line:
● Example
● print("Hello, World!") #This is a comment
● Comments does not have to be text to explain the code, it
can also be used to prevent Python from executing code:
● Example
● #print("Hello, World!")
print("Cheers, Mate!")
● Multi Line Comments
● Python does not really have a syntax for multi line
comments.
● To add a multiline comment you could insert a # for each
line:
● Example
● #This is a comment
#written in
#more than just one line
print("Hello, World!")
● Since Python will ignore string literals that are not
assigned to a variable, you can add a multiline string
(triple quotes) in your code, and place your comment
inside it:
● Example
● """
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Assert Statement

● The assert keyword is used when debugging code.


● The assert keyword lets you test if a condition in your code
returns True, if not, the program will raise an AssertionError.
● You can write a message to be written if the code returns False,
check the example below.
● More Examples
● Example
● Write a message if the condition is False:
● x = "hello"

#if condition returns False, AssertionError is raised:


assert x == "goodbye", "x should be 'hello'"

You might also like