IP Notes Python Introduction
IP Notes Python Introduction
Fundamentals of Python
Character Set: A character set is a collection of valid characters which is
recognized by the programming language. Python has the following character
set.
Letters : A-Z, a-z
Digits: 0-9
Special Symbols: >, <, <>, _, (), [], (), /, % etc.
Whitespaces: Blank space, Enter, Tab etc.
Tokens: The smallest individual unit of program is known as Token. Various
types of tokens are given below:
1. Keywords
2. Identifiers
3. Literals
a. Numeric Literals
b. String Literals
c. Boolean Literals
4. Punctuators
5. Operators
Keywords: Keywords are reserved words. Each keyword has a specific meaning
to the Python interpreter, and we can use a keyword in our program only for the
purpose for which it has been defined.
Identifiers: Identifiers are names used to identify a variable, function, or other
entities in a program. The naming conventions of identifiers in Python are as
follows
1. An identifier cannot start with a digit.
2. Keywords cannot be used as identifiers.
3. We cannot use special symbols like !, @, #, $, %, etc., in identifiers.
(underscore can be used)
4. Identifiers cannot have spaces.
Examples of valid identifiers
a. num1
b. percentage
c. mark1
d. Stu_marks
Examples of invalid identifiers
a.1_ num (reason: Starting from digit)
b. marks@123 (reason: Using special character)
c. pass (reason: Keyword)
d. student age (reason: space)
Literals: Literals are the fixed value or constant value which we used in Python.
There are several kinds of literals in Python.
1. Numeric Literal: Numeric literals are the numbers that can be with or without
decimal. Numeric literals are of following types
a. Integer literal: These literals are the numbers/values which are without
decimal. It includes both positive and negative numbers along with 0. In other
words we can say that these literals are the whole numbers. for example 12, -3,
0
b. Floating Point Literals: These literals are the numbers/values with
decimal, for example 2.3, 3.9, -5.6, 6.0
2. String Literals: String literals are the values which are enclosed in quotes
(either single, double or tripple), for example: 'a', "anuj", '34", "S"
NOTE: Triple quotes are used to write multi line string.
3. Boolean Literals: Boolean literals have only two values ie True or False
Punctuators: These are the symbols used in Python to frame structure,
statement or expression.
Commonly used punctuators in Python are: [], {), (), +,-, //= ,== etc.
Operators: Operators are special symbols which are used to perform some
mathematical or logical operations on values.
Examples:
a = 12 #12 is integer literal and 'a' is identifier
b = 7.0 #7.0 is float literal and 'b' is identifier
c = "Numbers" #"Number" is string literal and 'c' is identifier
s = a+b #=and+are operators
print("Sum of two", c, "is", s) #print is keyword and double quotes("),
comma(,) are punctuators.
Variables: Variable in Python refers to an object an item or element that is
stored in the memory. Value of a variable can be a string (e.g., 'b', 'Global
Citizen'), numeric (e.g., 345) or any combination of alphanumeric characters.
for example
marks = 56
name = "Ananya"
Remark: Variable declaration is implicit in Python, means variables are
automatically declared and defined when they are assigned a value the first
time. Variables must always be assigned values before they are used in
expressions as otherwise it will lead to an error in the program.
Variables in Python are created when we assign values. for example,
>>> x #lt return error as we didn't assign any value
Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> X
NameError: name 'x' is not defined
>>> x=8
>>> x #It is not showing any error
8
In python we can assign same value to different variables in one
statement, for example
p=q=r= 28
The above statement will assign value 28 to all the three variables.
>>>p
28
>>>q
28
>>>r
28
We can also assign different values to different variables in a single
statement. For Example,
x, y, z = 1, 2, 3
>>>x
1
>>>y
2
>>>z
3
Remark: The values will be assigned in order
Swapping of values
>>>a=9
>>>b=25
>>>a, b
(9, 25)
>>>a, b=b, a
>>>a, b
(25, 9)
Comments:
Comments are used to add a remark or a note in the source code.
Comments are not executed by the interpreter. They are added with the purpose
of making the source code easier for humans to understand. In Python, a
comment starts with # (hash sign). Multiline comment can be given in python by
enclosing it in triple quote ("') for example
#following program is to add two numbers
a=8
b=3
print("Sum = ", a+b)
'''Multi line comment in python can be given by enclosing it in triple quotes'''
id():
This function returns the identity (memory address) of an object which
remains the same for the lifetime of that object. for example:
num1 = 20
num2 = 20
print(id(num1))
print(id(num2))
OUTPUT:
8791510210176 #Your output can be different 8791510210176 #Both are
showing same address as both variables are storing same number ie 20
Dynamic Typing:
A variable referring to a value of any datatype say integer. In next line
same variable can be used to refer a value of another data type say String. This
process of shifting from one data type to another without giving any error is
called Dynamic Typing. for example
>>>a = 24
>>>a
24
>>>type(a)
<class 'int'>
>>>a = "Ilovemycountry" a
Ilovemycountry
>>>type(a)
<class 'str'>
NOTE: In Python, the values stored in variables decide its data type.
Data Types :
Data type identifies the type of data values a variable can hold and the
operations that can be performed on that data. Various data types in Python are
as follows:
1. Numbers
• Integer
• Boolean
• Floating Point
• Complex
2. Sequences
• Strings
• Lists
• Tuples
3. Mappings
• Dictionary
Number:-
This data type stores numerical values only. It is further classified into
three different types: int, float and complex.
DATA DESCRIPTION EXAMPLES
TYPE
int This data type stores integers. 4, -5, 23, -90
float This data type stores floating point -23.45, 40.26
numbers.
complex This data type stores complex numbers. 1+2j, 21+5j
Boolean data type (bool) is a sub type of integer. This data type stores two
values, True and False. Boolean True value is non-zero. Boolean False is the value
zero.
marks1 = 34
marks2 = 23.12
m1 = True
print(type(marks1))
print(type(marks2))
print(type(m1))
OUTPUT:
<class 'int'>
<class 'float'>
<class 'bool'>
NOTE: type() function determines the data type of the variable.
Variables of simple data types like integers, float, boolean, etc., hold single
values. But such variables are not useful to hold a long list of information, for
example, marks of all students in a class test, names of the months in a year,
names of students in a class. For this, Python provides data types like tuples,
lists, dictionaries and sets.
Sequence :
It is an ordered collection of items, where each item is indexed by an
integer. The three types of sequence data types available in Python are Strings,
Lists and Tuples.
1. String: String is a group of characters (like alphabets, digits or special
characters including spaces). Strings are enclosed in Single quotes (' ') or in
double (" "). for example:
st1 = "Anuj"
st2 = '2342'
NOTE: Numerical functions cannot be performed on String.
2. List: List is a sequence of items enclosed in square brackets [] and items are
separated by commas. for example:
L1 = [23, 'a', 4, 2.3, 'b'] #It is a list containing items of different data types.
L2 = ['a', 'b', 'c', 'd'] #It is a list containing items of same data types.
3. Tuple: Tuple is a sequence of items separated by commas and items are
enclosed in parenthesis ().
T1 = (1, 3, 56, 's', 5)
Difference between List and Tuple:
List Tuple
a. It is mutable a. It is immutable
b. Items are enclosed in [] b. Items are enclosed in ()
Mapping:
Mapping is an unordered data type in Python. Mapping data type in
Python is Dictionary.
Dictionary: Dictionary in Python holds data items in key-value pairs. Items in a
dictionary are enclosed in curly brackets {}. Every key is separated from its value
using a colon (:) sign.
The key: value pairs of a dictionary can be accessed using the key.
for example:
D1 = {"a": "Apple", "b": "Ball", "c": "Cat"} #"a","b", "c" are keys and "Apple",
"Ball", "Cat" are respective values
Mutable and Immutable Data Types
Variables whose values can be changed after they are created and
assigned are called mutable. Variables whose values cannot be changed after
they are created and assigned are called immutable. Python data types can be
classified into mutable and immutable as shown below:
Immutable data types are: Mutable data types are:
1. Integer 1. List
2. Float 2. Sets
3. Boolean 3. Dictionary
4. String
5. Tuple
Operators
Operators are special symbols which are used to perform some
mathematical or logical operations on values. The values on which the operators
work are called operands.
for example, in 34 + 31, here '+' is a mathematical addition operator and the
values 34 and 31 are operands.
3. Assignment Operators:
Operator Explanation Examples
= Assigns value of right-side operand to left-side >>> x=7
operand. >>> x
7
+= X+=y is same as x = x+y >>> x = 20
>>> y = 10
>>> x+=y
30
-= X+=y is same as x = x-y >>> x = 20
>>> y = 10
>>> x-=y
10
*= X*=y is same as x = x*y >>> x = 20
>>> y = 10
>>> x*=y
200
/= X/=y is same as x = x/y >>> x = 20
>>> y = 10
>>> x/=y
2.0
//= X//=y is same as x = x//y >>> x = 20
>>> y = 10
>>> x//=y
2
**= X**=y is same as x = x**y >>> x=2
>>> y=3
>>> x**=y
8
*= X%=y is same as x = x%y >>> x = 22
>>> y = 10
>>> x%=y
2
4. Logical Operators:
There are three logical operators in Python. The logical operator evaluates
to either True or False
Operator Explanation Examples
and It returns True if all the conditions are >>> x = 7
True >>> y = 9
>>> x > 5 and y >
7
True
>>> x < 10 and y >
10
False
or It returns True if any one of the >>> x = 7
conditions are True >>> y = 4
>>> x > 5 and y >
7
True
>>> x > 10 and y >
7
False
not It negates the truth. It makes True to >>> x = 7
False and False to True >>> y = 4
>>> not(x>5 or
y>7)
False
5. Identity Operators:
Identity operators is used to determine whether two variables are
referring to the same object or not. There are two identity operators.
Operator Explanation Examples
is Evaluates True if the variables on either >>> n1 = 5
side of the operator point towards the >>> n2 = n1
>>> id(n1)
same memory location and False
1423451526
otherwise. >>> id(n2)
1423451526
>>> n1 is n2
True
Is not Evaluates False if the variables on either >>> n1 = 5
side of the operator point towards the >>> n2 = n1
>>> id(n1)
same memory location and False 1423451526
otherwise. >>> id(n2)
1423451526
>>> n1 is not n2
False
6. Membership operators:
Membership operators are used to check if a value is a member of the
given sequence (List, String, Tuple etc.) or not. There are two membership
operators in Python.
Operators Explanation Examples
In Returns True if the >>>'a' in 'amit'
variable/value is found in True
the specified sequence and >>>1 in [11, 22, 33, 44]
False
otherwise False
not in Returns False if the >>>'a' not in 'amit'
variable/value is found in False
the specified sequence and >>>1 not in [11,
22, 33, 441
True otherwise
True
Expressions:
An expression is defined as a combination of constants, variables, and
operators, An expression always evaluates to a value.
1. 3+4 (34-23)
2. 34 %3+3
Evaluation of expressions:
Evaluation of the expression is based on precedence of operators. (It
determines which operator will be evaluated first). Higher precedence operator
is evaluated before the lower precedence operator.
The following table lists precedence of all operators from highest to lowest.
Order of Precedence Operators Description
1 ** Exponentiation
2 *, /, %, // Multiply, Divide, Modulo,
and Floor division
3 +, - Addition and Subtraction
4 <=, <, >, >=, ==, != Relational and Comparison
operators
5 =, %=, /=, //=, -=, +=, Assignment operators
*=, **=
6 is, is not Identity operators
7 in, not in Membership operators
8 not Logical operator
9 and Logical operator
10 or Logical operator
Implicit Conversion :
Implicit conversion, also known as coercion, happens when data type
conversion is done automatically by Python and is not instructed by the
programmer.
n1 = 7 #n1 is an integer
n2 = 2.0 #n2 is a float
res = n1 - n2 #res is difference of a float and an integer
print(res)
print(type(res))
OUTPUT:
5.0
<class 'float'>
NOTE: In above example variable 'res' was automatically converted to a float
value.
Debugging:
We can make some mistakes while writing a program, due to which, the
program may not execute or may give wrong output. The process of identifying
and removing such mistakes (called bugs), from a program is called debugging.
Errors in the programs can be classified into three categories.
1. Syntax Error:
When we are not writing the programs according to the rules that
determine its syntax then Syntax error occurs. If any syntax error is present, the
interpreter shows error message(s) and stops the execution there only. for
example (1 + 2) is syntactically correct, whereas (9-2 is not due to absence of
right parenthesis.
2. Logical Error:
An error that causes the program to behave incorrectly. Logical error
produces an undesired output but without abrupt termination of the program.
Logical errors are also called semantic errors as they occur when the meaning of
the program (its semantics) is not correct. for example, code to find the average
of two numbers
>>> 12 + 6/2 #This code will not give the correct output so statement is
logically incorrect
>>>15 # This is not the average of 12 and 6
3. Runtime Error:
A runtime error causes abnormal termination of program. Runtime error is
when the statement is syntactically correct, but the interpreter cannot execute
it. for example Division by Zero is most common runtime error.