Python Module 1
Python Module 1
⮚ Features
⮚ How to install python interpreter
⮚ Basic Syntax
⮚ Variable and Data Types
⮚ Operator
⮚ Input-Output : standard input output
⮚ Conditional Statements
⮚ Looping
⮚ Control statements
⮚ Arrays vs lists
⮚ python data structures (list, tuple, dictionary)
What is python?
GUI
Software Development
Web Development
Artificial Intelligence
Why to Learn Python?
✔ It uses English keywords frequently where as other languages use punctuation, and it
has fewer syntactical constructions than other languages
Popular apps developed in Python
❖YouTube
❖Google
❖Dropbox
❖Quora
❖Instagram
❖Mozilla Firefox
Key advantages of learning Python:
⮚ Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
• It provides very high-level dynamic data types and supports dynamic type
checking.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java
(General purpose programming lang).
Hello World using Python
The most up-to-date and current source code, binaries, documentation, news, etc., is available on the
official website of Python https://www.python.org/
Windows Installation
• Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to
install.
• To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save
the installer file to your local machine and then run it to find out if your machine supports MSI.
• Run the downloaded file. 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 are done.
Python IDEs
✔ Pydev
✔ Pycharm
✔ Sublime Text
✔ Visual Studio Code
✔ Vim
First Python Program
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
Type the following text at the Python prompt and press the Enter −
If you are running new version of Python, then you would need to use print statement with parenthesis
as in print ("Hello, Python!"). However in Python version 2.4.3, this produces the following result −
Hello, Python!
Hello, Python!
▪ A Python identifier is a name used to identify a variable, function, class, module or other object.
▪ An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
▪ Python does not allow punctuation characters such as @, $, and % within identifiers.
▪ Python is a case sensitive programming language. Thus, Manpower and manpower are two different
identifiers in Python.
Python provides no braces to indicate blocks of code for class and function definitions or flow control.
Blocks of code are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block must be indented
the same amount. For example −
if True:
print "True"
else:
print "False"
Multi-Line Statements
For example −
total = item_one + \
item_two + \
item_three
▪ Statements contained within the [], {}, or () brackets do not need to use the line continuation
character.
For example −
days = ['Monday', 'Tuesday', 'Wednesday’,
'Thursday', 'Friday']
Quotation in Python
▪ Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the
same type of quote starts and ends the string.
▪ The triple quotes are used to span the string across multiple lines.
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is made up of multiple
lines and sentences."""
Comments in Python
▪ A hash sign (#) that is not inside a string literal begins a comment.
▪ All characters after the # and up to the end of the physical line are part of the comment and
the Python interpreter ignores them.
# First comment
print "Hello, Python!" # second comment
'''
This is a multiline comment.
'''
Variables
For example −
a = b = c = 1
a,b,c = 1,2,"john"
Standard Data Types
Number data types store numeric values. Number objects are created when you
assign a value to them.
For example −
var1 = 1
var2 = 10
Cont…
▪ Strings in Python are identified as a contiguous set of characters represented in the quotation marks.
▪ Python allows for either pairs of single or double quotes.
▪ Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the
beginning of the string and working their way from -1 at the end.
▪ The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator.
For example −
This
Hellowill produce the following result −
World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python Lists
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales’}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values
Cont…
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john’}
['dept', 'code', 'name’]
['sales', 6734, 'john']
Types of Operator
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
// Floor Division - The division of operands where the 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -
result is the quotient in which the digits after the 4, -11.0//3 = -4.0
decimal point are removed. But if one of the operands
is negative, the result is floored, i.e., rounded away
from zero (towards negative infinity) −
Python Comparison Operators
These operators compare the values on either sides of them and decide the relation among them. They
are also called Relational operators.
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 (a == b) is not true.
== becomes true.
If values of two operands are not equal, then condition (a != b) is true.
!= becomes true.
If the value of left operand is greater than the value of right (a > b) is not true.
> operand, then condition becomes true.
If the value of left operand is less than the value of right (a < b) is true.
< operand, then condition becomes true.
If the value of left operand is greater than or equal to the (a >= b) is not true.
>= value of right operand, then condition becomes true.
If the value of left operand is less than or equal to the (a <= b) is true.
<= value of right operand, then condition becomes true.
Python Assignment Operators
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b =
13; Now in the binary format their values will be 0011 1100 and 0000 1101 respectively.
Following table lists out the bitwise operators supported by Python language with an
example each in those, we use the above two variables (a and b) as operands −
a = 0011 1100
b = 0000 1101
-----------------
here are following logical operators supported by Python language. Assume variable a holds 10 and variable b
holds 20 then
Operator Description Example
and Logical AND If both the operands are true then (a and b) is true.
condition becomes true.
Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below −
Identity operators compare the memory locations of two objects. There are two Identity
operators explained below −
Operator Description Example
The following table lists all operators from highest precedence to lowest.
Sr.No. Operator & Description
1 ** 7 ^|
Exponentiation (raise to the power) Bitwise exclusive `OR' and regular `OR'
2 ~+- 8 <= < > >=
Comparison operators
Complement, unary plus and minus (method
9 <> == !=
names for the last two are +@ and -@)
Equality operators
3 * / % // 10 = %= /= //= -= += *= **=
Multiply, divide, modulo and floor division Assignment operators
4 +- 11 is is not
Addition and subtraction Identity operators
5 >> << 12 in not in
Right and left bitwise shift Membership operators
6 & 13 not or and
Logical operators
Bitwise 'AND'
Standard Input-Output
In python, for printing something on the console or the standard output screen, we use a
simple print() function.
For example, if you want to print some messages on the console, you can print it by using a
print() function.
Syntax of print() function is- print(message)
Let’s have a look>>>x=56
in the example-
>>>print("Your age is",x)
OUTPUT-
Your age is 56.
Python Input- input() function.
Till now, we are providing value to the program, but if you want that user will give input
value, then there is a function – input().
Input() function allows users to provide the value of their choice.
Let’s take a look in the example-
>>>age= input("Tell your Age:")
Tell your Age: 25
>>>print(age)
>>>age
OUTPUT- 25
‘25’
But, here the value entered by the user as an age “25” is a string, it is not a number. Because
input () function return type is string.
For converting this into a number, int() or float() functions are there.
>>>int('25’)
OUTPUT- 25
Output Formatting – format() function.
In a normal way, we write our code in a print() statement, but we can use format()
method to make our output more attractive and structured.
Let’s see in the example, how to use format() method.
>>> num1=5
>>> num2=7
>>> print('value of num1 is{0} and num2 is {1}'.format(num1,num2))
Here {0} represents index value 0, and {1} represents index value 1.
>>> num1=5
>>> num2=7
>>> print(f'value of num1 is{num1} and num2 is {num2}')
Cont…
>>> a=3.14254678
>>> b=10.2903348
>>>print('value of a is {0:.3} and b is {1:.3}'.format(a,b))
▪ The format() method formats the specified value(s) and insert them inside the string's
placeholder.
▪ The placeholder is defined using curly brackets: {}. Read more about the placeholders in the
Placeholder section below.
▪ The format() method returns the formatted string.
1 if statements
An if statement consists of a boolean expression followed by one or more
statements.
2 if...else statements
An if statement can be followed by an optional else statement, which
executes when the boolean expression is FALSE.
3 nested if statements
You can use one if or else if statement inside another if or else if
statement(s).
Single Statement Suites
var = 100
if ( var == 100 ) : print ("Value of expression is 100“)
print ("Good bye!“) ))
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that manages
the loop variable.
3 nested loops
You can use one or more loop inside any another while, for or do..while loop.
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 initialization
while i < 6: Condition
print(i)
i += 1 Increment/decrement
▪ 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.
Syntax:
for variable_name in sequence:
statement_1
statement_2
....
Examples
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"] for x in "banana":
for x in fruits: print(x)
print(x)
The for loop does not require an indexing variable to set beforehand.
Cont…
for x in range(6):
print(x)
Output: 0
2
Note that range(6) is not the values of 1 to 6, but the values 0 to 5.
3
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements.
1 break statement
Terminates the loop statement and transfers execution to the statement immediately
following the loop.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior
to reiterating.
3 pass statement
The pass statement in Python is used when a statement is required syntactically but you do
not want any command or code to execute.
break statement
▪ The purpose of this statement is to end the execution of the loop (for or while) immediately and the
program control goes to the statement after the last statement of the loop.
▪ If there is an optional else statement in while or for loop it skips the optional clause also.
Syntax :
while (expression1):
statement_1
statement_2
......
if expression2 :
break
Example
▪ The continue statement in Python returns the control to the beginning of the while loop. The continue
statement rejects all the remaining statements in the current iteration of the loop and moves the
control back to the top of the loop.
▪ The continue statement can be used in both while and for loops.
Example
▪ The pass statement in Python is used when a statement is required syntactically but you do not want
any command or code to execute.
▪ The pass statement is a null operation; nothing happens when it executes. The pass is also useful in
places where your code will eventually go, but has not been written yet
Example
Example : Output:
my_list = [10, "apple", 3.14, True] [10, 'apple', 3.14, True]
print(my_list)
Applications: 1. Storing and manipulating mixed data (e.g., student records with ID, name, marks)
2. Creating dynamic lists from user input or file data
3. Web scraping results collection
4. Temporary storage of varied data types (e.g., settings, logs, configurations)
List vs Array
List:
Example : Output:
my_list = [2, 1, 1, 0, 2,1] [2, 1, 1, 0, 2,1]
print(my_list)
Applications:
1. Storing and manipulating mixed data (e.g., student records with ID, name, marks)
2. Creating dynamic lists from user input or file data
3. Web scraping results collection
4. Temporary storage of varied data types (e.g., settings, logs, configurations)
List vs Array
Array:
An array is a collection of items stored at contiguous memory locations, typically of the
same data type. Unlike lists, arrays are more memory-efficient and faster for numeric data
operations.
Example : Output:
import array array('i', [10, 20, 30, 40])
my_array = array.array('i’, [2, 1, 1, 0, 2, 1])
print(my_array)
List vs Array
Array:
Applications: Use in Industry:
1. Data Science & Machine Learning: Arrays using
1. Numerical computations (large datasets)
NumPy for datasets, feature matrices
2. Image processing (pixel arrays)
2. Finance: Stock data analysis, financial modeling
3. Signal processing
using numerical arrays
4. Scientific computing
3. Healthcare & Bioinformatics: Medical imaging
5. Time series or sensor data
data, ECG signal arrays
4. Engineering: Simulation data, IoT sensor
readings, CAD geometry data
5. Gaming Industry: Graphics and sound data
arrays
Example: Multiply a sequence by 2
Using List:
my_list = [1, 2, 3]
result = my_list * 2
print(result)
Output
[1, 2, 3, 1, 2, 3] # Repeats the list