PythonPart I
PythonPart I
CONTENTS
Unit II: Computational Thinking and Programming -1 .................................................................................. 3
PART B: PROGRAMMING IN PYTHON ................................................................................................... 3
1.EXECUTION MODES OF PYTHON ........................................................................................................ 4
Mode 1 - Interactive Mode ........................................................................................................................... 4
Mode 2 - Script Mode ................................................................................................................................... 5
2.PYTHON CHARACTER SET .................................................................................................................... 6
3.TOKENS ........................................................................................................................................................ 6
3.1. Keywords ............................................................................................................................................ 6
3.2. Identifiers (Names) ............................................................................................................................ 7
3.3. Literals ................................................................................................................................................ 8
3.4. Operators .......................................................................................................................................... 10
3.4.1. Unary Operators ............................................................................................................................... 10
3.4.2 Binary Operators ............................................................................................................................... 11
3.4.2.1 Arithmetic Operators ............................................................................................................... 12
Evaluating Arithmetic Expressions (Type Conversions) ......................................... 12
Negative Number Arithmetic [Dealing with % and // in python] ........................... 16
3.4.2.2 Relational Operators ................................................................................................................ 17
3.4.2.3 Logical Operators ..................................................................................................................... 19
1. or Operator ............................................................................................................... 20
2. and Operator ............................................................................................................. 21
3. not Operator ............................................................................................................... 22
3.4.2.4 Assignment Operators ............................................................................................................... 24
3.4.2.5 Augmented Assignment Operators ......................................................................................... 24
3.4.2.6 Identity Operators .................................................................................................................... 24
Equality (==) vs Identity (is) operators ...................................................................... 25
3.4.2.7 Bitwise Operators ..................................................................................................................... 27
3.4.2.8 Membership Operators............................................................................................................ 29
3.4.3 Operator Precedence ................................................................................................................ 29
3.4.4 Operator Associativity ............................................................................................................. 30
3.5. Punctuators ................................................................................................................................ 30
4.VARIABLES ............................................................................................................................................... 31
4.1 Memory allocation in traditional programming languages .............................................................. 31
1
2
2
3
3
4
4
5
5
6
3.TOKENS
• A token is the smallest individual unit in a python program. All statements and instructions in a program
are built with tokens.
• Python has following tokens:
1. Keywords
2. Identifiers (Names)
3. Literals
4. Operators
5. Punctuators
3.1. Keywords
Keywords are words that have some special meaning or significance in a programming language. They can’t
be used as variable names, function names, or any other random purpose. They are used for their special
features. In Python we have 33 keywords.
6
7
7
8
3.3. Literals
Literals are the fixed values or data items used in a source code. Python supports different types of literals such
as:
(i) String Literals: The text written in single, double, or triple quotes represents the string literals in Python.
For example: “Computer Science”, ‘sam’, etc. We can also use triple quotes to write multi-line strings.
(iii) Numeric Literals: These are the literals written in form of numbers.
a) Integer Literal: It includes both positive and negative numbers along with 0. It doesn’t include
fractional parts. It can also include binary, decimal, octal, hexadecimal literal.
8
9
b) Float Literal: It includes both positive and negative real numbers. It also includes fractional parts.
c) Complex Literal: It includes a+bi numeral, here a represents the real part and b represents the complex
part.
d) Boolen Literals: Boolean literals have only two values in Python. These are True and False.
(e) Special Literals: Python has a special literal ‘None’. It is used to denote nothing, no values, or the absence
of value.
(f) Literals Collections: Literals collections in python includes list, tuple, dictionary, and sets.
9
10
List: It is a list of elements represented in square brackets with commas in between. These variables can be of
any data type and can be changed as well.
Tuple: It is also a list of comma-separated elements or values in round brackets. The values can be of any data
type but can’t be changed.
Dictionary: It is the unordered set of key-value pairs.
Set: It is the unordered collection of elements in curly braces ‘{}’.
3.4. Operators
Operators are tokens that triggers some computation or action when applied to variables and other objects in an
expression.
They are classified into two as follows:
a. Unary + b. Unary –
10
11
c. ~ bitwise complement
not operator in Python performs logical negation to Boolean expression. You have to mention an expression or
a variable that has a boolean value associated with it. If the check is True, not will evaluate it as False and vice
versa. The not in Python is considered one of the basic operators used in Python, along
with AND and OR operators. Its function is similar to the inverter gate used in Digital Electronics.
11
12
The act of changing an object’s data type is known as type conversion. The Python interpreter automatically
performs Implicit Type Conversion. Python prevents Implicit Type Conversion from losing data.
The user converts the data types of objects using specified functions in explicit type conversion, sometimes
referred to as type casting. When type casting, data loss could happen if the object is forced to conform to a
particular data type.
Implicit conversion (Coercion) : Compiler does it without programmer’s involvement
If both operands are standard numeric types, the following coercions are applied.
1. If one operand is complex number, the other one is also converted to complex number.
2. If one operand is float number, the other one is also converted to float number.
12
13
Find the output and data type of the two expressions given below:
Expression 1 :
13
14
Expression 2:
14
15
15
16
1.FLOOR DIVISION
Note: a//b <= a/b
Example 1: -7//4
Example 2: 7//-4
Normal division gives answer as -1.75 [ -7/4 and also for 7/-4]
So floor division’s answer should look for an integer lesser than it on a number line.
2.MODULO DIVISION
16
17
17
18
Precision defines how many bits will be occupied in memory to store the number. The more bits are made
available, the more digits after the decimal point can be stored before rounding occurs.
18
19
19
20
1. or Operator
It combines two expressions which make its operands in the following ways:
i)Relational Expressions as operands.
ii)Numbers/Strings/Lists as operands
20
21
2. and Operator
It combines two expressions which make its operands in the following ways:
i)Relational Expressions as operands.
21
22
ii)Numbers/Lists/String as operands.
3. not Operator
22
23
23
24
An augmented assignment is generally used to replace a statement where an operator takes a variable as one of
its arguments and then assigns the result back to the same variable. This can be used only for numbers and not
for mutable datatypes.
A simple example is x += 1 which is expanded to x = x + 1 .
24
25
When 2 variables are referring to the same value, the is operator returns True. Then the == operator also
returns True.
25
26
Opposite (if equal need not be in same memory location) hold true in some cases. Even though they are equal
they need not be in same memory location.
Few cases where python create two different objects even though they store same value:
1. Input of string from console.
26
27
Bitwise and
Biwise or
27
28
Biwise xor
28
29
There are two membership operators in Python i.e., "in" and "not in". The "in" operator is used to test whether
a value is a member of a sequence.
29
30
3.5. Punctuators
30
31
4.VARIABLES
4.1 Memory allocation in traditional programming languages
31
32
32
33
Output:
10
PYTHON
34
35
• input() always returns value of string data type hence below error occurs.Even though the age entered is a
number,input() returns it as a string value.
35
36
36
37
37
38
Video Links to understand how carriage return and backspace (\r,\b) works.
[ Few python versions/systems donot support them]
• What is \r in python?
• What is \b in python?
38
39
7.USE OF COMMENTS
Comments can be used to :
1. explain Python code.
2. make the code more readable.
3. prevent execution when testing code.
Types :
1. Single Line Comment
2. Multiline Comment
3. Inline Comment
39
40
8.1 Numbers
8.1.1) Integers:
Positive or Negative numbers without fractional part.
Types of integers
a) Signed : Used to represent positive and negative numbers.
b) Boolean: Represents truth values True (1) or False(0).
Printing boolean equivalents of 0 and 1 is as follows:
• print(bool(0)) #Output is False
• print(bool(1)) #Output is True
Conversion of the boolean values to string is as follows:
• str(False) # Output is ‘False’
• str(True) # Output is ‘True’
40
41
41
42
8.2 Strings
• A String is a data structure in Python that represents a sequence of characters.
• It is an immutable data type, meaning that once you have created a string, you cannot change the
components in it.
• Strings are used widely in many different applications, such as storing and manipulating text data,
representing names, addresses, and other types of data that can be represented as text.
• Creating a String in Python: Strings in Python can be created using single quotes or double quotes or
even triple quotes.
42
43
The index value of the first element in a string in negative indexing is –(lengthofthestring) : -6
The index value of the second element in a string in negative indexing is –(lengthofthestring-1): -(6-1)
Eg: B’s index value in negative indexing is -6. 6 is the length of the string(no of elements in the string)
43
44
8.3 Lists
• Lists are used to store multiple items in a single variable.
• Lists are created using square brackets.
• thislist = ["apple", "banana", "cherry"]
print(thislist)
• List items are ordered, changeable, and allow duplicate values.
• List items are indexed, the first item has index [0], the second item has index [1] etc.
• When we say that lists are ordered, it means that the items have a defined order, and that order will not
change.
• If you add new items to a list, the new items will be placed at the end of the list.
• The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.
• Since lists are indexed, lists can have items with the same value.
• To determine how many items a list has, use the len() function:
• A list can contain different data types:
• list1 = ["abc", 34, True, 40, "male"]
8.4 Sets
myset = {"apple", "banana", "cherry"}
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data.
A set is a collection which is unordered, unchangeable*, and unindexed.
* Note: Set items are unchangeable, but you can remove items and add new items.
Sets are written with curly brackets.
8.5 Dictionary
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
• Dictionaries are written with curly brackets, and have keys and values.
44
45
45
46
Exception in mutability
We know that a tuple in Python is immutable. But the tuple consists of a sequence of names with unchangeable
bindings to objects.
Consider a tuple
tup = ([3, 4, 5], 'myname') # this tuple has list as first element and string as second.
Strings are immutable so we can’t change their value. But the contents of the list can change. The tuple itself
isn’t mutable but contains items that are mutable.
46
47
9.Errors in Python
Error (bug)
Anything in the code that prevents the program from compiling and running correctly.
Debugging
The process of identifying and removing errors from computer hardware or software:
Types of Errors:
9.2.Logical Errors
The program to behave incorrectly, but they do not usually crash the program. Unlike a program with syntax
errors, a program with logic errors can be run, but it does not operate as intended.
47
48
9.3.Run-Time Errors
Errors that are thrown once the code is run are under the class of runtime errors. These errors will always
include an error message printed to the interpreter.
48