Download as pdf or txt
Download as pdf or txt
You are on page 1of 83

Python

Python is a powerful general-purpose programming language. It is used in web


development, data science, creating software, and so on. Fortunately for beginners,
Python has simple easy-to-use syntax. This makes Python an excellent language to learn
to program for beginners.

Why Learn Python?


 Python is easy to learn. Its syntax is easy and code is very readable.

 Python has a lot of applications. It's used for developing web applications, data science,
rapid application development, and so on.

 Python allows you to write programs in fewer lines of code than most of the
programming languages.

 The popularity of Python is growing rapidly. Now it's one of the most popular
programming languages.

Python is a cross-platform programming language, which means that it can run on


multiple platforms like Windows, macOS, Linux. It is free and open-source. Even though
most of today's Linux and Mac have Python pre-installed in it, the version might be out-
of-date. So, it is always a good idea to install the most current version.

The Easiest Way to Run Python

The easiest way to run Python is by using Thonny IDE.


The Thonny IDE comes with the latest version of Python bundled in it. So you don't have
to install Python separately.
Follow the following steps to run Python on your computer.

1. Download Thonny IDE.


2. Run the installer to install Thonny on your computer.
3. Go to: File > New. Then save the file with .py extension. For
example, hello.py, example.py, etc.
You can give any name to the file. However, the file name should end with .py
4. Write Python code in the file and save it.

Running Python using Thonny IDE

5. Then Go to Run > Run current script or simply click F5 to run it.
Install Python Separately
If you don't want to use Thonny, here's how you can install and run Python on your
computer.

1. Download the latest version of Python.

2. Run the installer file and follow the steps to install Python
During the install process, check Add Python to environment variables. This will add
Python to environment variables, and you can run Python from any part of the computer.

Also, you can choose the path where Python is installed.

Installing

Python on the computer


Once you finish the installation process, you can run Python.
Run Python in Immediate mode
Once Python is installed, typing python in the command line will invoke the interpreter
in immediate mode. We can directly type in Python code, and press Enter to get the
output.
Try typing in 1 + 1 and press enter. We get 2 as the output. This prompt can be used as a
calculator. To exit this mode, type quit() and press enter.

Running Python on the Command Line

Run Python in the Integrated Development Environment (IDE)

We can use any text editing software to write a Python script file.

We just need to save it with the .py extension. But using an IDE can make our life a lot
easier. IDE is a piece of software that provides useful features like code hinting, syntax
highlighting and checking, file explorers, etc. to the programmer for application
development.
By the way, when you install Python, an IDE named IDLE is also installed. You can use
it to run Python on your computer. It's a decent IDE for beginners.
When you open IDLE, an interactive Python Shell is opened.
Now you can create a new file and save it with .py extension. For example, hello.py
Write Python code in the file and save it. To run the file, go to Run > Run Module or
simply click F5.
Your first Python Program
Now that we have Python up and running, we can write our first Python program.

Let's create a very simple program called Hello World. A "Hello, World!" is a simple
program that outputs Hello, World! on the screen. Since it's a very simple program, it's
often used to introduce a new programming language to beginners.
Type the following code in any text editor or an IDE and save it as hello_world.py

print("Hello, world!")

Then, run the file. You will get the following output.
Hello, world!

More Examples

print(‘Hello World’)

print(100)

print(1,2,3) //multiple values can be printed and it must be separated by coma and output
will be 1 2 3 . Notice that in output, we have space as a separator because default
separator value is space.

Print(‘abc’,’xyz’,’aaa’,”qqq”) //both single quote or double quote can be used

Print( ) //in this case, only end argument default value will be printed which is “\n”

Print() //this will print new line

Print(1) //this will print 1

Print(end=”&”) //we have only end argument value here

Print(end=”&”)

Print(1)

Print(“hello”)

Print(end=”&”)

Print(1, end=”@”)

Print(“hello”)

Print(2)
Print(4)

Print(1,2, sep=’- - ‘) //output= 1—2

Print (“the answer is”, 100) //here we have string argument and number argument. Both
can be used

Print (“the answer is “ , 2 , sep = “:”) // output is the answer is: 2

Python Keywords
Keywords are the reserved words in Python.

We cannot use a keyword as a variable name, function name or any other identifier. They
are used to define the syntax and structure of the Python language. In Python, keywords
are case sensitive. There are 33 keywords in Python 3.7. This number can vary slightly
over the course of time.
All the keywords except True, False and None are in lowercase and they must be written
as they are.

Python Identifiers

An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
Rules for writing identifiers

1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or


digits (0 to 9) or an underscore _. Names like myClass, var_1 and print_this_to_screen,
all are valid example.
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name.

Keywords cannot be used as identifiers.

global = 1

Output

File "<interactive input>", line 1


global = 1
^
SyntaxError: invalid syntax

We cannot use special symbols like !, @, #, $, % etc. in our identifier.

a@ = 0

Output

File "<interactive input>", line 1


a@ = 0
^
SyntaxError: invalid syntax

An identifier can be of any length.


Things to Remember

