0% found this document useful (0 votes)
2 views

BDS306B_Module1

This document provides an overview of Python programming, covering its introduction, features, and fundamental concepts such as variables, data types, operators, and I/O functions. It details various data types including primitive and non-primitive types, as well as operations on strings, lists, and dictionaries. Additionally, it explains Python syntax, comments, and formatted print functions, making it a comprehensive guide for beginners in Python programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

BDS306B_Module1

This document provides an overview of Python programming, covering its introduction, features, and fundamental concepts such as variables, data types, operators, and I/O functions. It details various data types including primitive and non-primitive types, as well as operations on strings, lists, and dictionaries. Additionally, it explains Python syntax, comments, and formatted print functions, making it a comprehensive guide for beginners in Python programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Semester : III

Subject : Python Subject Code : BDS306B


Module 1
Contents
Reference - Textbook1 – Chapter 3 (3.2, 3.3, 3.4, 3.6, 3.7, 3.9, 3.10)

 Introduction to Python
 Elements of Python Language
 Python block structure
 Variables
 Assignment statement
 Data types in python
 Operators
 I/O functions (formatted and unformatted)

Introduction to Python

Python is an interpreted, high level and general purpose programming language. It was developed by
Guido Von Rossum (Netherlands). The design began in late 1990 and it was first released in February,
1991.

Features of Python

1. A simple language which is easier to learn. It has simple syntax.


2. Free and Open Source.
3. Platform independent.
4. Portable
5. Robust
6. Interpreted language
7. Rich set of libraries
8. Object Oriented
9. Embedded and Extensible
10. Dynamically typed
Elements of Python Language

Token

Basic building block or lexical unit of a program is called token.

Types of tokens

1. Variable
2. Data type
3. Literal
4. Constant
5. Operators
6. Keywords
7. Punctuators
8. Identifiers

Variable

Variable is a named memory location to store a value (number or character) that can change anywhere in
the program. Variables in python are dynamically typed – variable can be assigned a value without being
declared. Data type of a variable is determined automatically at the time of initialization.

Assigning values to variables

Multple variables can be assigned to a single value in a single statement


a=b=c=3
Multiple variables can be assigned different values in a single statement
a,b = 4,5

id()

id function when used with variable gives address of memory location. Two or more variables storing
same integer value will be pointing to same memory location.

Example :
x = 23
y = 23

id(x) will be equal to id(y) as x and y storing same integer value. Once x or y value is changed
id(x) will not be equal to id(y)

Data type

Data type determines the type of value stored in a variable. There are two kinds of data types.
Primitive and non-primitive data types.
Primitive data types in python are int, float, bool, complex
Non-primitive data types are complex, str, list, tuple, set, etc. Non-primitive data types are also called as
collection data type.
Example :
x = 123
type(x)
output :
<class 'int'>

y = 123.4566
type(x)
output :
<class 'float'>

str1 = “python”
type(str1)
output :
<class 'str'>

c = 3 + 5j
type(c)
print(c.real)
print(c.imag)
output:
3.0
5.0
<class 'complex'>

x = True
type(x)
output :
<class 'bool'>

Non-primitive data types or Collection data types


String
Group of characters (alphabets, digits, punctuations, etc) enclosed in single quote, double
quote or triple quote is string. String is immutable and ordered.

x = “a5$*ag”
type(x)
print(x[2]) # each character can be accessed using position(index) and hence ordered
x[3] = ‘z’ # error as string immutable and it cannot be changed
output:
<class 'str'>
$

Lists
Group of values of any data type enclosed in square brackets is called list. It is mutable and
ordered.

Example :
lst1 = [1,’a’,3.45]
type(lst1)
print(lst1[0]) # values in list can be accessed using position (index) and hence ordered
lst1[2] = ‘abc’ # as list is mutable, list can be modified
output :
<class 'list'>
1

Tuples

Group of values of any data type enclosed in braces is called tuple. It is immutable and ordered.

Example :

t1 = (1,5.6,”xyz”)
type(t1)
t1[1] = 34.5 # error as tuple is immutable and cannot be changed
output:
<class 'tuple'>

Byte and Byte Arrays

Byte data type is used to store group of integers in range 0-255. It immutable and ordered.

Example :
l st= [10,20,30]
b = bytes(lst)
type(b)
lst2 = bytes([10,20,456] )# error as only 0-255 can be stored in bytes
b[0] = 77 # error as bytes is immutable
for x in b :
print(x)
output:
<class 'bytes'>
10
20
30
Bytearray is same as byte except that bytearray is mutable
lst= [10,20,30]
b = bytearray(lst)
print(type(b))
lst2 =bytearray( [10,20,456] )# error as only 0-255 can be stored in bytes
b[0] = 77 # error as bytes is immutable
for x in b :
print(x)
output:
<class 'bytearray'>
77
20
30
Bytes and Bytearray is used to store image, audio and video files.
Dictionary

group of key value pair enclosed in flower bracket is called dictionary. Every value in dictionary
is key and value separated by “:”. It is mutable and unordered.

Rules :
1. In a dictionary, no two keys can be same.
2. data type of a key must be immutable

Example :
d1 = {'a':97, 'b':98,'c':99}
print(type(d1))
print(d1['b']) # values in dictionary is accessed using key and not position and hence
unordered
d1['c'] = 101 # values can be changed and keys can be added to dictionary and hence
# mutable
d1['d'] = 100
#d1[['e','f','g']]= [102,103,104] # error as key value must be immutable
output:
<class 'dict'>
98
Sets/Frozen sets

Set is group of value of any data types enclosed in flower brackets. It is mutable and
unordered. Duplicate values are not allowed in sets.
Example :
s1 = {1,2,3,5}
type(s1)
output:
<class 'set'>
Frozenset is same as set except that frozenset is immutable
To create frozenset :
s1 = frozenset({1,2,4,5})
type(s1)
output:
<class 'frozenset'>

Operations on lists, string, tuple

indexing – accessing elements in sequence object using position is called indexing.


Index values starts from 0. In python, negative indexing is allowed and
it starts from -1 in reverse order.

Example : str1 = “Python”


str1[0] is “P”
str1[-1] is “n” # item in reverse order

lst = [10,20,30,40]
lst[0] is 10
lst[-1] is 40
lst[-2] is 30 # second item from right side
slicing - slicing is the process of extracted part of a sequence object.
Example :
lst = [10,20,30,40,50,60,70,80,90,100]
print(lst[0:5])
print(lst[5:])
print(lst[5:8])
print(lst[5:10:2])
print(lst[5::2])
print(lst[::-1])
print(lst[::-2])
print(lst[-3:])
print(lst[:-3])
Output :
[10, 20, 30, 40, 50]
[60, 70, 80, 90, 100]
[60, 70, 80]
[60, 80, 100]
[60, 80, 100]
[100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
[100, 80, 60, 40, 20]
[80, 90, 100]
[10, 20, 30, 40, 50, 60, 70]
concatenation - ‘+’ acts as concatenation operator when used with strings, lists and tuples
Example :
lst1 = [10,20]
lst2 = [30,40]
lst3 = lst1 + lst2
print(lst3)
str1 = “python”
str2 = “language”
str3 = str1 + str2
print(str3)
output :
[10, 20, 30, 40]
pythonlanguage
repetition - ‘*’ operator when used with strings, lists and tuples acts as repetition operators

Example :
lst1 = [10,20]
print(lst1 * 3)
str1 = "python"
print(lst1 * 4)

[10, 20, 10, 20, 10, 20]


pythonpythonpythonpython

Literals - Literals are fixed values (numeric or character) in a program.


Integer Literal
Decimal Integer Literal - an integer with decimal base is decimal integer literal
Binary Integer Literal – binary number preceded by 0b is binary integer literal
x = 0b11010
Octal Integer Literal – ocatal number preceded by 0o is octal integer literal
x = 0o231
Hexadecimal Integer Literal – hexadecimal number preceded by 0x is hexadecimal integer
literal
x = 0xa2e3
Float Literal
Fractional Float Literal – float value in decimal form is fractional float literal 234.56

Exponent Float Literal – float value in exponent form is exponent float literal
234.5678 can be expressed as 23.45678e-01

String Literal

Single character or group of characters enclosed in single quote, double quote or triple quote is
called string literal. Triple quotes are used to store or assign multi line strings.
x = ‘a’
y = “a”
z = ‘’’a’’’
str1 = ‘Python’
str2 = “Language”
str3 = ‘’’Java’’’

Operators - Operators are symbols used to perform calculation, comparison and joining
expressions.

Operators in Python with precedence and associativity

Python follows PEDMAS rule to evaluate expressions with arithmetic operators

Parenthesis
Exponent
Division
Multiplication
Addition
Subtraction
Integer division operator (//) - used to extract only integer part after division and ignore decimal part
Example – 14//5 =2

Reminder Operator (%) – used to get remainder after division


Example – 14 % 5 = 4

Shift Operator (<<, >>) – used to shift binary numbers by 1 or more bits to the left or right
left shift – zeros will be added at he end
Example :
11010 << 2 = 1101000 ( 2 zeros are added)
11010 << 3 = 11010000 ( 3 zeros are added)
right shift – bits from end or right is ignored
11010 >> 2 = 110 ( last 2 bits ignored)
11010 >> 3 = 11 ( last 3 bits are ignored)

Bitwise Operator ( |, &, ^, ~) -

bitwise or (|) -
Truth Table for bitwise or
0|0=0
0|1=1
1|0=1
1|1=1
Example -
x = 10 ( 1010 in binary)
y = 12 ( 1100 in binary)
x | y = 1110 (using truth table)

bitwise and (&) -


Truth Table for bitwise or
0&0=0
0&1=0
1&0=0
1&1=1

x = 10 ( 1010 in binary)
y = 12 ( 1100 in binary)
x & y = 1000 (using truth table)
bitwise exclusive or (^) -
Truth Table for bitwise or
0^0=0
0^1=1
1^0=1
1^1=0
Example -
x = 10 ( 1010 in binary)
y = 12 ( 1100 in binary)
x ^ y = 0110 (using truth table)
bitwise complement (~) - is unary operator
Example -
x = 12
~x = -(x+1) = -(12+1) = -13
Membership operator (in, not in)– used to check if a value exists in sequence object (list, tuple, string,
etc)

str1 = “python”
“p” in str1 returns True
“p” not in str1 returns False

Identity operator (is, is not) – used to check if variables are pointing to same object or same memory
location

x = y = 12
x is y returns True
x is not y returns False
z = 14
x is z returns False

Keywords – Words that have meaning in a programming language are called keywords or reserved
words.
Example - for, else, if, etc are keywords
xyz, num, n1, etc. are not keywords

Punctuators – Symbols used for specific purpose

Example - :,(,{,),}, etc.

Comments in Python

Comments are lines in program that are ignored by compiler or interpreter. They are used for
documentation purpose.

Single line comment - ‘#’ symbol is used for single line comments
Multiple line comments – triple quotes ‘’’ are used to enclose multiple line comments

I/O Functions

Input Function – accepting input from user at run time is done using input() function.
input() function returns value of string type. It needs to be converted to
required type while accepting input.
eval() - function that can be used with input() function. It determines and converts the user
input to int, float, string or complex.

Example - x = eval(input(“Enter a number”))


if user enters 23, x is of type int
if user enters 23.6754, x is of type float

print Function – used to display output on screen. To display strings single, double or triple quotes
can be used.
Syntax
print(argument)
Example -
x = 10
y = 20
print(“x = “,x,”y=”,y)
output –
x = 10y= 20

Escape sequence (\n, etc) can be used for print in the print statements
Example - print(‘Hello’)
To print Joyce’s car - we need to use double quote
print(“Joyce’s car”)

Extensions of print statement -


while using print statement, two or more arguments are seperated by space by default
Example -
print(“a”, “b”,”c”)
output – a b c

sep flag – sep flag is used in print statement to specify the character to be used
instead of space to separate the arguments while displaying.
Example -
print(“a”,”b”,”c”,sep=”*”)
output – a*b*c

end flag – end flag is used in print statement to specify the character to be used
instead of newline to separate ouput of two print statements. By default end flag is set to
newline.
Example -
print(“Python”)
print(“for”)
print(“Data Science”)
output – Python
for
Data Science
Example -
print(“Python”, end=”$”)
print(“for”, end = “$”
print(“Data Science”)
print(“Semester III”)
output - Python$for$Data Science
Semester III

Formatted Print Function

using f’string literal


string preceded with f is called f’string or F’string

Example :

name = “Virat”
USN = 123
print(f’name = {name}, USN = {USN}’)
using format specifier

name = “Virat”
USN = 123
perc = 78.3456
print(‘name = %s, USN = %d, Percentage=%.2f’%(name,USN,perc))

using format function

Using format function, order can be changed


name = “Virat”
USN = 123
print("name={1},USN={0}".format(USN,name))

You might also like