Python Module 1
Python Module 1
What is Python?
With its interpreted nature, Python's syntax and dynamic typing make it an ideal
language for scripting and rapid application development.
Python has many third-party libraries that can be used to make its functionality
easier. These libraries cover many domains, for example, web development,
scientific computing, data analysis, and more.
1. def func():
2. statement 1
3. statement 2
4. …………………
5. …………………
6. statement N
In the above example, the statements that are the same level to the right belong
to the function. Generally, we can use four whitespaces to define indentation.
In Python, comments can be added using the '#' symbol. Any text written after
the '#' symbol is considered a comment and is ignored by the interpreter. This
trick is useful for adding notes to the code or temporarily disabling a code
block. It also helps in understanding the code better by some other developers.
'If', 'otherwise', 'for', 'while', 'try', 'except', and 'finally' are a few reserved
keywords in Python that cannot be used as variable names. These terms are used
in the language for particular reasons and have fixed meanings. If you use these
keywords, your code may include errors, or the interpreter may reject them as
potential new Variables.
Features of Python
Python provides many useful features which make it popular and valuable from
the other programming languages. It supports object-oriented programming,
procedural programming approaches and provides dynamic memory allocation.
We have listed below a few essential features.
2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example,
the hello world program you simply type print("Hello World"). It will take only
one line to execute, while Java or C takes multiple lines.
3) Interpreted Language
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX,
and Macintosh, etc. So, we can say that Python is a portable language. It enables
programmers to develop the software for several competing platforms by
writing a program only once.
6) Object-Oriented Language
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code
and thus it can be used further in our Python code. It converts the program into
byte code, and any platform can use that byte code.
It provides a vast range of libraries for the various fields such as machine
learning, web developer, and also for the scripting. There are various machine
learning libraries, such as Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc.
Django, flask, pyramids are the popular framework for Python web
development.
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python
runs code line by line like C,C++ Java. It makes easy to debug the code.
11. Embeddable
The code of the other programming language can use in the Python source code.
We can use Python source code in another programming language as well. It
can embed other language into our code.
Python Applications
The GUI stands for the Graphical User Interface, which provides a smooth
interaction to any application. Python provides a Tk GUI library to develop a
user interface. Some popular GUI libraries are given below.
o Tkinter or Tk
o wxWidgetM
o Kivy (used for writing multitouch applications )
o PyQt or Pyside
3) Console-based Application
Python provides many free library or module which helps to build the
command-line apps. The necessary IO libraries are used to read and write. It
helps to parse argument and create console help text out-of-the-box. There are
also advance libraries that can develop independent console apps.
4) Software Development
This is the era of Artificial intelligence where the machine can perform the task
the same as the human. Python language is the most suitable language for
Artificial intelligence or machine learning. It consists of many scientific and
mathematical libraries, which makes easy to solve complex calculations.
6) Business Applications
o Gstreamer
o Pyglet
o QT Phonon
8) 3D CAD Applications
o Fandango (Popular )
o CAMVOX
o HeeksCNC
o AnyCAD
o RCAM
9) Enterprise Applications
Python can be used to create applications that can be used within an Enterprise
or an Organization. Some real-time applications are OpenERP, Tryton, Picalo,
etc.
Python contains many libraries that are used to work with the image. The image
can be manipulated according to our requirements. Some libraries of image
processing are given below.
o OpenCV
o Pillow
o SimpleITK
Installation on Windows
Now, Select Customize installation and proceed. We can also click on the
customize installation to choose desired location and features. Other important
thing is install launcher for the all user must be checked.
Here, under the advanced options, click on the checkboxes of " Install Python
3.11 for all users ", which is previously not checked in. This will checks the
other option " Precompile standard library " automatically. And the location of
the installation will also be changed. We can change it later, so we leave the
install location default. Then, click on the install button to finally install.
Step - 3 Installation in Process
The set up is in progress. All the python libraries, packages, and other python
default files will be installed in our system. Once the installation is successful,
the following page will appear saying " Setup was successful ".
Step - 4: Verifying the Python Installation
To verify whether the python is installed or not in our system, we have to do the
following.
Now, to work on our first python program, we will go the interactive interpreter
prompt(idle). To open this, go to "Start" and type idle. Then, click on open to
start working on idle.
First Python Program
In this Section, we will discuss the basic syntax of Python, we will run a simple
program to print Hello World on the console.
3.8M
457
Package in Java
Python provides us the feature to execute the Python statement one by one at the
interactive prompt. It is preferable in the case where we are concerned about the
output of each line of our Python program.
To open the interactive mode, open the terminal (or command prompt) and type
python (python3 in case if you have Python2 and Python3 both installed on
your system).
It will open the following prompt where we can execute the Python statement
and check their impact on the console.
The interpreter prompt is best to run the single-line statements of the code.
However, we cannot write the code every-time on the terminal. It is not suitable
to write multiple lines of code.
Using the script mode, we can write multiple lines code into a file which can be
executed later. For this purpose, we need to open an editor like notepad, create a
file named and save it with .py extension, which stands for "Python". Now, we
will implement the above example using the script mode.
1. print ("hello world"); #here, we have used print() function to print the message
on the console.
To run this file named as first.py, we need to run the following command on the
terminal.
Step - 1: Open the Python interactive shell, and click "File" then
choose "New", it will open a new blank script in which we can write our code.
Step -2: Now, write the code and press "Ctrl+S" to save the file.
Step - 3: After saving the code, we can run it by clicking "Run" or "Run
Module". It will display the output to the shell.
The output will be shown as follows.
Step - 4: Apart from that, we can also run the file using the operating system
terminal. But, we should be aware of the path of the directory where we have
saved our file.
Multi-line Statements
Multi-line statements are written into the notepad like an editor and saved it
with .py extension. In the following example, we have defined the execution of
the multiple code lines using the Python script.
Code:
Script File:
We may wish to describe the code we develop. We might wish to take notes of
why a section of script functions, for instance. We leverage the remarks to
accomplish this. Formulas, procedures, and sophisticated business logic are
typically explained with comments. The Python interpreter overlooks the
remarks and solely interprets the script when running a program. Single-line
comments, multi-line comments, and documentation strings are the 3 types of
comments in Python.
Aside from that, we can leverage comments to overlook specific code while
evaluating other code sections. This simple technique stops some lines from
running or creates a fast pseudo-code for the program.
Single-Line Comments
Code
Output:
Output:
This program's output will be identical to the example above. The computer
overlooks all content following #.
Multi-Line Comments
Python does not provide the facility for multi-line comments. However, there
are indeed many ways to create multi-line comments.
In Python, we may use hashtags (#) multiple times to construct multiple lines of
comments. Every line with a (#) before it will be regarded as a single-line
comment.
Code
1. # it is a
2. # comment
3. # extending to multiple lines
In this case, each line is considered a comment, and they are all omitted.
Code
Python Variables
Variable names can be a group of both the letters and digits, but they have to
begin with a letter or an underscore.
It is recommended to use lowercase letters for the variable name. Rahul and
rahul both are two different variables.
Identifier Naming
Python does not bind us to declare a variable before using it in the application.
It allows us to create a variable at the required time.
Every value has a datatype, and variables can hold values. Python is a powerfully comp
language; consequently, we don't have to characterize the sort of variable while announcing it
interpreter binds the value implicitly to its type.
1. a = 5
We did not specify the type of the variable a, which has the value five from an integer. The Py
interpreter will automatically interpret the variable as an integer.
We can verify the type of the program-used variable thanks to Python. The type() functi
Python returns the type of the passed variable.
Consider the following illustration when defining and verifying the values of various data typ
1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
Standard data types
A variable can contain a variety of values. On the other hand, a person's id must be stored
integer, while their name must be stored as a string.
The storage method for each of the standard data types that Python provides is specifie
Python. The following is a list of the Python-defined data types.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
The data types will be briefly discussed in this tutorial section. We will talk about every singl
of them exhaustively later in this instructional exercise.
Numbers
Numeric values are stored in numbers. The whole number, float, and complex qualities ha
place with a Python Numbers datatype. Python offers the type() function to determine a varia
data type. The instance () capability is utilized to check whether an item has a place with a spe
class.
When a number is assigned to a variable, Python generates Number objects. For instance,
1. a=5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
9. print(" c is a complex number", isinstance(1+3j,complex))
Output:
o Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and s
An integer can be any length you want in Python. Its worth has a place with int.
o Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accura
within 15 decimal places.
o Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y si
the genuine and non-existent parts separately. The complex numbers like 2.14j, 2.0 +
etc.
Sequence Type
String
The sequence of characters in the quotation marks can be used to describe the string. A string
be defined in Python using single, double, or triple quotes.
String dealing with Python is a direct undertaking since Python gives worked-in capabilitie
administrators to perform tasks in the string.
When dealing with strings, the operation "hello"+" python" returns "hello python," and
operator + is used to combine two strings.
Because the operation "Python" *2 returns "Python," the operator * is referred to as a repe
operator.
Example - 1
Output:
Example - 2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
List
Lists in Python are like arrays in C, but lists can contain data of different types. The thing
away in the rundown are isolated with a comma (,) and encased inside square sections [].
To gain access to the list's data, we can use slice [:] operators. Like how they worked with str
the list is handled by the concatenation operator (+) and the repetition operator (*).
Example:
Output:
Because we cannot alter the size or value of the items in a tuple, it is a read-only data structure
Example:
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
Traceback (most recent call last):
File "main.py", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
Dictionary
A dictionary is a key-value pair set arranged in any order. It stores a specific value for each
like an associative array or a hash table. Value is any Python object, while the key can hold
primitive data type.
The comma (,) and the curly braces are used to separate the items in the dictionary.
Output:
Boolean
True and False are the two default values for the Boolean type. These qualities are utiliz
decide the given assertion valid or misleading. The class book indicates this. False ca
represented by the 0 or the letter "F," while true can be represented by any value that is not ze
Look at the following example.
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
The data type's unordered collection is Python Set. It is iterable, mutable(can change
creation), and has remarkable components. The elements of a set have no set order; It might r
the element's altered sequence. Either a sequence of elements is passed through the curly b
and separated by a comma to create the set or the built-in function set() is used to create the s
can contain different kinds of values.
Python String
3.9M
460
Package in Java
Syntax:
1. str = "Hi Python !"
Here, if we check the type of the variable str using a Python script
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
Like other languages, the indexing of the Python strings starts from 0. For
example, The string "HELLO" is indexed as given in the below figure.
Consider the following example:
1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])
Output:
H
E
L
L
O
IndexError: string index out of range
1. # Given String
2. str = "JAVATPOINT"
3. # Start Oth index to end
4. print(str[0:])
5. # Starts 1th index to 4th index
6. print(str[1:5])
7. # Starts 2nd index to 3rd index
8. print(str[2:4])
9. # Starts 0th to 2nd index
10.print(str[:3])
11.#Starts 4th to 6th index
12.print(str[4:7])
Output:
JAVATPOINT
AVAT
VA
JAV
TPO
We can do the negative slicing in the string; it starts from the rightmost
character, which is indicated as -1. The second rightmost index indicates -2, and
so on. Consider the following image.
1. str = 'JAVATPOINT'
2. print(str[-1])
3. print(str[-3])
4. print(str[-2:])
5. print(str[-4:-1])
6. print(str[-7:-2])
7. # Reversing the given string
8. print(str[::-1])
9. print(str[-12])
Output:
T
I
NT
OIN
ATPOI
TNIOPTAVAJ
IndexError: string index out of range
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The
string object doesn't support item assignment i.e., A string can only be replaced
with new string since its content cannot be partially replaced. Strings are
immutable in Python.
Example 1
1. str = "HELLO"
2. str[0] = "h"
3. print(str)
Output:
Example 2
1. str = "HELLO"
2. print(str)
3. str = "hello"
4. print(str)
Output:
HELLO
hello
1. str = "JAVATPOINT"
2. del str[1]
Output:
1. str1 = "JAVATPOINT"
2. del str1
3. print(str1)
Output:
String Operators
Operato Description
r
+ It is known as concatenation operator used to join the strings given either sid
the operator.
[:] It is known as range slice operator. It is used to access the characters from
specified range.
not in It is also a membership operator and does the exact reverse of in. It returns true
particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases where we n
to print the actual meaning of escape characters such as "C://python". To de
any string as a raw string, the character r or R is followed by the string.
% It is used to perform string formatting. It makes use of the format specifiers use
C programming like %d or %f to map their values in python. We will discuss h
formatting is done in python.
Example
Consider the following example to understand the real use of Python operators.
1. str = "Hello"
2. str1 = " world"
3. print(str*3) # prints HelloHelloHello
4. print(str+str1)# prints Hello world
5. print(str[4]) # prints o
6. print(str[2:4]); # prints ll
7. print('w' in str) # prints false as w is not present in str
8. print('wo' not in str1) # prints false as wo is present in str1.
9. print(r'C://python37') # prints C://python37 as it is written
10.print("The string str : %s"%(str)) # prints The string str : Hello
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
Escape Sequence
Let's suppose we need to write the text as - They said, "Hello what's going on?"-
the given statement can be written in single quotes or double quotes but it will
raise the SyntaxError as it contains both single and double-quotes.
Example
Consider the following example to understand the real use of Python operators.
Output:
We can use the triple quotes to accomplish this problem but Python provides the
escape sequence.
The backslash(/) symbol denotes the escape sequence. The backslash can be
followed by a special character and it interpreted differently. The single quotes
inside the string must be escaped. We can apply the same as in the double
quotes.
Example -
1. # using triple quotes
2. print('''''They said, "What's there?"''')
3.
4. # escaping single quotes
5. print('They said, "What\'s going on?"')
6.
7. # escaping double quotes
8. print("They said, \"What's going on?\"")
Output:
2. \\ Backslash print("\\")
Output:
'
"
Hello World
Hello
World!
World!
Hello World!
Hello
World!
Hello
1. print("C:\\Users\\DEVANSH SHARMA\\Python32\\Lib")
2. print("This is the \n multiline quotes")
3. print("This is \x48\x45\x58 representation")
Output:
C:\Users\DEVANSH SHARMA\Python32\Lib
This is the
multiline quotes
This is HEX representation
We can ignore the escape sequence from the given string by using the raw
string. We can do this by writing r or R in front of the string. Consider the
following example.
1. print(r"C:\\Users\\DEVANSH SHARMA\\Python32")
Output:
C:\\Users\\DEVANSH SHARMA\\Python32
The format() method is the most flexible and useful method in formatting
strings. The curly braces {} are used as the placeholder in the string and
replaced by the format() method argument. Let's have a look at the given an
example:
Output:
Python allows us to use the format specifiers used in C's printf statement. The
format specifiers in Python are treated in the same way as they are treated in C.
However, Python provides an additional operator %, which is used as an
interface between the format specifiers and their values. In other words, we can
say that it binds the format specifiers to the values.
1. Integer = 10;
2. Float = 1.290
3. String = "Devansh"
4. print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi
I am string ... My value is %s"%(Integer,Float,String))
Output:
Python provides various in-built functions that are used for string handling.
Many String fun
Method Description
find(substring ,beginIndex, It returns the index value of the string where substrin
endIndex) found between begin index and end index.
isdigit() It returns true if all the characters are digits and there
least one character, otherwise False.
rsplit(sep=None, maxsplit = -1) It is same as split() but it processes the string from
backward direction. It returns the list of words in
string. If Separator is not specified then the string s
according to the white-space.
# Output
print(type(name))
Output:
Enter your name: GFG
Hello, GFG
<class 'str'>
Note: Python takes all the input as a string input by default. To convert it to
any other data type we have to convert the input explicitly. For example, to
convert the input to int or float we have to use the int() and float() method
respectively.
Example 2: Integer input in Python
Python3
add = num + 1
# Output
print(add)
Output:
Enter a number: 25
26
Here, we are using this function get user input and display to the user as well.
Output:
Enter a value: 45
You entered: 45
The input() method returns string value. So, if we want to perform arithmetic
operations, we need to cast the value first. See the example below.
Output:
Enter an integer: 12
Square of the value: 144
Python Operators
Introduction:
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
o Arithmetic Operators
Arithmetic Operators
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b = 20
- (Subtraction) It is used to subtract the second operand from the first operand. If the
operand is less than the second operand, the value results negative.
example, if a = 20, b = 5 => a - b = 15
/ (divide) It returns the quotient after dividing the first operand by the second oper
For example, if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a = 20,
(Multiplication) 4 => a * b = 80
% (reminder) It returns the reminder after dividing the first operand by the sec
operand. For example, if a = 20, b = 10 => a%b = 0
// (Floor It provides the quotient's floor value, which is obtained by dividing the
division) operands.
Program Code:
Output:
Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -
Comparison operator
Operato Description
r
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= The condition is met if the first operand is smaller than or equal to the sec
operand.
>= The condition is met if the first operand is greater than or equal to the sec
operand.
> If the first operand is greater than the second operand, then the condition beco
true.
< If the first operand is less than the second operand, then the condition beco
true.
Program Code:
Now we give code examples of Comparison operators in Python. The code is
given below -
Output:
Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -
Assignment Operators
Using the assignment operators, the right expression's value is assigned to the
left operand. There are some examples of assignment operators like =, +=, -=,
*=, %=, **=, //=. In the below table, we explain the works of the operators.
Operato Description
r
+= By multiplying the value of the right operand by the value of the left operand,
left operand receives a changed value. For example, if a = 10, b = 20 => a+ = b
be equal to a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand
assigns the modified value back to left operand. For example, if a = 20, b = 10
a- = b will be equal to a = a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand
assigns the modified value back to then the left operand. For example, if a = 1
= 20 => a* = b will be equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and ass
the reminder back to the left operand. For example, if a = 20, b = 10 => a %
will be equal to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4
= 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4/
1 to a.
Program Code:
Output:
Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -
a=b: False
a+=b: 38
a-=b: 26
a*=b: 192
a%=b: 2
a**=b: 1073741824
a//=b: 5
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. The
examples of Bitwise operators are bitwise OR (|), bitwise AND (&), bitwise
XOR (^), negation (~), Left shift (<<), and Right shift (>>). Consider the case
below.
For example,
1. if a = 7
2. b = 6
3. then, binary (a) = 0111
4. binary (b) = 0110
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000
10.Let, Binary of x = 0101
11. Binary of y = 1000
12.Bitwise OR = 1101
13.8 4 2 1
14.1 1 0 1 = 8 + 4 + 1 = 13
15.
16.Bitwise AND = 0000
17.0000 = 0
18.
19.Bitwise XOR = 1101
20.8 4 2 1
21.1 1 0 1 = 8 + 4 + 1 = 13
22.Negation of x = ~x = (-x) - 1 = (-5) - 1 = -6
23.~x = -6
In the below table, we are explaining the works of the bitwise operators.
Operator Description
& (binary A 1 is copied to the result if both bits in two operands at the same location ar
and) If not, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting
will be 1.
^ (binary xor) If the two bits are different, the outcome bit will be 1, else it will be 0.
~ (negation) The operand's bits are calculated as their negations, so if one bit is 0, the nex
will be 1, and vice versa.
<< (left shift) The number of bits in the right operand is multiplied by the leftward shift of
value of the left operand.
>> (right The left operand is moved right by the number of bits present in the r
shift) operand.
Program Code:
Now we give code examples of Bitwise operators in Python. The code is given
below -
Output:
Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -
a&b: 4
a|b: 7
a^b: 3
~a: -6
a<>b: 0
Logical Operators
Operato Description
r
and The condition will also be true if the expression is true. If the two expressio
and b are the same, then a and b must both be true.
or The condition will be true if one of the phrases is true. If a and b are the
expressions, then an or b must be true if and is true and b is false.
not If an expression a is true, then not (a) will be false and vice versa.
Program Code:
Now we give code examples of Bitwise operators in Python. The code is given
below -
Membership Operators
The membership of a value inside a Python data structure can be verified using
Python membership operators. The result is true if the value is in the data
structure; otherwise, it returns false.
Operato Description
r
not in If the first operand is not present in the second operand, the evaluation is true (
tuple, or dictionary).
Program Code:
1. x = ["Rose", "Lotus"]
2. print(' Is value Present?', "Rose" in x)
3. print(' Is value not Present?', "Riya" not in x)
Output:
Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -
Operato Description
r
Is If the references on both sides point to the same object, it is determined to be tru
is not If the references on both sides do not point at the same object, it is determined t
true.
Program Code:
Now we give code examples of Identity operators in Python. The code is given
below -
1. a = ["Rose", "Lotus"]
2. b = ["Rose", "Lotus"]
3. c=a
4. print(a is c)
5. print(a is not c)
6. print(a is b)
7. print(a is not b)
8. print(a == b)
9. print(a != b)
Output:
Now we compile the above code in python, and after successful compilation, we
run it. Then the output is given below -
True
False
False
True
True
False
Python Indentation
Example
if 5 > 2:
print("Five is greater than two!")
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
Example
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Example
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
In this example we use two variables, a and b, which are used as part of the if
statement to test whether b is greater than a. As a is 33, and b is 200, we know
that 200 is greater than 33, and so we print to screen that "b is greater than a".
Indentation
Example
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
Elif
The elif keyword is Python's way of saying "if the previous conditions were not
true, then try this condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Else
The else keyword catches anything which isn't caught by the preceding
conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater than b, so the first condition is not true, also
the elif condition is not true, so we go to the else condition and print to screen
that "a is greater than b".
You can also have an else without the elif:
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Short Hand If
If you have only one statement to execute, you can put it on the same line as the
if statement.
Example
If you have only one statement to execute, one for if, and one for else, you can
put it all on the same line:
Example
a=2
b = 330
print("A") if a > b else print("B")
This technique is known as Ternary Operators, or Conditional Expressions.
You can also have multiple else statements on the same line:
Example
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
And
Example
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Not
The not keyword is a logical operator, and is used to reverse the result of the
conditional statement:
Example
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
Nested If
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Python Loops
while loops
for loops
With the while loop we can execute a set of statements as long as a condition is
true.
Example
i=1
while i < 6:
print(i)
i += 1
Output-
1
2
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.
Code-
i=1
num = 5
print(i*num)
i += 1
Output:
10
15
20
25
30
35
40
45
50
With the break statement we can stop the loop even if the while condition is
true:
Example
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Output-
3
The continue Statement
With the continue statement we can stop the current iteration, and continue with
the next:
Example
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Output-
With the else statement we can run a block of code once when the condition no
longer is true:
Example
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Output-
A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works
more like an iterator method as found in other object-orientated programming
languages.
With the for loop we can execute a set of statements, once for each item in a
list, tuple, set etc.
Example
Output
apple
banana
cherry
The for loop does not require an indexing variable to set beforehand.
Example
for x in "banana":
print(x)
Output
b
a
n
a
n
a
With the break statement we can stop the loop before it has looped through all
the items:
Example
Output
apple
banana
Example
Exit the loop when x is "banana", but this time the break comes before the print:
Output
apple
With the continue statement we can stop the current iteration of the loop, and
continue with the next:
Example
Output
Apple
cherry
Example
for x in range(6):
print(x)
output
6
Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
Example
Example
Nested Loops
The "inner loop" will be executed one time for each iteration of the "outer
loop":
Example
Output
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
Python Functions
A function is a block of code which only runs when it is called.
Example
def my_function():
print("Hello from a function")
Calling a Function
Example
def my_function():
print("Hello from a function")
my_function()
Output:
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:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Output:
Emil Refsnes
Tobias Refsnes
Linus Refsnes
Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information
that are passed into a function.
Number of Arguments
Example
my_function("Emil", "Refsnes")
Output:
Emil Refsnes
Default Parameter Value
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Output:
I am from Sweden
I am from India
I am from Norway
I am from Brazil
Syntax
This function accepts any count of inputs but only evaluates and returns one
expression. That means it takes many inputs but returns only one output.
Example
Now we gave an example of a lambda function that adds 4 to the input number
is shown below.
1. # Code to demonstrate how we can use a lambda function for adding 4 numbers
2. add = lambda num: num + 4
3. print( add(6) )
Output:
Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -
10
Here we explain the above code. The lambda function is "lambda num: num+4"
in the given programme. The parameter is num, and the computed and returned
equation is num * 4.
There is no label for this function. It generates a function object associated with
the "add" identifier. We can now refer to it as a standard function. The lambda
statement, "lambda num: num+4", is written using the add function, and the
code is given below: Program Code 2:
Now we gave an example of a lambda function that adds 4 to the input number
using the add function. The code is shown below -
Output:
Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -
10
Program Code 3:
1. a = lambda x, y : (x * y)
2. print(a(4, 5))
Output:
Now we compile the above code in python, and after successful compilation, we
run it. Then the output is given below -
20
Program Code 4:
Now we gave another example of a lambda function that adds 2 numbers and
return one result. The code is shown below -
1. a = lambda x, y, z : (x + y + z)
2. print(a(4, 5, 5))
Output:
Now we compile the above code in python, and after successful compilation, we
run it. Then the output is given below -
14
Map():
The map() function executes a specified function for each item in an iterable.
The item is sent to the function as a parameter.
Syntax
map(function, iterables)
def myfunc(n):
return len(n)
Parameter Values
Parameter Description
More Examples
Example
Make new fruits by sending two iterable objects into the function:
Let's construct a module. Save the file as example_module.py after entering the
following.
Example:
1. # Here, we are creating a simple Python program to show how to create a modul
e.
2. # defining a function in the module to reuse it
3. def square( number ):
4. # here, the above function will square the number passed as the input
5. result = number ** 2
6. return result # here, we are returning the result of the function
In Python, we may import functions from one module into our program, or as
we say into, another module.
For this, we make use of the import Python keyword. In the Python window, we
add the next to import keyword, the name of the module we need to import. We
will import the module we defined earlier example_module.
Syntax:
1. import example_module
We may use the dot operator to use the functions using the module name. For
instance:
Example:
1. # here, we are calling the module square method and passing the value 4
2. result = example_module.square( 4 )
3. print("By using the module square of number is: ", result )
Output:
There are several standard modules for Python. The complete list of Python
standard modules is available. The list can be seen using the help command.
Similar to how we imported our module, a user-defined module, we can use an
import statement to import other standard modules.
Using the import Python keyword and the dot operator, we may import a
standard module and can access the defined functions within it. Here's an
illustration.
Code
1. # Here, we are creating a simple Python program to show how to import a stand
ard module
2. # Here, we are import the math module which is a standard module
3. import math
4. print( "The value of euler's number is", math.e )
5. # here, we are printing the euler's number from the math module
Output: