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

Week 3 Computer Science 1116

The document outlines the structure of a Python program, detailing its components such as comments, statements, expressions, functions, and indentation. It explains variables and data types, highlighting the concepts of dynamic typing, mutable and immutable types, and the classification of data types in Python. Additionally, it covers operators and operands, categorizing various types of operators available in Python for data manipulation.

Uploaded by

sdgamerz48
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Week 3 Computer Science 1116

The document outlines the structure of a Python program, detailing its components such as comments, statements, expressions, functions, and indentation. It explains variables and data types, highlighting the concepts of dynamic typing, mutable and immutable types, and the classification of data types in Python. Additionally, it covers operators and operands, categorizing various types of operators available in Python for data manipulation.

Uploaded by

sdgamerz48
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

1.

2 STRUCTURE OF A PYTHON PROGRAM


A Python program constitutes several elements such as statements, expressions, functions,
comments, etc., which are synchronized in the manner as shown below:

programs consist of modules contain statements


contain

expressions
create and process

objects

Let us see the several components of a basic Python program.

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

Numbers None Sequences Sets Mappings

Dictionary

Integer Floating Complex Strings Tuples Lists


Point

Boolean

Computer Science with Python–XII

Fig. 1.2: Classification of Data Types in Python

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.3.1 Dynamic Typing


One of the salient features of Python is dynamic typing. It refers to declaring a variable multiple
times with values of different data types as and when required. It allows you to redefine a
variable with different data types such as numeric, string, etc.
For example, consider the statement:
x = 20
The above statement signifies a variable ‘x’ of integer type as it holds an integer value. Now,
suppose later in the program, you re-assign a value of different type to variable ‘x’ then, Python
shall generate no error and allows the re-assignment with different set of values. For example,
x = 20
print(x)
x = "Computer Science"
print(x)
x = 3.276
print(x)
The above code on execution shall display the output as:
>>>20
>>>Computer Science
>>>3.276
In the above example, we have assigned three different values to the variable ‘x’ with different
types. This process is referred to as Dynamic typing.

CTM: Each and every element in Python is referred to as an object.

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.

1.5 MUTABLE AND IMMUTABLE TYPES


In certain situations, we may require changing or updating the values of certain variables used
in a program. However, for certain data types, Python does not allow us to change the values
once a variable of that type has been created and assigned values.
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. When an attempt is made to update the value of an immutable variable, the old
variable is destroyed and a new variable is created by the same name in memory.
Python data types can be classified into mutable and immutable as under:
 Examples of mutable objects: list, dictionary, set, etc.
 Examples of immutable objects: int, float, complex, bool, string, tuple, etc.
For example, int is an immutable type which, once created, cannot be modified.
Consider a variable ‘x’ of integer type:
>>>x = 5
This statement will create a value 5 referenced by x.
x 5
Now, we create another variable ‘y’ which is copy of the variable ‘x’.
>>>y = x
The above statement will make y refer to value 5 of x. We are creating an object of type int.
Identifiers x and y point to the same object.
x
Review of Python Basics

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.

1.6 OPERATORS AND OPERANDS


Python allows programmers to manipulate data or operands through operators. Operators are
Computer Science with Python–XII

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).

Operator Description Example(s)


+ (unary) To explicitly express a positive number Value of +3 is +3
– (unary) To represent a negative number Value of –3 is –3
+ (binary) To add two numbers Value of 23+3.5 is 26.5
– (binary) To subtract one value from the other Value of 45 – 32 is 13
* To find the product of two numbers Value of 3.2*6 is 19.2
/ To find the quotient when one value is divided by the other. • Value of 3/2 is 1.5
• Value of –3/2 is –1.5
• Value of 10.0/3 is
3.3333333333333335
// (Floor division) To find the integar part of the quotient • Value of 3//2 is 1
when one number is divided by the other. The result is • Value of –3//2 is –2
always the largest integer less than or equal to the actual • Value of 10.0//3 is 3.0
quotient.
% (Remainder) To find the remainder when one value is • Value of 3%2 is 1
divided by the other. • Value of 10%6 is 4
• Value of 6%10 is 6
• Value of 10.3%3.2 is
0.70000000000000002
** (Exponent) To raise a number to the power of another • Value of 3**2 is 9
number. The expression a**b is used to find the value of ab. • Value of 3**–2 is
0.1111111111111111
• Value of 10.2**3.1 is
1338.6299344200029

 Assignment Operators: = (Assignment), += (Add and Assign), –= (Subtract and Assign),


