Python Syntax, Keywords, Variables, Data Types, Operators
Python Syntax, Keywords, Variables, Data Types, Operators
Keywords, Variables,
Data Types
Presented by
Mohd Shuaib
Assistant Professor
Python Syntax
• Statement ends with the token NEWLINE character ( i.e. carriage return).
• It means each line is a statement in python Script.
print('SNo: ', 1)
print('First Name: ', 'Aditya')
print('Last Name: ', 'Joshi')
print('Age: ', 19)
• One statement is joined by backslash character \ if it is spanned over multiple
lines
Example:
if 1000 > 10 and \
20 <= 30 and \
True != False and \
False == False :
print('correct conditions')
• Two different statements can not be joined with \ in single line.
print('Hello \
BCA class!') # a multi-line statement
print('Hello') \
print(' BCA class!') # two statement in one logical line give SyntaxError: invalid
syntax
• the semicolon ; is used to separate multiple statements in a single line.
Example:
print('Hello');print('BCA class!');print('how are you’)
Example:
All the lines in a block must use the same indentation, either space or a tab.
def welcomemsg(msg):
print("Hello ", msg)
print("Welcome to Python class BCA Stuents")
You may use either interactive shell or IDLE or any GUI based IDE
Error will be
IndentationError: expected an indented block if you not use indentation or
IndentationError: unexpected indent
Comments
# this is a comment
print("Hello students")
# print("Welcome to Python class")
print("with interesting matplotlib library") #comment after a statement.
Multiline comments
• There is no provision for making multi line comments but you can make multi line string
Python multi-line comment is a piece of text enclosed in a delimiter
(“””) on each end of the comment. Again there should be no white
space between delimiters (“””). Single or double quotes both may be
used
# Write Python code here
print("Hello Class")
• However, if these multiline comments are placed directly after a
function or class signature, then these turn into docstrings.
• Docstring is an in-built feature of Python, which is used to associate
documentation that has been written with Python modules,
functions, classes and methods. It is added right below the
functions, modules, or classes to describe what they do. In Python,
the docstring is then made available via the __doc__ attribute.
print(add(2, 10))
Python Naming Conventions
Identifiers
Script may contain variables, functions, classes, packages etc.
• Identifier is the name given to these programming elements.
• An identifier should start with either an alphabet letter (lower or
upper case) or an underscore (_).
• After that, more than one alphabet letter (a-z or A-Z), digits (0-9), or
underscores may be used to form an identifier.
• No other characters are allowed.
• Identifiers in Python are case sensitive, which means variables named age
and Age are different.
• Class names should use the TitleCase convention. It should begin with an
uppercase alphabet letter e.g. MyClass, Student, Employee.
• Function names should be in lowercase. Multiple words should be separated
by underscores, e.g. add(num), calculate_tax(amount).
• Variable names in the function should be in lowercase e.g., x, num, salary.
• Module and package names should be in lowercase e.g., mymodule,
tax_calculation. Use underscores to improve readability.
• Constant variable names should be in uppercase e.g., RATE, TAX_RATE.
• Use of one or two underscore characters when naming the instance attributes
of a class.
• Two leading and trailing underscores are used in Python itself for a special
purpose, e.g. __add__, __init__, etc.
Display Output
• The print() serves as an output statement in Python. It echoes the value of any
Python expression on the Python shell.
• Multiple values can be displayed by the single print() function separated by comma.
The following example displays values of name and age variables using the single
print() function.
name="Aditya"
print(name) # display single variable
age=19
print(name, age)# display multiple variables
print("Name:", name, ", Age:",age) # display formatted output
By default, a single space ' ' acts as a separator between values. However, any other
character can be used by providing a sep parameter.
Getting User's Input
• The input() function is a part of the core library of standard Python
distribution. It reads the key strokes as a string object which can be referred to
by a variable having a suitable name.
• The blinking cursor waits for the user's input. The user enters his input and
then hits Enter. This will be captured as a string.
• The input() function has an optional string parameter that acts as a prompt for
the user.
• The input() function always reads the input as a string, even if comprises of
digits. The type() function used earlier confirms this behaviour.
name=input("Enter your name: ")
print(type(name))
age=input("Enter your age: ")
print(type(age))
Keywords
• These are predefined words having special purpose and cannot be used for other things
• Except for the first three (False, None and True), the other keywords are entirely in lowercase.
Get it by
help("keywords") 35 keywords
Here is a list of the Python keywords. Enter any keyword to get more help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
Variables in Python
• Variable is the name given to a value.
• We can refer this value later on with the name of the variable
• Variable points to an object.
• A literal value is assigned to a variable using = operator
• Left side should be the name of a variable and right side should be the
value.
>>> n=20
>>> n
20
• print() is also used to display the value of variable
• Variables in Python are objects. Use the type() function to get the class name
of an object.
>>> type(n)
<class 'int’>
The type of n is int. An object of int class contains a integer literal 20
• Depending upon the value they are all class
>>> msg='Hello World'
>>> type(msg)
<class 'string'>
>>> isPythonInterpreted = True
>>> type(isPythonInterpreted)
<class 'bool’>
>>> a=10
>>> b=10
>>> a+b
20
>>> a='Hello '
>>> b='Class'
>>> a+b
'Hello Class'
Identity of Object
• Each object in Python has an id.
• It is the object's address in memory represented by an integer value. The
id() function returns the id of the specified object where it is stored.
>>> a=100
>>> id(a)
140723188454144
>>> msg="hello class"
>>> id(msg)
3125284964016
• An id will be changed if a variable changed to different value.
>>> msg="hello class"
>>> id(msg)
3125284964016
>>> msg="BCA Class is good"
>>> id(msg)
3125283818352
• Multiple variables assigned to the same literal value will have the same id
>>> a=100
>>> id(a)
140723188454144
>>> z=100
>>> id(z)
140723188454144
>>> b=a
>>> id(b)
140723188454144
• Python optimize memory usage by not creating separate objects if they point to same
value.
List: A list object is an ordered collection of one or more data items, not
necessarily of the same type, put in square brackets.
Tuple: A Tuple object is an ordered collection of one or more data items, not
necessarily of the same type, put in parentheses.
Mapping Data Type
Dictionary: A dictionary Dict() object is an unordered collection of data in a
key:value pair form. A collection of such pairs is enclosed in curly brackets. For
example: {1:“Aditya", 2:“Joshi", 3:"Ram", 4: “Shree"}
Data objects of the above types are stored in a computer's memory for
processing. Some of these values can be modified during processing, but
contents of others can't be altered once they are created in the memory.
Numbers, strings, and Tuples are immutable, which means their contents can't
be altered after creation.
• Leading zeros in non-zero integers are not allowed e.g. 02345 is invalid number, 0000 is 0.
>>> 0000
0
>>> 02345
File "<stdin>", line 1
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal
integers
• Python does not allow comma as number delimiter. Use underscore _ as a
delimiter instead.
>>> a=1_2_3_56
>>> a
12356
Float
In Python, floating point numbers (float) are positive and negative real numbers
with a fractional part denoted by the decimal symbol . or the scientific notation
E or e, e.g. 1234.56, 3.142, -1.55, 0.23.
>>> x=1.5
>>> type(x)
<class 'float'>
>>> f=2e400
>>> f
Inf
Floats has the maximum size depends on your system. The float beyond its maximum size referred
as "inf", "Inf", "INFINITY", or "infinity". Float 2e400 will be considered as infinity for most systems.
Scientific notation is used as a short representation to express floats having many digits. For
example: 345.56789 is represented as 3.4556789e2 or 3.4556789E2
>>> f=1e3
>>> f
1000.0
>>> f=1e5
>>> f
100000.0
>>> f=3.4556789e2
>>> f
345.56789
• Use the float() function to convert string, int to float.
>>> float('5.5')
5.5
>>> float('5')
5.0
>>> float(' -5')
-5.0
>>> float('1e3')
1000.0
>>> float('-Infinity')
-inf
>>> float('inf')
inf
Complex Number
A complex number is a number with real and imaginary components. For
example, 5 + 8j is a complex number where 5 is the real component and 8
multiplied by j is an imaginary component.
>>> a=5+9j
>>> a
(5+9j)
>>> type(a)
<class 'complex’>
You must use j or J as imaginary component. Using other character will throw
syntax error.
Arithmetic Operators
str1='''This is
the first
Multi-line string.
'''
print(str1)
• If a string literal required to embed double quotes as part of a string then, it
should be put in single quotes. Likewise, if a string includes a single quote as a
part of a string then, it should be written in double quotes.
not in Returns true if a character does not exist in the given string >>> a = 'Python'
>>> 'x' not in a
True
>>> 'y' not in a
False
Python - List
• list is a mutable sequence data type. A list object contains one or more items
of different data types in the square brackets [] separated by a comma.
Declaration of lists variable:
>>> list1=[] # empty list
>>> print(list1)
[]
>>> stunames=["Aditya", "Joshi", "Yogesh", "kanishk", "Deepa"] #string list
>>> print(stunames)
['Aditya', 'Joshi', 'Yogesh', 'kanishk', 'Deepa']
>>> glevel=[1, "Aditya", 24, 94.5, True] #list with different data types
>>> print(glevel)
[1, 'Aditya', 24, 94.5, True]
Accessing List
• accessed using a zero-based index in the square brackets []. start from zero and
increment by one for each item
names=["Aditya", "Joshi", "Mohit", "Rohit"]
print(names[0])
print(names[1])
print(names[2])
print(names[3])
runfile('C:/Users/Aditya/Desktop/untitled13.py', wdir='C:/Users/Aditya/Desktop')
Aditya
Joshi
Mohit
Rohit
A list can contain multiple inner lists as items that can be accessed using
indexes.
data=[1, 2, 3, [4, 5, 6, [7, 8, [9]]], 10]
print(data[0]) # returns 1
print(data[1]) # returns 2
print(data[3]) # returns [4, 5, 6, [7, 8, [9]]]
print(data[4]) # returns 10
print(data[3][0]) # returns 4
print(data[3][3]) # returns [7, 8, [9]]
print(data[3][3][0]) # returns 7
print(data[3][3][2]) # returns [9]
List class
All the list objects are the objects of the list class in Python. Use the list()
constructor to convert from other sequence types to list
num=[1,2,3,4] runfile('C:/Users/Aditya/
print(type(num)) Desktop/untitled13.py',
mylist=list('BCA4') wdir='C:/Users/Aditya/Desktop'
print(mylist) )
num=list({1:'one',2:'two'}) <class 'list'>
print(num) ['B', 'C', 'A', '4']
num=list((40, 50, 60)) [1, 2]
print(num) [40, 50, 60]
num=list({400, 500, 600}) [400, 600, 500]
print(num)
Iterate through List
num=[1,2,3,4]
for var in num:
print(var)
Output:
1
2
3
4
Update list
The list is mutable. You can add new items in the list using the append() or
insert() methods, and update items using indexes.
Course=["BCA", "MCA", "BSC IT"]
print(Course)
Course[0]="MSC IT"
Course[1]="BCA"
Course.append("BSC CS")
print(Course)
runfile('C:/Users/Aditya/Desktop/untitled13.py', wdir='C:/Users/Aditya/Desktop')
['BCA', 'MCA', 'BSC IT']
['MSC IT', 'BCA', 'BSC IT', 'BSC CS']
Remove Items
• Use the remove(), pop() methods, or del keyword to delete the list item or the whole list.
print(Course)
del Course[0]# removes item at index 0 ['MSC IT', 'BCA', 'BSC IT', 'BSC CS']
print("After del Course[0]: ", Course) After del Course[0]: ['BCA', 'BSC IT', 'BSC CS']
After Course.remove("BCA"): ['BSC IT', 'BSC CS']
BSC IT
Course.remove("BCA") # removes "BCA" After Course.pop(0): ['BSC CS']
After Course.pop(): []
print('After Course.remove("BCA"): ', Course)
NameError: name 'Course' is not defined
del Course
print(Course)
Tuples
• Tuple is an immutable collection of elements of different data types. It is
an ordered collection, so it preserves the order of elements in which
they were defined.
• Tuples are defined by enclosing elements in parentheses (), separated
by a comma. tpl=() # empty tuple runfile('C:/Users/Aditya/Desktop/
Declaration: print(tpl) untitled13.py',
names = ('Aditya', 'Neha', 'Shree', wdir='C:/Users/Aditya/Desktop’)
'GEU') # string tuple
print(names) ()
nums = (1, 2, 3, 4, 5) # int tuple ('Aditya', 'Neha', 'Shree', 'GEU')
print(nums) (1, 2, 3, 4, 5)
emp=(1, 'Aditya', True, 30, 240000) (1, 'Aditya', True, 30, 240000)
# heterogeneous data tuple
print(emp)
it is not necessary to enclose the tuple elements in parentheses.
Tuple Class
The underlying type of a tuple is the tuple class. Check the type of a variable
using the type() function.
The tuple() constructor is used to convert any iterable to tuple type.
num={1,2,3,3,3,3,4,4,4,4,4,5,6,7,7,7,8}
print(num)
The order of elements in the set is not necessarily the same as the
order given at the time of assignment. Python optimizes the
structure of a set for performing operations over it, as defined in
mathematics.
Only immutable (and hashable) objects can be a part of a set object.
Numbers (integer, float, as well as complex), strings, and tuple
objects are accepted, but set, list, and dictionary objects are not.
>>> myset = {(10,10), 10, 20} # valid
>>> myset
{(10, 10), 10, 20}
>>> s=set()
>>> type(s)
<class 'set'>
>>> s
set()
set() function also use to convert string, tuple, or dictionary object to a set object
>>> s=set('Hello')
>>> s
{'o', 'l', 'e', 'H’}
>>> s = set((1,2,3,4,5))
>>> s
{1, 2, 3, 4, 5}
Declaration:
roll = {"1":"Aditya", "2":"Mukul", "3":"Sneha"}
Above, roll is a dictionary object which contains key-value pairs inside { }. The
left side of : is a key, and the right side is a value. The key should be unique and
an immutable object. A number, string or tuple can be used as key.
d = {} # empty dictionary
decNames={1.5:"One and Half", 2.5: "Two and Half", 3.5:"Three and Half"} # float key, string value
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5} # string key, int value
print(d)
print(numNames)
print(decNames)
print(items)
print(romanNums)
a dictionary with a list as a key is not valid, as the list is mutable
Leads to error
But list can be used as value
emptydict = dict()
Print(emptydict)
Accessing Dictionary:
Dictionary is an unordered collection, so a value cannot be
accessed using an index; instead, a key must be specified in
the square brackets
capitals = {"USA":"Washington DC", "France":"Paris", "India":"New Delhi"}
print(capitals["USA"])
print(capitals["France"])
print(capitals["usa"]) # Error: Key is case-sensitive
print(capitals["Japan"]) # Error: key must exist
runfile('C:/Users/Aditya/Desktop/untitled13.py',
wdir='C:/Users/Aditya/Desktop')
{'1': 'Aditya', '2': 'Mukul', '3': 'Sneha'}
{'2': 'Mukul', '3': 'Sneha'}
dict.pop(): The dict.pop() method removes the key and returns its value. If a key
does not exist in the dictionary, then returns the default value if specified, else
throws a KeyError.
runfile('C:/Users/Aditya/Desktop/untitled13.py', wdir='C:/Users/Aditya/Desktop')
{'1': 'Aditya', '2': 'Mukul', '3': 'Sneha'}
deleted value is : Sneha
{'1': 'Aditya', '2': 'Mukul'}
roll = {"1":"Aditya", "2":"Mukul", "3":"Sneha"}
print(roll)
delvalue=roll.pop("5","Key not found")
print("deleted value is : ",delvalue)
print(roll)
runfile('C:/Users/Aditya/Desktop/untitled13.py', wdir='C:/Users/Aditya/Desktop')
{'1': 'Aditya', '2': 'Mukul', '3': 'Sneha'}
deleted value is : Key not found
{'1': 'Aditya', '2': 'Mukul', '3': 'Sneha'}
dict.popitem(): The dict.popitem() method removes and returns a tuple of (key, value) pair from
the dictionary. Pairs are returned in Last In First Out (LIFO) order.
roll = {"1":"Aditya", "2":"Mukul", "3":"Sneha"}
print(roll)
print(roll.popitem())
print(roll.popitem())
print(roll.popitem())
print(roll)
#print(roll.popitem()) #KeyError: 'popitem(): dictionary is empty'
runfile('C:/Users/Aditya/Desktop/untitled13.py', wdir='C:/Users/Aditya/Desktop')
{'1': 'Aditya', '2': 'Mukul', '3': 'Sneha'}
('3', 'Sneha')
('2', 'Mukul')
('1', 'Aditya')
{}
Retrieve Dictionary Keys and Values
The keys() and values() methods return a view objects
containing keys and values respectively.
d1 = {'name': 'Aditya', 'age': 21, 'marks': 80, 'course': 'BCA'}
print(d1.keys())
print(d1.values())
runfile('C:/Users/Aditya/Desktop/untitled13.py',
wdir='C:/Users/Aditya/Desktop')
dict_keys(['name', 'age', 'marks', 'course'])
dict_values(['Aditya', 21, 80, 'BCA'])
Check dictionary keys
You may check it with in and not in keywords
if ('name' in d1):
print("Key found")
else:
print("Key not found")
Multi-dimensional Dictionary
d1={"name":"Aditya","age":25, "rollno":1}
d2={"name":"Vaibhav","age":23, "rollno":50}
d3={"name":"Shanku", "age":20, "rollno":30}
stu={1:d1,2:d2,3:d3}
print(stu)
The stu object is a two-dimensional dictionary. Here d1, d2, and d3 are assigned as
values to keys 1, 2, and 3, respectively. The stu[1] returns d1.
print(stu[1])
{'name': 'Aditya', 'age': 25, 'rollno': 1}
print(stu[1]["name"])
Aditya