Python is a case-sensitive language. This means, Variable and variable are not the same.
Always give the identifiers a name that makes sense. While c = 10 is a valid name,
writing count = 10 would make more sense, and it would be easier to figure out what it
represents when you look at your code after a long gap.
Multiple words can be separated using an underscore, like this_is_a_long_variable.
Python Statement
Instructions that a Python interpreter can execute are called statements. For example, a =
1 is an assignment statement. if statement, for statement, while statement, etc. are other
kinds of statements

Multi-line statement
In Python, the end of a statement is marked by a newline character. But we can make a
statement extend over multiple lines with the line continuation character (\). For example:

a=1+2+3+\
4+5+6+\
7+8+9

This is an explicit line continuation. In Python, line continuation is implied inside


parentheses ( ), brackets [ ], and braces { }. For instance, we can implement the above
multi-line statement as:

a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)

Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case
with [ ] and { }. For example:

colors = ['red',
'blue',
'green']

We can also put multiple statements in a single line using semicolons, as follows:

a = 1; b = 2; c = 3

Python Comments
Comments are very important while writing a program. They describe what is going on
inside a program, so that a person looking at the source code does not have a hard time
figuring it out.

In Python, we use the hash (#) symbol to start writing a comment.


Comments are for programmers to better understand a program. Python Interpreter
ignores comments.

#This is a comment
#print out Hello
print('Hello')

Multi-line comments
We can have comments that extend up to multiple lines. One way is to use the hash(#)
symbol at the beginning of each line. For example:

#This is a long comment


#and it extends
#to multiple lines

Another way of doing this is to use triple quotes, either ''' or """.

"""This is also a
perfect example of
multi-line comments"""

Python Variables
A variable is a named location used to store data in the memory. It is helpful to think of
variables as a container that holds data that can be changed later in the program. For
example,

number = 10

Here, we have created a variable named number. We have assigned the value 10 to the
variable.
You can think of variables as a bag to store books in it and that book can be replaced at
any time.

number = 10
number = 1.1

Initially, the value of number was 10. Later, it was changed to 1.1.
Assigning values to Variables in Python

We can use the assignment operator = to assign a value to a variable.


Example 1: Declaring and assigning value to a variable

website = "apple.com"
print(website)

Output

apple.com

In the above program, we assigned a value apple.com to the variable website. Then, we
printed out the value assigned to website i.e. apple.com

you don't have to explicitly define the variable type. It automatically knows
that apple.com is a string and declares the website variable as a string.

Example 2: Changing the value of a variable

website = "apple.com"
print(website)

# assigning a new value to website


website = "programiz.com"

print(website)

Output
apple.com
programiz.com

In the above program, we have assigned apple.com to the website variable initially.
Then, the value is changed to programiz.com.

Example 3: Assigning multiple values to multiple variables

a, b, c = 5, 3.2, "Hello"

print (a)
print (b)
print (c)

If we want to assign the same value to multiple variables at once, we can do this as:

x = y = z = "same"

print (x)
print (y)
print (z)

The second program assigns the same string to all the three variables x, y and z.

Assigning value to constant in Python

In Python, constants are usually declared and assigned in a module. Here, the module is a
new file containing variables, functions, etc which is imported to the main file. Inside the
module, constants are written in all capital letters and underscores separating the words.
Example 3: Declaring and assigning value to a constant

Create a constant.py:

PI = 3.14
GRAVITY = 9.8

Create a main.py:

import constant

print(constant.PI)
print(constant.GRAVITY)

Output

3.14
9.8

In the above program, we create a constant.py module file. Then, we assign the constant
value to PI and GRAVITY. After that, we create a main.py file and import
the constant module. Finally, we print the constant value.

Note: In reality, we don't use constants in Python. Naming them in all capital letters is a
convention to separate them from variables, however, it does not actually prevent
reassignment.

Rules and Naming Convention for Variables and constants

1. Constant and variable names should have a combination of letters in lowercase (a to z) or


uppercase (A to Z) or digits (0 to 9) or an underscore (_). For example:
2. snake_case

3. MACRO_CASE

4. camelCase

CapWords

5. Create a name that makes sense. For example, vowel makes more sense than v.
6. If you want to create a variable name having two words, use underscore to separate
them. For example:

7. my_name

current_salary

8. Use capital letters possible to declare a constant. For example:

9. PI

10. G

11. MASS

12. SPEED_OF_LIGHT

TEMP
13. Never use special symbols like !, @, #, $, %, etc.

14. Don't start a variable name with a digit.

Python Literals
Literals are representations of fixed values in a program. They can be numbers,
characters, or strings, etc. For example, 'Hello, World!' , 12 , 23.0 , 'C' , etc.
Literals are often used to assign values to variables or constants. For example,

site_name = 'hello.com'

In the above expression, site_name is a variable, and ‘hello.com' is a literal.

Python Numeric Literals


Numeric Literals are immutable (unchangeable). Numeric literals can belong to 3
different numerical types: Integer , Float , and Complex .

Python Boolean Literals


There are two boolean literals: True and False .

For example,

result1 = True

Here, True is a boolean literal assigned to result1 .

String and Character Literals in Python


Character literals are characters enclosed in a quote. For example,

some_character = 'S'

Here, S is a character literal assigned to some_character .

Similarly, String literals are sequences of Characters enclosed in quotation marks.

For example,

some_string = 'Python is fun'

Here, 'Python is fun' is a string literal assigned to some_string .

Special Literal in Python


Python contains one special literal None . We use it to specify a null variable. For
example,
value = None

print(value)

# Output: None

Here, we get None as an output as the value variable has no value assigned to it.
Python Data Types
Every value in Python has a datatype. Since everything is an object in Python
programming, data types are actually classes and variables are instance (object) of these
classes.

There are various data types in Python. Some of the important types are

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.
We can use the type() function to know which class a variable or a value belongs to.

Similarly, 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
print(a, "is of type", type(a))

a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))

Output

5 is of type <class 'int'>


2.0 is of type <class 'float'>
(1+2j) is complex number? True

Integers can be of any length, it is only limited by the memory available.

The float type in Python designates a floating-point number. float values are specified
with a decimal point. 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)

Notice that the float variable b got truncated.

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']

We can use the slicing operator to extract an item or a range of items from a list. The
index starts from 0 in Python.

a = [5,10,15,20,25,30,35,40]

# a[2] = 15
print("a[2] = ", a[2])

# a[0:3] = [5, 10, 15]


print("a[0:3] = ", a[0:3])

# a[5:] = [30, 35, 40]


print("a[5:] = ", a[5:])

Output

a[2] = 15
a[0:3] = [5, 10, 15]
a[5:] = [30, 35, 40]

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

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

Output

[1, 2, 4]

Python Tuple
Tuple is an ordered sequence of items same as a list. The only difference is that tuples are
immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than lists as they cannot
change dynamically.

It is defined within parentheses () where items are separated by commas.

t = (5,'program', 1+3j)

We can use the slicing operator [] to extract items but we cannot change its value.

t = (5,'program', 1+3j)

# t[1] = 'program'
print("t[1] = ", t[1])

# t[0:3] = (5, 'program', (1+3j))


print("t[0:3] = ", t[0:3])
# Generates error
# Tuples are immutable
t[0] = 10

Output

Traceback (most recent call last):


File "test.py", line 11, in <module>
t[0] = 10
TypeError: 'tuple' object does not support item assignment
Range
Range represents a sequence of numbers and they are not modifiable

Example

a = range(5)

01234

a[0] // gives you 0

a[1] //gives you 1

Another Example

# create a sequence of numbers from 0 to 3

numbers = range(4)

# iterating through the sequence of numbers

for i in numbers:

print(i)

# Output:

#0
#1
#2
#3

Note: range() returns an immutable sequence of numbers that can be easily converted
to lists, tuples, sets etc.
Syntax of range()
The range() function can take a maximum of three arguments:

range(start, stop, step)

The start and step parameters in range() are optional.


Now, let's see how range() works with different number of arguments.

Example 1: range() with Stop Argument


If we pass a single argument to range() , it means we are passing the stop argument.
In this case, range() returns a sequence of numbers starting from 0 up to the number
(but not including the number).

# numbers from 0 to 3 (4 is not included)


numbers = range(4)
print(list(numbers)) # [0, 1, 2, 3]

# if 0 or negative number is passed, we get an empty sequence


numbers = range(-4)
print(list(numbers)) # []

Example 2: range() with Start and Stop Arguments


If we pass two arguments to range() , it means we are passing start and stop arguments.

In this case, range() returns a sequence of numbers starting from start (inclusive) up
to stop (exclusive).

# numbers from 2 to 4 (5 is not included)


numbers = range(2, 5)
print(list(numbers)) # [2, 3, 4]

# numbers from -2 to 3 (4 is not included)


numbers = range(-2, 4)
print(list(numbers)) # [-2, -1, 0, 1, 2, 3]

# returns an empty sequence of numbers


numbers = range(4, 2)
print(list(numbers)) # []

Example 3: range() with Start, Stop and Step Arguments


If we pass all three arguments,

 the first argument is start

 the second argument is stop

 the third argument is step

The step argument specifies the incrementation between two numbers in the sequence.

# numbers from 2 to 10 with increment 3 between numbers


numbers = range(2, 10, 3)
print(list(numbers)) # [2, 5, 8]

# numbers from 1 to 4 with increment of 1


# range(0, 5, 1) is equivalent to range(5)
numbers = range(0, 5, 1)
print(list(numbers)) # [0, 1, 2, 3, 4]

Note: The default value of start is 0, and the default value of step is 1. That's
why range(0, 5, 1) is equivalent to range(5) .
range() in for Loop
The range() function is commonly used in a for loop to iterate the loop a certain
number of times. For example,
# iterate the loop 5 times
for i in range(5):
print(i, 'Hello')

Output
0 Hello
1 Hello
2 Hello
3 Hello
4 Hello

Set Type
A set is an unordered collection of elements. Its order is not maintained in the set. It
means that elements are not appear in the same order as they are entered into the set.

It also does not accept duplicate values

Sets are unordered so we cannot access its element by indexing.

Set is defined by values separated by commas inside braces {}

Example

A = {1,2,3,”test”}
B = {1,1,2,2,3,3}

We canot use A[0] to access an item

Example

a = {10,100,200}

{200, 10, 100}

Example

# create a set named student_id


student_id = {112, 114, 116, 118, 115}

# display student_id elements


print(student_id)

# display type of student_id


print(type(student_id))

Output

{112, 114, 115, 116, 118}


<class 'set'>

Example

a = {1,2,2,3,3,3}
print(a)

Output

{1, 2, 3}
Since, set are unordered collection, indexing has no meaning. Hence, the slicing
operator [] does not work.

>>> a = {1,2,3}
>>> a[1]
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
TypeError: 'set' object does not support indexing

Python Dictionary
In Python, dictionaries are defined within braces {} with each item being a pair in the
form key:value. keys are unique identifiers that are associated with each value. Key
and value can be of any type.

>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>

Example

# create a dictionary named names


names = {'A': 'B', 'C': 'D', 'E': 'F'}

print(names)

Output
{'A': 'B', 'C': 'D', 'E': 'F'}

In the above example, we have created a dictionary named names . Here,


1. Keys are 'A' , 'C' , 'E'

2. Values are 'B' , 'D' , 'F'

Access Dictionary Values Using Keys

We use keys to retrieve the respective value . But not the other way around. For
example,
# create a dictionary named capital_city
capital_city = {'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}

print(capital_city['Nepal']) # prints Kathmandu

print(capital_city['Kathmandu']) # throws error message

Here, we have accessed values using keys from the capital_city dictionary.
Since 'Nepal' is key, capital_city['Nepal'] accesses its respective value i.e. Kathmandu

However, 'Kathmandu' is the value for the 'Nepal' key, so capital_city['Kathmandu'] throws an
error message.

Example

d = {1:'value','key':2}
print(type(d))

print("d[1] = ", d[1])


print("d['key'] = ", d['key'])

# Generates error
print("d[2] = ", d[2])

Output

<class 'dict'>
d[1] = value
d['key'] = 2
Traceback (most recent call last):
File "<string>", line 9, in <module>
KeyError: 2
Python Type Conversion
In programming, type conversion is the process of converting data of one type to
another. For example: converting int data to str .

There are two types of type conversion in Python.

 Implicit Conversion - automatic type conversion

 Explicit Conversion - manual type conversion

Python Implicit Type Conversion


In certain situations, Python automatically converts one data type to another. This is
known as implicit type conversion.

Example 1: Converting integer to float


Let's see an example where Python promotes the conversion of the lower data type
(integer) to the higher data type (float) to avoid data loss.

integer_number = 123
float_number = 1.23

new_number = integer_number + float_number

# display new value and resulting data type


print("Value:",new_number)
print("Data Type:",type(new_number))
Output

Value: 124.23
Data Type: <class 'float'>

In the above example, we have created two


variables: integer_number and float_number of int and float type respectively.
Then we added these two variables and stored the result in new_number .

As we can see new_number has value 124.23 and is of the float data type.
It is because Python always converts smaller data types to larger data types to avoid
the loss of data.

Note:
 We get TypeError , if we try to add str and int . For example, '12' + 23 . Python is not
able to use Implicit Conversion in such conditions.
 Python has a solution for these types of situations which is known as Explicit
Conversion.

Explicit Type Conversion


In Explicit Type Conversion, users convert the data type of an object to required data
type.

We use the built-in functions like int() , float() , str() , etc to perform explicit type
conversion.
This type of conversion is also called typecasting because the user casts (changes) the
data type of the objects.
Example 2: Addition of string and integer Using Explicit
Conversion
num_string = '12'
num_integer = 23

print("Data type of num_string before Type Casting:",type(num_string))

# explicit type conversion


num_string = int(num_string)

print("Data type of num_string after Type Casting:",type(num_string))

num_sum = num_integer + num_string

print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))

Output

Data type of num_string before Type Casting: <class 'str'>


Data type of num_string after Type Casting: <class 'int'>
Sum: 35
Data type of num_sum: <class 'int'>

In the above example, we have created two


variables: num_string and num_integer with str and int type values respectively. Notice the
code,

num_string = int(num_string)

Here, we have used int() to perform explicit type conversion of num_string to integer
type.

After converting num_string to an integer value, Python is able to add these two
variables.
Finally, we got the num_sum value i.e 35 and data type to be int .

Key Points to Remember


1. Type Conversion is the conversion of an object from one data type to another
data type.

2. Implicit Type Conversion is automatically performed by the Python interpreter.

3. Python avoids the loss of data in Implicit Type Conversion.

4. Explicit Type Conversion is also called Type Casting, the data types of objects
are converted using predefined functions by the user.

5. In Type Casting, loss of data may occur as we enforce the object to a specific
data type.
Python Basic Input and Output
Python Output
In Python, we can simply use the print() function to print output. For example,
print('Python is powerful')

# Output: Python is powerful

Here, the print() function displays the string enclosed inside the single quotation.
Syntax of print()
In the above code, the print() function is taking a single parameter.

However, the actual syntax of the print function accepts 5 parameters

print(object= separator= end= file= flush=)

Here,

 object - value(s) to be printed


 sep (optional) - allows us to separate multiple objects inside print() .

 end (optional) - allows us to add add specific values like new line "\n" , tab "\t"

 file (optional) - where the values are printed. It's default value
is sys.stdout (screen)
 flush (optional) - boolean specifying if the output is flushed or buffered.
Default: False

Example 1: Python Print Statement


print('Good Morning!')
print('It is rainy today')
Output

Good Morning!
It is rainy today

In the above example, the print() statement only includes the object to be printed.
Here, the value for end is not used. Hence, it takes the default value '\n' .

So we get the output in two different lines.

Example 2: Python print() with end Parameter


# print with end whitespace
print('Good Morning!', end= ' ')

print('It is rainy today')

Output

Good Morning! It is rainy today

Notice that we have included the end= ' ' after the end of the first print() statement.
Hence, we get the output in a single line separated by space.

Example 3: Python print() with sep parameter


print('New Year', 2023, 'See you soon!', sep= '. ')
Output

New Year. 2023. See you soon!

In the above example, the print() statement includes multiple items separated by a
comma.
Notice that we have used the optional parameter sep= ". " inside the print() statement.
Hence, the output includes items separated by . not comma.

Example: Print Python Variables and Literals


We can also use the print() function to print Python variables. For example,
number = -10.6

name = "Programiz"

# print literals
print(5)

# print variables
print(number)
print(name)

Output

5
-10.6
Programiz

Example: Print Concatenated Strings


We can also join two strings together inside the print() statement. For example,
print('Programiz is ' + 'awesome.')
Output

Programiz is awesome.

Here,

 the + operator joins two strings 'Programiz is ' and 'awesome.'

 the print() function prints the joined string

Python Input
While programming, we might want to take the input from the user. In Python, we can
use the input() function.
Syntax of input()

input(prompt)

Here, prompt is the string we wish to display on the screen. It is optional.

Example: Python User Input


# using input() to take user input
num = input('Enter a number: ')

print('You Entered:', num)

print('Data type of num:', type(num))

Output

Enter a number: 10
You Entered: 10
Data type of num: <class 'str'>

In the above example, we have used the input() function to take input from the user and
stored the user input in the num variable.
It is important to note that the entered value 10 is a string, not a number.
So, type(num) returns <class 'str'> .

To convert user input into a number we can use int() or float() functions as:

num = int(input('Enter a number: '))

Here, the data type of the user input is converted from string to integer .

Python Arithmetic Operators

Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example

+ Addition Adds values on either side of the operator. a+b=


30
- Subtraction Subtracts right hand operand from left hand operand. a–b=-
10

* Multiplies values on either side of the operator a*b=


Multiplication 200

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand and returns b%a=
remainder 0

** Exponent Performs exponential (power) calculation on operators a**b =10


to the
power 20

9//2 = 4 and
// Floor Division - The division of operands where the result is the
9.0//2.0 = 4.0,
quotient in which the digits after the decimal point are removed. -11//3 = -4, -
11.0//3 = -4.0
But if one of the operands is negative, the result is floored, i.e.,
rounded away from zero (towards negative infinity) −

Python Comparison Operators

Comparison operators are used to compare two values:

Assume variable a holds 10 and variable b holds 20, then −


Operator Description Example

== If the values of two operands are equal, then the condition becomes (a == b) is
true. not true.

!= If values of two operands are not equal, then condition becomes (a != b) is


true. true.

> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.

< If the value of left operand is less than the value of right operand, (a < b) is
then condition becomes true. true.

>= If the value of left operand is greater than or equal to the value of (a >= b) is
right operand, then condition becomes true. not true.

<= If the value of left operand is less than or equal to the value of right (a <= b) is
operand, then condition becomes true. true.
Python Assignment Operators

Operator Description Example

= Assigns values from right side operands to left side operand c=a+b
assigns
value of a
+ b into c

+= Add It adds right operand to the left operand and assign the result c += a is
to left operand equivalent
to c = c +
a

-= Subtract It subtracts right operand from the left operand and assign the c -= a is
result to left operand equivalent
to c = c -
a

*= Multiply It multiplies right operand with the left operand and assign the c *= a is
result to left operand equivalent
to c = c *
a
/= Divide It divides left operand with the right operand and assign the c /= a is
result to left operand equivalent
to c = c /
a

%= Modulus It takes modulus using two operands and assign the result to c %= a is
AND left operand equivalent
to c = c %
a

**= Exponent Performs exponential (power) calculation on operators and c **= a is


assign value to the left operand equivalent
to c = c
** a

//= Floor It performs floor division on operators and assign value to the c //= a is
Division left operand equivalent
to c = c //
a
Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are true x < 5 and x < 10

or Returns True if one of the statements is true x < 5 or x < 4

not Reverse the result, returns False if the result is not(x < 5 and x <
true 10)
Python Built In Math Functions

Round method in Python

In Python, the round method rounded off the given number. If you have not specified
how many decimals points to rounding off given number then it rounds the given
number in the integer.

Syntax

round(number, digits)

Example: python round method

x = round(5.5)
print(x)

x = round(6.76543, 2)
print(x)

Output
6
6.77

Pow method in python

x power y (xy)

Example: pow example python

Let us see Python’s built-in pow () method with an example:


x = pow(2, 3)
print(x)

Abs method in python

One more great in-built method is available in Python. In Python, the ABS () method
is used when the absolute value of a given number is to be found.

Syntax

abs(n)

Example: ABS method in python


x = abs(-5.50)
print(x)

Output

5.50

Min method in python

In Python, the min() method is used when the smallest value is to be obtained from a
list or a given input list.

Syntax

min(n1, n2, n3, …)

Example: python get min of list

x = min(5, 10, 15, 25, 35, 45, 55) # list of items

print(x) // output

Output
5
Max method in python

In Python, the max() method is used when the largest value is to be obtained from a
list or a given input list.

Syntax

max(n1, n2, n3, …)

Example: python get max of list


x = max(5, 10, 15, 25, 35, 45, 55) # list of items

print(x)

Output
55

CMP method in python

The CMP() method in Python compares the two given objects and returns a result of
1,- 1, 0.

Syntax

cmp(a, b)

Example: python cmp function


# when x<y
x=1
y= 2
print(cmp(x, y))

# when x = y
x=2
y= 2
print(cmp(x, y))

# when x>y
x=3
y= 2
print(cmp(x, y))
Output
-1
0
1

Python hex method

Use of hex () method in python changed the given number to hexadecimal value.

Syntax

hex(number)

Example: python hex function


x = hex(555)
print(x)

Output
0x22b

Python oct method

Use of oct() method in python changed the given number to octal string.

Syntax

oct(number)

Example: python oct function


x = oct(555)
print(x)

Output
0o1053
int() method in python

The int() method returns an integer object from any number or string.

Example: string to int in python


# integer
print("int(123) is:", int(123))

# float
print("int(123.23) is:", int(123.23))

# string
print("int('123') is:", int('123'))

Output

int(123) is: 123


int(123.23) is: 123
int('123') is: 123

Python len method

The len() the function returns the number of items in an object.

Example
mylist = [1, 2, 3, 4, 5]
x = len(mylist)
print(x)

Output

Python Math Module

Sometimes when working with some kind of financial or scientific projects it becomes
necessary to implement mathematical calculations in the project. Python provides the
math module to deal with such calculations. Math module provides functions to deal with
both basic operations such as addition(+), subtraction(-), multiplication(*), division(/)
and advance operations like trigonometric, logarithmic, exponential functions.

Finding the power of a number

pow() function computes x**y. This function first converts its arguments into float and
then computes the power.

Example:

# Python code to demonstrate pow()

# version 1

print ("The value of 3**4 is : ",end="")

# Returns 81

print (pow(3,4))

Output

The value of 3**4 is : 81.0

Finding the absolute value

fabs() function returns the absolute value of the number.

# Python code to demonstrate the working of

# fabs()

# importing "math" for mathematical operations

import math

a = -10
# returning the absolute value.

print ("The absolute value of -10 is : ", end="")

print (math.fabs(a))

Output

The absolute value of -10 is : 10.0

Finding the Square root

sqrt() function returns the square root of the number.

# Python3 program to demonstrate the

# sqrt() method

# import the math module

import math

# print the square root of 0

print(math.sqrt(0))

# print the square root of 4

print(math.sqrt(4))

# print the square root of 3.5

print(math.sqrt(3.5))

Output
0.0

2.0

1.8708286933869707

Check if the value is infinity

isinf() function is used to check whether the value is infinity or not.

import math

print (math.isinf(math.pi))

Output

False

math.factorial() function

import math

x=5

# returning the factorial

print ("The factorial of 5 is : ", end ="")

print (math.factorial(x))

Output

120
Python Random Module

Python Random module is an in-built module of Python that is used to generate


random numbers in Python.

Random in Python Examples


Example: Printing a random value from a list in Python.

# import random
import random

# prints a random value from the list


list1 = [1, 2, 3, 4, 5, 6]
print(random.choice(list1))

Output
2

Generate Random Numbers in Python

random.randint() method is used to generate random integers between the given range.

Syntax: randint(start, end)


Example: Creating random integers

Syntax: randint(start, end)

Example: Creating random integers


# Python3 program explaining work
# of randint() function

# import random module


import random

# Generates a random number between


# a given positive range
r1 = random.randint(5, 15)
print("Random number between 5 and 15 is " (r1))

# Generates a random number between


# two given negative range
r2 = random.randint(-10, -2)
print("Random number between -10 and -2 is " (r2))

Output

Random number between 5 and 15 is 7

Random number between -10 and -2 is -9

Generate Random Float numbers in Python

A random.random() method is used to generate random floats between 0.0 to 1

Syntax: random.random()

# Python3 program to demonstrate


# the use of random() function .

# import random
from random import random

# Prints random item


print(random())

Output
0.3717933555623072
Randomly Select Elements from a List in Python

Example 1: Python random.choice() function is used to return a random item from a


list, tuple, or string.

import random

# prints a random value from the list


list1 = [1, 2, 3, 4, 5, 6]
print(random.choice(list1))

# prints a random item from the string


string = "geeks"
print(random.choice(string))

# prints a random item from the tuple


tuple1 = (1, 2, 3, 4, 5)
print(random.choice(tuple1))

Output
2
K
5

Example 2: Python random.sample() function is used to return a random item from a


list, tuple, or string.

Syntax: random.sample(sequence, length)


# import random
from random import sample

# Select Random number from List


# Prints list of random items of given length
list1 = [1, 2, 3, 4, 5]

print(sample(list1,3))

# Select Random number from Tuple


# Prints list of random items of given length
list2 = (4, 5, 6, 7, 8)

print(sample(list2,3))

# Select Random number from string


# Prints list of random items of given length
list3 = "45678"

print(sample(list3,3))

Output
[1, 5, 4]

[8, 5, 6]

['7', '4', '5']

Shuffle List in Python


A random.shuffle() method is used to shuffle a sequence (list). Shuffling means
changing the position of the elements of the sequence.

# import the random module


import random

# declare a list
sample_list = [1, 2, 3, 4, 5]
print("Original list : ")
print(sample_list)

# first shuffle
random.shuffle(sample_list)
print("\nAfter the first shuffle : ")
print(sample_list)

# second shuffle
random.shuffle(sample_list)
print("\nAfter the second shuffle : ")
print(sample_list)

Output:
Original list :

[1, 2, 3, 4, 5]

After the first shuffle :

[4, 3, 5, 2, 1]

After the second shuffle :

[1, 3, 4, 5, 2]

Python Random uniform() Method


Example
Return a random number between, and included, 20 and 60:

import random

print(random.uniform(20, 60))
Python Random randrange() Method
Example
Return a number between 3 and 9:

import random

print(random.randrange(3, 9))

Python Random sample() Method

Example
Return a list that contains any 2 of the items from a list:

import random

mylist = ["apple", "banana", "cherry"]

print(random.sample(mylist, k=2))

Output
['apple', 'cherry']
Conditional Statement
Decision making is required when we want to execute a code only if a certain condition is
satisfied.

The if…elif…else statement is used in Python for decision making.


Python if Statement Syntax

if test expression:

statement(s)

Here, the program evaluates the test expression and will execute statement(s) only if the
test expression is True.
If the test expression is False, the statement(s) is not executed.
In Python, the body of the if statement is indicated by the indentation. The body starts
with an indentation and the first unindented line marks the end.
Python interprets non-zero values as True. None and 0 are interpreted as False.
Example: Python if Statement

# If the number is positive, we print an appropriate message

num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")

num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")

When you run the program, the output will be:

3 is a positive number
This is always printed
This is also always printed.

In the above example, num > 0 is the test expression.


The body of if is executed only if this evaluates to True.
When the variable num is equal to 3, test expression is true and statements inside the
body of if are executed.
If the variable num is equal to -1, test expression is false and statements inside the body
of if are skipped.
The print() statement falls outside of the if block (unindented). Hence, it is executed
regardless of the test expression.

Python if...else Statement

Syntax of if...else

if test expression:

Body of if

else:
Body of else

The if..else statement evaluates test expression and will execute the body of if only when
the test condition is True.
If the condition is False, the body of else is executed. Indentation is used to separate the
blocks.
Example of if...else

# Program checks if the number is positive or negative


# And displays an appropriate message

num = 3

# Try these two variations as well.


# num = -5
# num = 0

if num >= 0:
print("Positive or Zero")
else:
print("Negative number")

Output

Positive or Zero

In the above example, when num is equal to 3, the test expression is true and the body
of if is executed and the body of else is skipped.
If num is equal to -5, the test expression is false and the body of else is executed and the
body of if is skipped.
If num is equal to 0, the test expression is true and body of if is executed and body of
else is skipped.

Python if...elif...else Statement

Syntax of if...elif...else

if test expression:

Body of if

elif test expression:

Body of elif

else:

Body of else

The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block and so on.
If all the conditions are False, the body of else is executed.
Only one block among the several if...elif...else blocks is executed according to the
condition.
The if block can have only one else block. But it can have multiple elif blocks.
statement in Python
Example of if...elif...else

'''In this program,


we check if the number is positive or
negative or zero and
display an appropriate message'''

num = 3.4

# Try these two variations as well:


# num = 0
# num = -4.5

if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

When variable num is positive, Positive number is printed.


If num is equal to 0, Zero is printed.
If num is negative, Negative number is printed.

Python Nested if statements

We can have a if...elif...else statement inside another if...elif...else statement. This is


called nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation is the only
way to figure out the level of nesting. They can get confusing, so they must be avoided
unless necessary.

Python Nested if Example

'''In this program, we input a number


check if the number is positive or
negative or zero and display
an appropriate message
This time we use nested if statement'''

num = float(input("Enter a number: "))


if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

Output 1

Enter a number: 5
Positive number

Output 2

Enter a number: -1
Negative number
Output 3

Enter a number: 0
Zero

Ternary Operator
Ternary operators provide a shorthand way to write conditional statements, which makes
the code more concise. Its just if-else condition in a single line

Example of Ternary Operator in Python

The ternary operator evaluates the condition first. If the result is true, it returns
the value_if_true. Otherwise, it returns value_if_false

For example

If we have normal if else situation for the following

Program

s = 10

If s > 5:

Print(“Yes”) //option 1

else:

Print(“No”) //option 2

Then, instead of so many lines, we can use ternary


Syntax is

Option1 if condition else option2

So above program can be

Print(“Yes”) if s > 5 else print(“No”)

We can also assign the result of Ternary to a variable

A = “Yes” if s > 5 else “No”

Print(A)

Another Example

marks = input('Enter the marks: ')

print("The result is Pass" if int(marks)>=35 else "The result is Fail")


Python For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a
string). With the for loop we can execute a set of statements, once for each item in a list, tuple, set
etc.

Example
Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

Output
apple
banana
cherry

Looping Through a String


Even strings are iterable objects, they contain a sequence of characters:

Example
Loop through the letters in the word "banana":

for x in "banana":
print(x)
Output
b
a
n
a
n
a
The break Statement
With the break statement we can stop the loop before it has looped through all the items:

Example
Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
break
Output
apple
banana

Example
Exit the loop when x is "banana", but this time the break comes before the print:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
break
print(x)
Output
Apple

The continue Statement


With the continue statement we can stop the current iteration of the loop, and continue with
the next:
Example
Do not print banana:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
continue
print(x)
Output
apple
cherry

The range() Function


To loop through a set of code a specified number of times, we can use the range() function,

The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.

Example
Using the range() function:

for x in range(6):
print(x)

Output

0
1
2
3
4
5

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.


The range() function defaults to 0 as a starting value, however it is possible to specify the
starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not
including 6):

Example
Using the start parameter:

for x in range(2, 6):


print(x)

Output

2
3
4
5

The range() function defaults to increment the sequence by 1, however it is possible to


specify the increment value by adding a third parameter: range(2, 30, 3):

Example
Increment the sequence with 3 (default is 1):

for x in range(2, 30, 3):


print(x)

Output

2
5
8
11
14
17
20
23
26
29
Else in For Loop
The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:

Example
Print all numbers from 0 to 5, and print a message when the loop has ended:

for x in range(6):
print(x)
else:
print("Finally finished!")
Output
0
1
2
3
4
5
Finally finished!

Note: The else block will NOT be executed if the loop is stopped by a break statement.

Example
Break the loop when x is 3, and see what happens with the else block:

for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")

Output
0
1
2

Nested Loops
A nested loop is a loop inside a loop.

Example
Print each adjective for every fruit:

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)

Output

red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry

The pass Statement


for loops cannot be empty, but if you for some reason have a for loop with no content, put in
the pass statement to avoid getting an error.

Example
for x in [0, 1, 2]:
pass
Output

Nothing

The while Loop


With the while loop we can execute a set of statements as long as a condition is true.

Example
Print i as long as i is less than 6:

i=1
while i < 6:
print(i)
i += 1
Output
1
2
3
4
5
Note: remember to increment i, or else the loop will continue forever.

The while loop requires relevant variables to be ready, in this example we need to define an
indexing variable, i, which we set to 1.

The break Statement


With the break statement we can stop the loop even if the while condition is true:

Example
Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Output
1
2
3

The continue Statement


With the continue statement we can stop the current iteration, and continue with the next:

Example
Continue to the next iteration if i is 3:

i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)

Output

1
2
4
5
6
The else Statement
With the else statement we can run a block of code once when the condition no longer is
true:

Example
Print a message once the condition is false:

i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

Output

1
2
3
4
5
i is no longer less than 6
Python Functions
A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function
In Python a function is defined using the def keyword:

Example
def my_function():
print("Hello from a function")

Calling a Function
To call a function, use the function name followed by parenthesis:

def my_function():
print("Hello from a function")

my_function()

Arguments
Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Parameters or Arguments?
A parameter is the variable listed inside the parentheses in the function
definition.

An argument is the value that is sent to the function when it is called.

Number of Arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the function
with 2 arguments, not more, and not less.

Example
This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil", "Refsnes")

If you try to call the function with 1 or 3 arguments, you will get an error:

Example
This function expects 2 arguments, but gets only 1:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil")
Arbitrary Arguments, *args
If you do not know how many arguments that will be passed into your function,
add a * before the parameter name in the function definition.

Example
If the number of arguments is unknown, add a * before the parameter name:

def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

Arbitrary Arguments are often shortened to *args in Python documentations.

Keyword Arguments
You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

Arbitrary Keyword Arguments, **kwargs


If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function
definition.
This way the function will receive a dictionary of arguments, and can access the
items accordingly:

Example
If the number of keyword arguments is unknown, add a double ** before the
parameter name:

def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

Default Parameter Value


The following example shows how to use a default parameter value.

If we call the function without argument, it uses the default value:

Example
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Passing a List as an Argument


You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.

E.g. if you send a List as an argument, it will still be a List when it reaches the
function:
Example
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

Return Values
To let a function return a value, use the return statement:

Example
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

The pass Statement


function definitions cannot be empty, but if you for some reason have
a function definition with no content, put in the pass statement to avoid getting
an error.

Example
def myfunction():
pass

You might also like