*= (Multiply and Assign), /= (Divide and Assign Quotient), **= (Exponent and Assign),
%= (Divide and Assign Remainder), //= (Floor division and Assign).
Operator Description Example
+= Evaluates R-value and adds it to x=5
(Add and L-value. The final result is assigned to y  =  10
Assign) L-value. x  +=  2*y
print("x=",x,  "and  y=",y)
gives the result: x=   25   and   y=   10
–= Evaluates R-value and subtracts it from x=5
(Subtract and L-value. The final result is assigned to y  =  10
Assign) L-value. x  –=  2*y
print("x=",x,  "and  y=",y
Review of Python Basics

gives the result: x=   –15   and   y=   10


*= Evaluates R-value and multiplies x=5
(Multiply and it with L-value. The final result is y  =  10
Assign) assigned to L-value. x  *=  2*y
print("x=",x,  "and  y=",y)
gives the result: x=   100   and   y=   10

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

 Logical Operators: or, and, not.


Operator Description Example (assuming x=6, y=2)
not Negates a condition and returns True if the not(x > y) returns
condition is false, otherwise returns False. False
and Combines two conditions and returns True if (x >3 and y<2) returns
both the conditions are true, otherwise returns False
False.
or Combines two conditions and returns True if (x>3 or y<2) returns
at least one of the conditions is true, otherwise True
returns False.

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.

Review of Python Basics

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.

1.7.1 Type Casting (Explicit Conversion)


As and when required, we can change the data type of a variable in Python from one type to
another. Such data type conversion can happen in two ways:
• either explicitly (forced) when the programmer specifies for the interpreter to convert a
data type into another type; or
• implicitly, when the interpreter understands such a need by itself and does the type
conversion automatically.
 Explicit Conversion
Explicit conversion, also called type casting, happens when data type conversion takes place
deliberately, i.e., the programmer forces it in the program. The general form of an explicit
data type conversion is:
(new_data_type) (expression)
With explicit type conversion, there is a risk of data loss since we are forcing an expression
to be of a specific type.
For example, converting a floating value of x = 50.75 into an integer type, i.e., int(x) will
discard the fractional part .75 and shall return the value as 50.

>>> 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.

OBJECTIVE TYPE QUESTIONS


1. Fill in the blanks.
(a) ................. is the Python operator responsible for declaring variables.
1.48 (b) The built-in function randrange() belongs to ....................... module.
(c) A .................. operator does not directly operate on data but produces a left-to-right evaluation of
expression.
(d) median() method belongs to ................. module in Python.
(e) The reserved words in Python are called ............... and these cannot be used as names or identifiers.
(f) An ................. is a symbol used to perform an action on some value.
(g) A file that contains a collection of related functions and other definitions is called ................. .
(h) The modules in Python have the ................. extension.
(i) A ................. is just a module that contains some useful definitions.
(j) Each object in Python has three key attributes—a ................., a ............. and an ................. .
(k) In Python, the non-zero value is treated as ................. and zero value is treated as ................. .
(l) Keys of a dictionary must be .......................... .
(m) In ....................., the adjoining values in a sequence are compared and exchanged repeatedly until
the entire array is sorted.
(n) Logical operators are used to combine two or more ........... expressions.
(o) The ............. function returns the length of a specified list.
Answers: (a) Assignment (=) operator (b) random (c) comma (,)
(d) statistics (e) keywords (f) operator
(g) module (h) .py (i) library
(j) type, value, id (k) true, false (l) unique
(m) Bubble sort (n) relational (o) len()
2. State whether the following statements are True or False.
(a) The two statements x = int(22.0/7) and x = int(22/7.0) yield the same results.
(b) The given statement: x + 1 = x is a valid statement.
(c) List slice is a list in itself.
(d) Relational operators return either true or false.
(e) break, continue, pass are the three conditional statements.
(f) The % (modulus) operator cannot be used with the float data type.
(g) The range() function is used to specify the length of a for-in loop.
(h) Assignment operator can be used in place of equality operator in the test condition.
(i) Comments in Python begin with a “$” symbol.
(j) In print() function, if you use a concatenate operator (+) between two strings, both the strings are
joined with a space in between them.
(k) If we execute Python code using prompt “>>>” then we call it an interactive interpreter.
(l) Lists are immutable while strings are mutable.
(m) The keys of a dictionary must be of immutable types.
(n) Lists and strings in Python support two-way indexing.
(o) Tuples can be nested and can contain other compound objects like lists, dictionaries and other tuples.
Answers: (a) True (b) False (c) True (d) True (e) False (f) True
(g) True (h) False (i) False (j) False (k) True (l) False
Review of Python Basics

(m) True (n) True (o) True


3. Multiple Choice Questions (MCQs)
(a) Which of the following is not considered a valid identifier in Python?
(i) two2 (ii) _main (iii) hello_rsp1 (iv) 2 hundred
(b) What will be the output of the following code— print(“100+200”)?
(i) 300 (ii) 100200 (iii) 100+200 (iv) 200

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

(l) Which arithmetic operators cannot be used with strings?


(i) + (ii) * (iii) – (iv) All of the above
(m) What will be the output when the following code is executed?
>>>str1="helloworld"
>>>str1[:–1]
(i) dlrowolleh (ii) hello (iii) world (iv) helloworld
(n) What is the output of the following statement?
print("xyyzxyzxzxyy".count('yy', 1))
(i) 2 (ii) 0 (iii) 1 (iv) Error

1.50

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy