Week 3 Computer Science 1116
Week 3 Computer Science 1116
expressions
create and process
objects
Comments
(Start with #)
Function
Statements Expressions
Blocks
Indentation
Function call
Inline Comments
(Comments beginning in the middle of a line)
As shown in the snippet given above, the several components that a Python program holds are:
Expressions: An expression represents something, like a number, a string, or an element.
Any value is an expression.
Statements: Anything that does something is a statement. Any assignment to a variable or
function call is a statement. Any value contained in that statement is an expression.
Comments: Comments are the additional information provided against a statement or a
chunk of code for the better clarity of the code. Interpreter ignores the comments and
does not count them in commands.
Symbols used for writing comments include Hash (#) or Triple Double Quotation marks (“””).
Hash (#) is used in writing single-line comments that do not span multiple lines. Triple
Review of Python Basics
Quotation Marks (‘’’ or “””) are used to write multiple-line comments. Three triple
quotation marks to start the comment and again three quotation marks to end the comment.
Functions: Function is a set of instructions defined under a particular name, which once
written can be called whenever and wherever required.
Block(s): A block refers to a group of statements which are part of another statement or
function. All statements inside a block are indented at the same level.
1.3
1.3 VARIABLES AND DATA TYPES
A variable is like a container that stores values you can access or change. The purpose of
using variables is to allow the stored values to be used later on. We have learnt that any object
or variable in Python is a name that refers to a value at a particular memory location and
possesses three components:
A Value: It represents any number or a letter or a string. To assign any value to a variable,
we use assignment operator (=).
An Identity: It refers to the address of the variable in memory which does not change once
created. To retrieve the address (identity) of a variable, the command used is:
>>>id(variable_name)
A Type: We are not required to explicitly declare a variable with its type. Whenever we
declare a variable with some value, Python automatically allocates the relevant data type
associated with it.
Hence, the data type of a variable is according to the value it holds.
For example, >>> x = 20
The above statement signifies ‘x’ to be of integer type since it has been assigned an integer
value 20.
Data types are classified as follows (Fig.1.2):
Data Types
Dictionary
Boolean
Computer Science with Python–XII
1. Number or Numeric Data Type: Numeric data type is used to store numeric values. It is
further classified into three subtypes:
(a) Integer and Long: To store whole numbers, i.e., decimal digits without a fraction part.
They can be positive or negative. Examples: 566, –783, –3, 44, etc.
1.4
(b) Float/Floating Point: Floating point numbers signify real numbers. This data type
is used to store numbers with a fraction part. They can be represented in scientific
notation where the uppercase or lowercase letter ‘e’ signifies the 10th power:
(c) Complex Numbers: Complex numbers are pairs of real and imaginary numbers. They
take the form ‘a + bj’, where ‘a’ is the float and ‘b’ is the real part of the complex number.
(d) Boolean: Boolean data type is used in situations where comparisons to be made
always result in either a true or a false value.
2. None: This is a special data type with an unidentified value. It signifies the absence of
Review of Python Basics
value in a situation, represented by None. Python doesn’t display anything when we give
a command to display the value of a variable containing value as None.
3. Sequence: A sequence is an ordered collection of items, indexed by integers (both positive
as well as negative). The three types of sequence data types available in Python are Strings,
Lists and Tuples, which we will discuss in successive topics.
1.5
4. Sets: Set is an unordered collection of values of any type with no duplicate entry. It is
immutable.
5. Mappings: This data type is unordered and mutable. Dictionaries in Python fall under
Mappings. A dictionary represents data in key-value pairs and accessed using keys, which
are immutable. Dictionary is enclosed in curly brackets ({ }).
1.4 KEYWORDS
Computer Science with Python–XII
Keywords are the reserved words used by a Python interpreter to recognize the structure of
a program. As these words have specific meanings for the interpreter, they cannot be used as
variable names or for any other purpose. For checking/displaying the list of keywords available
in Python, we have to write the following two statements:
import keyword
print(keyword.kwlist)
1.6
Fig. 1.3: Keywords in Python
CTM: All these keywords are in small letters, except for False, None, True, which start with capital letters.
5
y
Now, we give another statement as:
>>>x = x + y
The above statement shall result in adding up the value of x and y and assigning to x.
1.7
Thus, x gets rebuilt to 10.
x 10
y 5
The object in which x was tagged is changed. Object x = 5 was never modified. An immutable
object doesn’t allow modification after creation. Another example of immutable object
is a string.
>>>str = "strings immutable"
>>>str[0] = 'p'
>>>print(str)
This statement shall result in TypeError on execution.
TypeError: 'str' object does not support item assignment.
This is because of the fact that strings are immutable. On the contrary, a mutable type object
such as a list can be modified even after creation, whenever and wherever required.
new_list = [10, 20, 30]
print(new_list)
Output:
[10, 20, 30]
Suppose we need to change the first element in the above list as:
new_list = [10, 20, 30]
new_list[0] = 100
print(new_list) will make the necessary updating in the list new_list and shall display the
output as:
[100, 20, 30]
This operation is successful since lists are mutable.
Python handles mutable and immutable objects differently. Immutable objects are quicker to
access than mutable objects. Also, immutable objects are fundamentally expensive to “change”
because doing so involves creating a copy. Changing mutable objects is cheap.
the symbols that operate upon these operands to form an expression. Operators available in
Python are categorized as follows:
Table 1.1: Operators in Python
Arithmetic Operators
Assignment Operators
Relational or Comparison Operators
Logical Operators
Identity Operators
Bitwise Operators
Membership Operators
1.8
Arithmetic/Mathematical Operators: + (addition), – (subtraction), * (multiplication),
/ (Division), ** (Exponent), % (Modulus), // (Floor Division).
1.9
/= Evaluates R-value and divides the x=5
(Divide and L-value with R-value. The quotient is y = 10
Assign Quotient) assigned to L-value. x /= y
print("x=",x, "and y=",y)
gives the result: x= 0.5 and y= 10
%= Evaluates R-value and divides the x=5
(Divide L-value with R-value. The remainder is x%= 4
and Assign assigned to L-value. print("x=",x)
Remainder) gives the result: x=1
//= Evaluates R-value and divides (floor x=5
(Floor division division) the L-value with R-value. The x //= 4
and Assign) quotient is assigned to L-value. print("x=",x)
gives the result: x=1
**= Evaluates R-value and calculates x=5
(Exponent and (L-value)R-value. The final result is x **= 4
Assign) assigned to L-value. print("x=",x)
gives the result: x= 625
Relational/Comparison Operators: > (greater than), < (less than), >= (greater than or
equal to), <= (less than or equal to), == (equal to), != (not equal to).
Operator Description Example (assuming x=6, y=2)
== Compares two values for equality. Returns True (x==y)returns
(Equality) if they are equal, otherwise returns False. False
!= Compares two values for inequality. Returns (x!=y)returns
(Inequality) True if they are unequal, otherwise returns True
False.
< Compares two values. Returns True if first value (x<y)returns
(Less than) is less than the second, otherwise returns False. False
<= Compares two values. Returns True if first value (x<=y)returns
(Less than or is less than or equal to the second, otherwise False
equal to) returns False.
> Compares two values. Returns True if first value (x>y)returns
(Greater than) is greater than the second, otherwise returns True
False.
>= Compares two values. Returns True if first (x>=y)returns
(Greater than or value is greater than or equal to the second, True
equal to) otherwise returns False.
Computer Science with Python–XII
1.10
1.7 INPUT AND OUTPUT (PYTHON’S BUILT-IN FUNCTIONS)
In order to provide the required set of values, data is to be fetched from a user to accomplish the
desired task. Thus, Python provides the following I/O (Input-Output) built-in library functions:
1. input(): The input() function accepts and returns the user’s input as a string and stores it in
the variable which is assigned with the assignment operator. It is important to remember
that while working with input(), the input fetched is always a string; so, in order to work
with numeric values, use of appropriate conversion function (int) becomes mandatory.
The input() function takes one string argument (called prompt). During execution, input()
shows the prompt to the user and waits for the user to input a value from the keyboard. When
the user enters a value, input() returns this value to the script. In almost all the cases, we store
this value in a variable.
Example 3: Display a welcome message to the user.
Example 4: Input two numbers from the user and display their sum and product.
1.11
In the above program, we have used the int() method. int() takes a number, expression or a
string as an argument and returns the corresponding integer value. int() method behaves
as per the following criteria:
(a) If the argument is an integer value, int() returns the same integer. For example,
int(12) returns 12.
(b) If the argument is an integer expression, the expression is evaluated and int()
returns this value. For example, int(12+34) returns 46.
(c) If the argument is a float number, int() returns the integer part (before the decimal
point) of the number. For example, int(12.56) returns 12.
2. eval(): eval() method takes a string as an argument, evaluates this string as a number, and
returns the numeric result (int or float as the case may be). If the given argument is not
a string or if it cannot be evaluated as a number, then eval() results in an error.
>>> x = 50.75
>>> print(int(x))
Computer Science with Python–XII
50
Following are some of the functions in Python that are used for explicitly converting an
expression or a variable into a different type.
Table 1.2: Explicit type conversion functions in Python
Function Description
int(x) Converts x into an integer.
float(x) Converts x into a floating-point number.
str(x) Converts x into a string representation.
chr(x) Converts x into a character.
unichr(x) Converts x into a Unicode character.
1.12
Python supports dynamic typing, i.e., a variable can hold values of different types at different times.
A function is a named block of statements that can be invoked by its name.
The input() function evaluates the data input and takes the result as numeric type.
The if statement is a decision-making statement.
The looping constructs while and for statements allow sections of code to be executed repeatedly.
for statement iterates over a range of values or a sequence.
The statements within the body of a while loop are executed over and over again until the condition of the while
becomes false or remains true.
A string is a sequence of characters.
We can create strings simply by enclosing characters in quotes (single, double or triple).
Positive subscript helps in accessing the string from the beginning.
Negative subscript helps in accessing the string from the end.
‘+’ operator joins or concatenates the strings on both sides of the operator.
The * operator creates a new string concatenating multiple copies of the same string.
List is a sequence data type.
A list is a mutable sequence of values which can be of any type and are indexed by integer.
A list is created by placing all the items (elements) inside a square bracket [ ], separated by commas.
A list can even have another list as an item. This is called nested list.
Another way of creating tuple is built-in function list().
Traversing a list means accessing each element of a list. This can be done by using looping statement, either for
or while.
List slicing allows us to obtain a subset of items.
copy() creates a list from another list. It does not take any parameter.
A tuple is an immutable sequence of values which can be of any type and are indexed by an integer.
Creating a tuple is as simple as putting values separated by a comma. Tuples can be created using parentheses ().
To create a tuple with a single element, the final comma is necessary.
Python provides various operators like ‘+’,‘*’,‘in’, ‘not in’, etc., which can be applied to tuples.
In a dictionary, each key maps a value. The association of a key and a value is called a key-value pair.
To create a dictionary, key-value pairs are separated by a comma and are enclosed in two curly braces {}. In
key-value pair, each key is separated from its value by a colon (:).
We can add new elements to an existing dictionary, extend it with single pair of values or join two dictionaries
into one.
We can also update a dictionary by modifying an existing key-value pair or by merging another dictionary with
an existing one.
Computer Science with Python–XII
Python provides us with a number of dictionary methods like: len(), pop(), items(), keys(), values(), get(), etc.
keys() method in Python dictionary returns an object that displays a list of all the keys in the dictionary.
Bubble sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they
are in the wrong order.
Insertion sort is an in-place sorting algorithm.
In Insertion sort, an element gets compared and inserted into the correct position in the list.
1.49
(c) Which amongst the following is a mutable datatype in Python?
(i) int (ii) string (iii) tuple (iv) list
(d) pow() function belongs to which library?
(i) math (ii) string (iii) random (iv) maths
(e) Which of the following statements converts a tuple into a list?
(i) len(string) (ii) list(string) (iii) tup(list) (iv) dict(string)
(f) The statement: bval = str1 > str2 shall return ............... as the output if two strings str1 and str2
contains “Delhi” and “New Delhi”.
(i) True (ii) Delhi (iii) New Delhi (iv) False
(g) What will be the output generated by the following snippet?
a = [5,10,15,20,25]
k = 1
i = a[1] + 1
j = a[2] + 1
m = a[k+1]
print(i,j,m)
(i) 11 15 16 (ii) 11 16 15 (iii) 11 15 15 (iv) 16 11 15
(h) The process of arranging the array elements in a specified order is termed as:
(i) Indexing (ii) Slicing (iii) Sorting (iv) Traversing
(i) Which of the following Python functions is used to iterate over a sequence of numbers by specifying
a numeric end value within its parameters?
(i) range() (ii) len() (iii) substring() (iv) random()
(j) What is the output of the following?
d = {0: 'a', 1: 'b', 2: 'c'}
for i in d:
print(i)
(i) 0 (ii) a (iii) 0 (iv) 2
1 b a a
2 c 1 2
b b
2 2
c c
(k) What is the output of the following?
x = 123
for i in x:
print(i)
(i) 1 2 3 (ii) 123 (iii) error (iv) infinite loop
Computer Science with Python–XII
1.50