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

Ch-4 Notes and Questions

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

Ch-4 Notes and Questions

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

CHAPTER- 4th

PYTHON PROGRAMMING FUNDAMENTALS

INTRODUCTION:

Python is an interpreted, object-oriented, high-level programming


language with dynamic semantics. Its high-level built in data
structures, combined with dynamic typing and dynamic binding,
make it very attractive for Rapid Application Development, as well as
for use as a scripting or glue language to connect existing
components together. Python's simple, easy to learn syntax
emphasizes readability and therefore reduces the cost of program
maintenance. Python programming language, developed by Guido
Van Rossum in early 1990s.

TOKENS IN PYTHON:

Tokens or lexical units are the smallest fractions in the python


programme. A token is a set of one or more characters having a
meaning together. There are 5 types of tokens in python which are
listed below:

1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Punctuators

1. Keywords

A keyword is a reserved word in a computer language that has a


specific meaning. Python keywords form the vocabulary of the python
language. Keywords aren’t allowed to be used as identifiers. They are
used to define the Python language’s “Syntax” or “Structure.”

2. Identifiers

In Python, an identifier is a name given to a Class, Function, or


Variable. It aids in distinguishing one entity from others.

Characteristics of Python Identifier:

a) The initial letter of the identifier should be any letter or underscore


(_).
b) Upper and lower case letters have distinct characteristics.

c) Except for the initial letter, any digit from 0 to 9 can be part of the

identification.
d) It shouldn’t be used as a keyword

e) Except for the underscore (_), an identifier cannot contain any

special characters.
f) Identifiers can be as long as you want them to be.

g) Case matters when it comes to identifier names. Myself and

myself, for example, are not the same thing.


3. Literals

Literals, tokens in Python, are data elements with a fixed value. Literals
return a value for an object of the specified type. Python supports a
variety of literals:

 String Literals
 Numeric Literals. These are further of three types, integer, float, and
complex literals.
 Boolean Literals
 Literal Collection

Lists, tuples, dictionaries, and sets are all examples of literal


collections in Python.

 List: A list is a collection of elements enclosed in square brackets


and separated by commas. These variables can be of any data
type, and their values can be altered.
 Tuple: A comma-separated list of elements or values in round
brackets is also known as a tuple. Values can be of any data type,
but they cannot be modified.
 Dictionary: It’s an unsorted collection of key-value pairs.
 Set: The “set” is an unordered collection of objects enclosed in curly
braces.

4. Operators

Operators are tokens that, when applied to variables and other


objects in an expression, cause a computation or action to occur.
Operands are the variables and objects to which the computation is
applied. There are 7 different operators.
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

Let us have a quick look on all these operators one by one:

Arithmetic Operators
Python arithmetic operators are used to perform mathematical
operations on numerical values. These operations are Addition,
Subtraction, Multiplication, Division, Modulus, Exponents and Floor
Division.

Operator Name Example

+ Addition 10 + 20 = 30

- Subtraction 20 – 10 = 10

* Multiplication 10 * 20 = 200

/ Division 20 / 10 = 2

% Modulus 22 % 10 = 2

** Exponent 4**2 = 16

// Floor Division 9//2 = 4


Comparison Operators
Python comparison operators compare the values on either sides of
them and decide the relation among them. They are also called
relational operators. These operators are equal, not equal, greater
than, less than, greater than or equal to and less than or equal to.

Operator Name Example

== Equal 4 == 5 is not true.

!= Not Equal 4 != 5 is true.

> Greater Than 4 > 5 is not true.

< Less Than 4 < 5 is true.

>= Greater than or Equal to 4 >= 5 is not true.

<= Less than or Equal to 4 <= 5 is true.

Assignment Operators
Python assignment operators are used to assign values to variables.
These operators include simple assignment operator, addition
assign, subtraction assign, multiplication assign, division and assign
operators etc.

Operator Name Example

= Assignment Operator a = 10

+= Addition Assignment a += 5 (Same as a = a + 5)


-= Subtraction Assignment a -= 5 (Same as a = a - 5)

*= Multiplication Assignment a *= 5 (Same as a = a * 5)

/= Division Assignment a /= 5 (Same as a = a / 5)

%= Remainder Assignment a %= 5 (Same as a = a % 5)

**= Exponent Assignment a **= 2 (Same as a = a ** 2)

//= Floor Division Assignment a //= 3 (Same as a = a // 3)

Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation.
Assume if a = 60; and b = 13; Now in the binary format their values will
be 0011 1100 and 0000 1101 respectively. Following table lists out the
bitwise operators supported by Python language with an example
each in those, we use the above two variables (a and b) as operands

a = 0011 1100

b = 0000 1101

--------------------------

a&b = 12 (0000 1100)

a|b = 61 (0011 1101)

a^b = 49 (0011 0001)

~a = -61 (1100 0011)

a << 2 = 240 (1111 0000)

a>>2 = 15 (0000 1111)


There are following Bitwise operators supported by Python language

Operator Name Example

& Binary AND Sets each bit to 1 if both bits are 1

| Binary OR Sets each bit to 1 if one of two bits


is 1

^ Binary XOR Sets each bit to 1 if only one of two


bits is 1

~ Binary Ones Inverts all the bits


Complement

<< Binary Left Shift Shift left by pushing zeros in from


the right and let the leftmost bits
fall off

>> Binary Right Shift Shift right by pushing copies of the


leftmost bit in from the left, and let
the rightmost bits fall off

Logical Operators
There are following logical operators supported by Python language.

Operator Description Example

and Logical If both the operands are true then (a and b)


AND condition becomes true. is true.
or Logical OR If any of the two operands are non-zero (a or b) is
then condition becomes true. true.

not Logical Used to reverse the logical state of its Not(a and
NOT operand. b) is false.

Membership Operators
Python’s membership operators test for membership in a sequence,
such as strings, lists, or tuples. There are two membership operators
as explained below-

Operator Description Example

In Evaluates to true if it finds a variable x in y, here in results


in the specified sequence and false in a 1 if x is a member
otherwise. of sequence y.

not in Evaluates to true if it does not finds x not in y, here not in


a variable in the specified results in a 1 if x is not
sequence and false otherwise. a member of
sequence y.

Identity Operators
Identity operators compare the memory locations of two objects.
There are two Identity operators explained below −

Operator Description Example


Is Evaluates to true if the variables on
x is y,
either side of the operator point to
here is results in 1 if
the same object and false
id(x) equals id(y).
otherwise.

is not Evaluates to false if the variables x is not y, here is


on either side of the operator point not results in 1 if
to the same object and true id(x) is not equal
otherwise. to id(y).

Operators Precedence
The following table lists all operators from highest precedence to
lowest.

Sr.No. Operator & Description

1 **

Exponentiation (raise to the power)

2 ~+-

Complement, unary plus and minus (method names for the


last two are +@ and -@)

3 * / % //

Multiply, divide, modulo and floor division

4 +-

Addition and subtraction


5 >> <<

Right and left bitwise shift

6 &

Bitwise 'AND'

7 ^|

Bitwise exclusive `OR' and regular `OR'

8 <= < > >=

Comparison operators

9 <> == !=

Equality operators

10 = %= /= //= -= += *= **=

Assignment operators

11 Is, is not

Identity operators

12 In, not in

Membership operators

13 Not, Or, And

Logical operators
5. Punctuators

Punctuators are tokens in python employed to put the grammar and


structure of syntax into practice. Punctuators are symbols that are
used to structure programming sentences in a computer language.
Some commonly used punctuators are: ‘, ‘ ,#, \ ,( ) ,{ },[ ] ,@ ,: , =

Structure of Python Program:


DATA TYPE IN PYTHON

Python provides various standard data types that define the storage
method on each of them. The data types defined in Python are given
below:

 Numbers
 Sequence Type
 Boolean
 Set
 Dictionary

Numeric Data Type

Number stores numeric values. The integer, float, and complex values
belong to a Python Numbers data-type. Python provides
the type() function to know the data-type of the variable.

Python supports three types of numeric data.

1. Int - Integer value can be any length such as integers 10, 2, 29, -
20, -150 etc. Python has no restriction on the length of an integer. Its
value belongs to int.
2. Float - Float is used to store floating-point numbers like 1.9,
9.902, 15.2, etc. It is accurate upto 15 decimal points.

3. complex - A complex number contains an ordered pair, i.e., x +


iy where x and y denote the real and imaginary parts, respectively.
The complex numbers like 2.14j, 2.0 + 2.3j, etc.

Sequence Data Type

1. String

The string can be defined as the sequence of characters represented


in the quotation marks. In Python, we can use single, double, or triple
quotes to define a string.

String handling in Python is a straightforward task since Python


provides built-in functions and operators to perform operations in the
string.

In the case of string handling, the operator + is used to concatenate


two strings as the operation "hello"+" python" returns "hello python".

The operator * is known as a repetition operator as the operation


"Python" *2 returns 'Python Python'.

Example - 1

str = "string using double quotes"


print(str)
s = '''''A multiline
string'''
print(s)
Output:

string using double quotes


A multiline
string

Example - 2

str1 = 'hello javatpoint' #string str1


str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2

Output:

he
o
hello javatpointhello javatpoint
hello javatpoint how are you

2. List

The List can contain data of different types. The items stored in the list
are separated with a comma (,) and enclosed within square brackets
[].
We can use slice [:] operators to access the data of the list. The
concatenation operator (+) and repetition operator (*) works with the
list in the same way as they were working with the strings.

Example -

list1 = [1, "hi", "Python", 2]


#Checking type of given list
print(type(list1))

#Printing the list1


print (list1)

# List slicing
print (list1[3:])

# List slicing
print (list1[0:2])

# List Concatenation using + operator


print (list1 + list1)

# List repetation using * operator


print (list1 * 3)

Output:

[List]
[1, 'hi', 'Python', 2]
[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
4. Tuple

A tuple is similar to the list in many ways. Like lists, tuples also contain
the collection of the items of different data types. The items of the
tuple are separated with a comma (,) and enclosed in parentheses
().

A tuple is a read-only data structure as we can't modify the size and


value of the items of a tuple.

Example –

tup = ("hi", "Python", 2)


# Checking type of tup
print (type(tup))

#Printing the tuple


print (tup)

# Tuple slicing
print (tup[1:])
print (tup[0:1])

# Tuple concatenation using + operator


print (tup + tup)

# Tuple repatation using * operator


print (tup * 3)

# Adding value to tup. It will throw an error.


t[2] = "hi"
Output:

<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
TypeError: 'tuple' object does not support item assignment

Dictionary

Dictionary is an unordered set of a key-value pair of items. It is like an


associative array or a hash table where each key stores a specific
value. Key can hold any primitive data type, whereas value is an
arbitrary Python object.

The items in the dictionary are separated with the comma (,) and
enclosed in the curly braces {}.

Example –

d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}

# Printing dictionary
print (d)

# Accesing value using keys


print("1st name is "+d[1])
print("2nd name is "+ d[4])

print (d.keys())
print (d.values())
Output:

{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}


1st name is Jimmy
2nd name is mike
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])

Boolean

Boolean type provides two built-in values, True and False. These
values are used to determine the given statement true or false. It
denotes by the class bool. True can be represented by any non-zero
value or 'T' whereas false can be represented by the 0 or 'F'.

Example -

# Python program to check the boolean type


print(type(True))
print(type(False))
print(false)

Output:

<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set

Python Set is the unordered collection of the data type. It is iterable,


mutable(can modify after creation), and has unique elements. In set,
the order of the elements is undefined; it may return the changed
sequence of the element. The set is created by using a built-in
function set(), or a sequence of elements is passed in the curly
braces and separated by the comma. It can contain various types of
values.

Example -

# Creating Empty set


set1 = set()

set2 = {'James', 2, 3,'Python'}

#Printing Set value


print(set2)

# Adding element to the set

set2.add(10)
print(set2)

#Removing element from the set


set2.remove(2)
print(set2)

Output:

{3, 'Python', 'James', 2}


{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}
Key Differences Between Mutable and Immutable in Python

Mutable Immutable

The objects can be modified after Objects can not be modified after
the creation as well. the creation of the objects.

Classes that are mutable are not Classes that are immutable are
considered final. considered final.

Thread unsafe. Thread-safe.

Classes are not made final for the Classes are made final for the
mutable objects. immutable objects.

Example: Lists, Dicts, Sets, User- Example: int, float, bool, string,
Defined Classes, Dictionaries, etc. Unicode, tuple, Numbers, etc.

Type Conversion/ Data type casting

Python defines type conversion functions to directly convert one data


type to another which is useful in day-to-day and competitive
programming. There are two types of Type Conversion in Python:

1. Implicit Type Conversion


2. Explicit Type Conversion

Implicit Type Conversion


In Implicit type conversion of data types in Python, the Python interpreter
automatically converts one data type to another without any user
involvement.
Example-
x = 10
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
z=x+y
print(z)
print("z is of type:",type(z))

Output:
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
z is of type: <class 'float'>

Explicit Type Conversion


In Explicit Type Conversion in Python, the data type is manually changed
by the user as per their requirement. With explicit type conversion, there is
a risk of data loss since we are forcing an expression to be changed in
some specific data type. Various forms of explicit type conversion are
explained below:

1. int(a, base): This function converts any data type to integer. ‘Base’
specifies the base in which string is if the data type is a string.
2. float(): This function is used to convert any data type to a floating-
point number.

Example-
s = "10010"
c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)
e = float(s)
print ("After converting to float : ", end="")
print (e)
Output:
After converting to integer base 2 : 18
After converting to float : 10010.0

USER INPUT IN PYTHON

To receive information through the keyboard, Python uses the input()


function. This function has an optional parameter, commonly known as
prompt, which is a string that will be printed on the screen whenever the
function is called. When the input()function is called, the program flow
stops until the user enters the input via the command line.

Example-
txt = input("Type something to test this out: ")
print( "This is output of input line: " txt)

FUNCTION IN PYTHON

Functions in Python is a block of statements that return the specific task.


The idea is to put some commonly or repeatedly done tasks together and
make a function so that instead of writing the same code again and again
for different inputs, we can do the function calls to reuse code contained
in it over and over again.

Some Benefits of Using Functions

 Reducing duplication of code


 Decomposing complex problems into simpler pieces
 Improving clarity of the code
 Reuse of code
 Information hiding
Python Function Declaration
The syntax to declare a function is:

Python Function Types

Python comes preloaded with many that you can use as per your needs.
You can even create new functions. Broadly, Python functions can belong
to one of the following three categories:

1. Built-in functions: These are pre-defined functions and are always


available for use. You have used some of them – (len), type(), int(), input()
etc.
2. Functions defined in modules: These functions are pre-defined in
particular modules and can only be used when the corresponding module
is imported.
For example, if you want to use pre-defined functions inside a module, say
sin(), you need to first import the module math (that contains definition of
sin()) in your program.
3. User defined functions: These are defined by the programmer. As
programmers you can create your own functions.

In this chapter, you will learn to write your own Python functions and use
them in your programs.
DEFINING FUNCTION IN PYTHON

A function once defined can be invoked as many times as needed by using


its name, without having to rewrite its code.
The syntax to declare a function is:

def function_name(arguments):
# function body
return
Here,

 def - keyword used to declare a function


 function_name - any name given to the function
 arguments - any value passed to function
 return (optional) - returns value from a function

Let's see an example,


def test():
print('Hello World!')

Or
def sum(x,y):
s = x+y
return s

Here,
we have created a function named test(). It simply prints the text
Hello World!.
Structure of a Python Program using Functions

Example:
def hello():
name = str(input("Enter your name: "))
if name:
print ("Hello " + str(name))
else:
print("Hello World")
return

hello()

Here,
 This code defines a function called hello().
 When the function is called, it prompts the user to enter their name
using the input() function and stores the input as a string in the
variable name.
 The code then checks if name is not an empty string using the if
statement.
 If name is not empty, the function prints "Hello" followed by the value
of name.
 If name is empty, the function prints "Hello World".
 Finally, the function returns None as there is no explicit return value
specified.
 When the code is run, the hello() function is called, prompting the
user to enter their name and printing the appropriate greeting based
on the input.
Indentation in Python

In Python, indentation is the leading whitespace (spaces or/and tabs)


before any statement. The importance of indentation in Python stems from
the fact that it serves a purpose other than code readability.

Rules of Indentation in Python

 Python’s default indentation spaces are four spaces. The number of


spaces, however, is entirely up to the user. However, a minimum of one
space is required to indent a statement.
 Indentation is not permitted on the first line of Python code.
 Python requires indentation to define statement blocks.
 A block of code must have a consistent number of spaces.
 To indent in Python, whitespaces are preferred over tabs. Also, use either
whitespace or tabs to indent; mixing tabs and whitespaces in
indentation can result in incorrect indentation errors.

Example-
site = 'prepbytes'
if site == 'prepbytes':
print('Logging on to prepbytes...')
else:
print('retype the URL.')
print('All set !')

Output
Logging on to prepbytes...
All set !
Rules and Tips in Python

There are certain rules that the programmer must follow when
programming. If you break any rule, you will get a so-called compilation
error, in other words, the compiler does not understand how to translate
the code, and then the computer does not know what to do. The program
will then crash.

As with syntax, rules are something you learn gradually, but it is still
important to start thinking about how to structure and write your programs.
Some basic rules in Python are:

 The first letter of a variable, function, or class must be one of the


letters (a-z) or (A-Z). Numbers or special characters such as & and%
are not allowed
 Special characters cannot be used in names
 There are reserved words, such as and, if, else, break, import, and
more, which are not allowed in naming. All reserved words can be
found here
 Python is sensitive to indentations, that marks a block segment in
your code

Add comments to the code in Python

A hashtag # creates a comment in the code. These are ignored by the


compiler. You can thus comment on your code so that it is easy to
understand what is happening.

Example:
print("Hello World!") # This is the comment
--> ignored by the compiler

Output:
Hello World!
DEBUGGING

Errors occurring in programming are called as bugs.The process of


tracking this bugs is called as debugging. There are three types of errors
that can occur while coding:
1. Syntax Error,
2. Runtime Error and
3. Semantic Error.

Syntax Error

The syntax is a defined structure or set of rules while writing a program. If


someone fails to maintain correct syntax ,then it may lead to Syntax Error.
>>> a=1+2
>>> a
3
>>> 1+2=a
SyntaxError: can't assign to operator
>>>

Runtime Error

This type of error does not appear until program is executed. In this,
program is executed successfully without syntax or logical error and this
type of error occurs at runtime i.e. while accepting values from user.
Runtime errors are also called as exceptions or interruptions in program.
a=2
b=3
c=4
d=input("enter a number")
sum=a+b+c+d
print(sum)
Output
enter a number5
Traceback (most recent call last):
File "C:/Python34/runtime error.py", line 5, in
sum=a+b+c+d
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Semantic Error/Logical Error

In this program will be executed without any error on prompt but will not
give desired output. Such type of error is called Semantic error. Semantic
errors are also called as logical errors. It is difficult to track such errors as it
requires to go backward to look for output and find errors causing incorrect
output.
num1=int(input("Enter first number"))
num2=int(input("Enter second number"))
add = num1 - num2
print("sum of two nums is ", add )

Output
Enter first number200
Enter second number57
sum of two nums is 143
MEMORY BYTES
> APython program can contain various components like expressions, statements, comments, functions, blocks and
indentation.
An expression is a legal combination of symbols that represents a value.
>Astatement is a programming instruction.
> Comments are non-executable, additional information added in a program for readability.
} In Python, comments begin with the hash (#) symbol/character.
> Avariable in Python is defined only when some value is assigned to it.
» Python supports dynamic typing, i.e., a variable can hold values of different types at different times.
function is a named block of statements that can be invoked by its name.
A
> The input() function evaluates the data input and takes the result as numeric type.
º Output is generated through print statement.
> An expression is a valid combination of operators and operands. Operands are the objects on which operators ara
applied.
> Arithmetic, relational and logical operators are used for performing computations in aprogram.
> Astring is a sequence of characters. To specify a string, we may use single, double or triple quotes.
> The operator +(addition) appliedon two string operands is used for concatenating them. Similarly, the operator
* (multiplication) is used to repeat a string a specific number of times.
When relational operators are applied in strings, strings are compared left to right, character by character.
according to their ASCIl values.
While evaluating aBoolean expression involving 'and' operator, the second sub-expression is evaluated only if the
first sub-expression yields True.
> While evaluating an expression involving 'or operator, the second sub-expression is evaluated only if the first
sub-expression yields False.
Avariable is a name that refers to a value. We may also say that a variable associates a name with a data object
such as number, character, string or Boolean.
º Values are assigned to variables using assignment statement. The syntax for assignment statements is as follows:
variable = expression
where variable is called I-value and expression is called r-value.
> In an assignment statement, the expression on the right-hand side of the equal to (=) operator is evaluated and
the value so obtained is assignedto the variable on the left-hand side of the equal to (=) operator.
º A variable name must begin with a letter or_(underscore character). It may contain any number of letters, digits
or underscore characters. No other character apart from these is allowed.
> Python is case-sensitive. Thus, marks and Marks are different variables.
> The shorthand notion for a = a <operator> b is
a<operator>=b
> In Python, multiple assignment statements can be specified in a single line as follows:
<name1>, <name2>, ... = <expression1>, <expression2>, ...
A keyword is a reserved word that is already defined by Python for a specific use. Keywords cannot be used for
any other purpose.
Trving to use a variable that has not been assigned a value gives an error.
º Run-time errors occur during the execution of a program.
> Irregular unexpected situations occurring during run-time are called exceptions.

OBJECTIVE TYPE QUESTIONS


1. Fill in the blanks.
(a) The smallest individual unit in a program is known as a
(b) Aword having special meaning reserved by a programming language is known as
(c) A literal is a sequence of characters surrounded by quotes.
(d) are tokens that trigger same computation/action when applied to variables.
(e) A is a reserved named location that stores values.
(f) Todetermine the type of an object we use function.
(g) The input() always returns a value of type.
(h) Blocks of codes are represented through
(i) In typing, a variable can hold values of different types at different times.
(i) In Python, the floating point numbers have precision of digits.
(k) Operators that act upon two operands are referred to as operators.
(0) truncates fractional remainders and gives only the whole part as the result.
(m) A............. ....

error does not stop execution but the program behaves incorrectly and produces
undesired/wrong output.
(n) Trying to access a variable or file that doesn't exist is a kind of error.

2. State whether the following statements are True or False.


(a) Python supports Unicode coding standard.
(b) An identifier must be a keyword of Python.
(c) Default variable initialization is string literal.
(d) 3+C=A is a valid statement.
(e) The input() always returns a value of an integer type.
(f) The print() without any value or name or expression prints a blank line.
(g) In Python, Boolean type is a sub-type of integer.
(h) "AISSCE-2020" is a valid string in Python.
(1) In Python, Integer data type has a fractional part.
i) Null literal in Python means "there's nothing here".
(k) Python supports multiple assignment to multiple variables.
(I) id() function is used to determine the data type of a variable.
3. Multiple Choice Questions (MCQs):
(a) Which of the following are the fundamental building blocks of a Python program?
(i) ldentifiers (ii) Constants (ii) Punctuators (iv) Tokens
(b) ldentifier name cannot be composed of special characters other than
(i) # (i) Hyphen (-) (ii) $ (iv) Underscore (
(c) Python takes indented spaces after the function declaration statement by default.
(i) 5 (ii) 6 (ii) 4 (iv) 3
(d) Single line comments in Python begin with symbol.
(i) # (ii) (i) (iv) %
(e) Which of the following does not represent a complex number?
() K= 2 +3j (ii) K= complex(2,3) (ii) K= 2 + 3i (iv) K= 4 +3j
(f) What is the order of precedence of arithmetic operators given below in Python?
1. Parenthesis 2. Exponential 3. Multiplication
4. Division 5. Addition 6. Subtraction
(i) 1, 2, 3, 4, 5, 6 (i) 2, 3, 4, 5, 6, 1 (ii) 1, 3, 2, 6, 4, 5 (iv) 4, 6, 5, 2, 3, 1
(g) What will be the output of the following snippet?
X, y = 2, 6
X, y= y, X + 2
print (x, y)
(i) 66 (ii) 4 4 (ii) 46 (iv) 64
(h) Which of the following is not in Python character set?
()) Letters: A -Z or a -z (ii) Digits: 0-9
(iii) Whitespaces: blank space, tab, etc. (iv) Images: Vector
() Each statement in Python is terminated by
(i) Semicolon (:) (ii) Colon (:) (ii) Comma (,) (iv) None of these
) The extension of aPython file is given as:
(i) .pt (ii) -pwy (iii) -py or .pyW (iv) -yppy
(k) The reserved words used by Python interpreter to recognize the structure of a program are termed as

(i) ldentifiers (iü) Tokens (ii) Literals (iv) Keywords


() What can be the maximum possible length of an identifier?
() 31 (ii) 63
(ii) 79 (iv) Can be of any length
(m) Which of the following operators is floor division?
(i) + (ii) / (ii) // (iv) >
(n) Which of the following is an invalid statement?
() a==c=2 (i) a,b, c=10,20, 30
(iii) a b c = 20,30, 40 (iv) a b c=20
(o) What is the result of this statement?
>>> 10>5 and 7>12 or not 18>3
(i) 10 (ii) True
(iii) False (iv) None
(p) What will be the output of the following Python code?
>>>6 * 3 + 4 ** 2 // 5 -8
(i) 13 (iü) 14
(ii) Error (iv) None
(g) What will be the output of the following Python code?
>>> a=72.55
>>> b=10
>>> c=int (atb )
>>>
(i) 72.55 (ii) 72
(ii) 82 (iv) None of these

SOLVED QUESTIONS
1. What are tokens in Python? How many types of tokens are allowed in Python? Exemplify your answer.
Ans. Token is the smallest individual unit in a program.
Types of tokens:
keywords: False, True, for, while
identifiers: a, A, Ist, dict1
literal: "python", 5, 9, class11'
operator: +, - /, *, **, %, 1/
punctuators: &, ^, ?, #, @, !
2. What are the different components of a variable?
Ans. Avariable has three main components:
(a) ldentity (memory address) of the variable.
(b) Type (data type) of the variable.
(c) Value of the variable.

3. Consider the following statements in Python interpreter and describe the output/statement required:
(a) Print a message "Hello World".
(b) a = 10
b= 12
C= a + b
print (c)
(c) To retrieve the data type of the inputted string "Hello" stored inside the variable a'.
(d) To describe the data type of variable 'b'.
(e) To retrieve the address of variables a and b.
(f) State the output:
>>> b= 12
>>> d = b
>>> d

>>> id (d)
>>>id (b)
(g) >>> a = " Hel lo"
>>> a * 10

(h) To display the value for a', a³ and a


(i) >> a = 15
>>> b = 4
>>> a/b
>>> a/ /b
(i) To swap the values of two variables, a and b, using multiple assignment statements.
(k) >>> a,b, C, d=10,27,4+5,10-7
>>> a//d
>>> d**d
>>> b/c
>>> a+b+c-d

Ans. (a) >>> print ("HelloWorld")


Hello World.
(b) >>> a = 10
>>> b = 12
>>>c =a + b
>>> print (c)
22
(c) >>> a = "Hello"
>>> type (a)
<class'str'>

(d) >>> type (b)


<class 'int'>
(e) >>> id (a)
52193248
>>> id (b)
1616896960
(f) >>> d =b
>>> d
12
>>> b
12
>>> id (d)
1616896960
>>> id (b)
1616896960
(g) >>> a= "Hello"
>>> a*10
'HelloHelloHelloHelloHelloHelloHelloHelloHelloHello
(h) >>> a= 10
>>> a**2
100
>>> a**3
1000
>>> a* *4
10000
() >>> a = 15
>>> b = 4
>>> a/b
3.75
>>> a/ /b
3

() >>>a, b= 10, 12
>>> a, b=b, a
>>> a
12
>>> b
10

(k) >>> a,b, c, d=10,27, 4+5, 10-7


>>>a//d
3
>>>d**d
27
>>>b/c
3.0
>>>a+b+c-d
43

4. Which of the following identifier names are invalid and why? (NCERT)
(i) Serial no. (ii) 1st Room
(iii) Hundred$ (iv) Total Marks
(v) Total Marks (vi) total-Marks
(vii) Percentage (viii) True
Ans. Following identifier names are invalid:
S.No. Invalid Identifier Reason
Serial no. ldentifier cannot contain special symbol
()
(ii) 1st ROom Identifier name cannot begin with number
(ii) Hundred$ Identifier cannot contain special symbol
(iv) Total Marks ldentifier cannot contain space
(vi) total-Marks ldentifier cannot contain special symbol
(viil) True ldentifier cannot be a keyword
5. What is the difference between a keyword and a variable?
Ans. Keyword is a special word that has a specific purpose and meaning to the Python interpreter. Keyworas
defined.
reserved words that can be used in our program only for the purpose for which they have been
For example, for, if, elif, else, def, True, False, etc. fixed/
Variable is the user-defined name given to a value that is stored in the memory. Variables are not They
reserved. These are defined bythe user but they can have letters, digits and the symbol underscore.
must begin with either a letter or underscore. For example, _age, name, result_1, etc.
6. What is a function? How is it useful?
Ans. Afunction in Python is a named block of statements within a program that performs a specific task
Forexample, the following program has a function within it, namely greet_msg().
# progl.py
def greet msg():
print ("Hello there!!")
name =
input ("Your name: ")
print (name, greet msg())
Functions are useful as they can be reused anywhere through their function call statements. So, for the
same functionality, one need not rewrite the code every time it is needed; rather, through functions it can
be used again and again.
7. Find the error.
def minus (total, decrement)
output = total decrement
return output
Ans. The function header has colon missing at the end and the following two statements are not indented. So, we
need to add colon (:) at the end of the header line and indent the two lines following the function header.
Thus, the corrected code will be:
def minus (total, decrement):
Output = total decrement
return output
8. Differentiate between mutable and immutable objects.
Ans. Mutable object: Objects whose values can be changed after they are created arnd assigned values are called
mutable objects. For example, list, dictionary, etc.
Immutable object: Objects whose values cannot be changed after they are created and assigned values are
called immutable objects. For example, int, float, string, tuple, etc.
9. Ritu is confused between 3*2 and 3**2. Help her to know the difference between the two expressions.
Ans. The statement 3*2 multiplies 3 by 2 and produces the result 6 while 3**2 calculates 3 raised to the
power 2 and produces the result 9.
10. How many types of strings are supported in Python?
Ans. Python allows two string types:
(1) Single line StringS-Strings that are terminated in a single line enclosed within single and double quotes.
(2) Multiline Strings-Strings storing multiple lines of text enclosed within three single or double quotes.
11. Differentiate between explicit and implicit type conversion.
Ans. An implicit type conversion is a conversion performed by the compiler without programmer's intervention.
An implicit conversion is applied generally whenever multiple data types are intermixed in an expression
(mixed mode expression), so as not to lose information.
An explicit tvpe conversion is user-defined conversion that forces an expression to a specific type. The
explicit type conversion is also known as Type Casting.
12. What are variable-naming conventions?
Ans. (i) Avariable must start with a letter or underscore followed by any number of digitsand/or letters.
(iü) No reserved word or standard should be used as the variable name.
(iii) No special character (other than underscore) should be included in the variable name.
(iv) Case sensitivityshould be taken care of.
13. What is None in Python?
Ans. Python has one special data type called None. The None type is used to indicate something that has not yet
been created. It is a non-null, unidentified value.
14. ldentify the types of the following literals:
"False", None, [100.200 20o
23.789, 23789, True, {4: "four",5: "five"}, True', "True", (1,2,3), False,
Ans. 23.789 Floating point
23789 integer
True Boolean

{4: "four", 5: "five"} Mapping (Dictionary)


'True' String
"True" String
(1,2,3) Sequence (Tuple)
False Boolean
"False" String
None None
(100,200,300] Sequence (List)
15. Write the corresponding Python statements:
(i) Assign value 100 to variable A and value 200 to variable B.
(ii) Assign value 10 to variables a, b and c.
(ii) Assign value 20 to xand delete5 from x and assign the variable x to variabley.
Ans. () A=100
B=200
(ii) a=b=c=10
(i) x=20
X=X-5

y=x

16. Find the output generated by the following code:


(1) x=2 (2) X=8
y=3 y=2
X+=y X+=y
print (x,y) y-=x
Ans. 5 3 print (x, y)
Ans. 10 -8

(3) a=5 (4) p=10


b=10 q=20
at=at+b p*=q//3
b*=a+b qt=ptq**2
print (a, b) print (p,q)
Ans. 20 300 Ans. 60 480

(5) p5/2 (6) p=2/5


q=p*4 q-p*4
r=ptq r=ptq
pt=ptq+r pt=ptq-r
rt=ptgtr r*=p-q+r
q-=ptq*r qt=ptq
print (p,q, r) print (p, q,)
Ans. 27.5 -642.5 62.5 Ans. 0. 4 3.6 8.0
17. What is the difference between an expression and a statement in Python?
Ans.
S. No. Expression Statement
1. An expression is a combination of symbols, Statement is defined as any programming
operators and operands. instruction given in Python as per the syntax.
2. An expression represents some value. Statement is given to execute a task.
3. The outcome of an expression is always a value. Statement may or may not return a value as
the result.
4. For exampie, 3*7+10 is an expression. For example, print("Hello") is a statement.
18., ldentify the error in the following Python statement:
>>> print ("My name is", first name)
Write the corrected statement also.
Ans. The atbove statement is trying toprint the value of an undefined variable first_name. The correction is made
by defining the variable name before using it, i.e.,
>>> first name = 'Rinku'
>>> print ("My name is", first name)
19. The following code is not giving the desired output. We want to input the value as 15 and obtain
output as 30. Could you pinpoint the problem?
num = input ("Enter Number: ")
result = num * 2
Print(result)
Ans. The problem is with input() function as it returns value as a string, so when we input the value 15 it will
assign to num variable as string '15' and not as integer 15. So, when num variable is multiplied by 2,the
output is ´1515' and not 30. To solve this problem, int() function is to be used while accepting the input.
Also, Print is not alegalstatement of Python;it should be print. The corrected code is:
num = int (input ("Enter Number:"))
result = num * 2
print (result)
20. Write aprogram to obtain temperature in Celsius and convert it into Fahrenheit using the formula:
F= C*9/5+32
Ans. #Celsius to Fahrenheit
cels = float(input ("Enter temp in Celsius :")
print ("Temperature in Celsius is :", cels)
f = cels * 9/5 + 32
print ("Temperature in Fahrenheit is :", f)
21. What will be the output produced by the following code?
name = 'Neeru!
age = 21
print (name, "you are", 21, "now but", )
print ("you will be", age + 1, "next year")
Ans. Output should be:
Neeru, you are 21 now but
you will be 22 next year
22. What will be the output of the following code? Explain.
X, y= 2, 6
X, y y, X + 2
print (x, y)
Ans. 6 4
Explanation: The first line of code assigns values 2 and 6 to variables x and y
The next line (second line) of code first evaluates the right-hand side, i.e., y, x +respectively.
2, which is 6, 2 + 2, i.e., 6,4;
And then assigns this to x, y, i.e., x, y =6, 4; so x gets 6 and y gets 4.
The third line prints x and y so the output is 6 4.
23. Write a Python code to calculate and display the selling price of an item. Cost price and profit is to k
accepted by user.
Ans. costPrice = int (input ('Enter cost price:'))
profit = int (input('Enter profit:'))
sellingPrice = costPrice + profit
print('Selling Price: ', sellingPrice)
Output:
Enter cost price: 50
Enter profit: 12
Selling Price: 62
24. What output will be produced by the following code?
A, B, C, D= 9.2, 2.0, 4, 21
print (A/4)
print (A//4)
print (B**C)
print (A*B)
Ans. 2.3
2.0
16.0
18.4

25. Write the Python code to accept time in minutes and convert it into hours and minutes.
Ans. min=int (input ("Enter time in minutes") )
h=min//60
m=min%60
print ("Hours=",h)
print ("Minutes=", m)
26. Evaluate (to true or false) each of the following expressions:
(i) 14 <= 14
(ii) 14 < 14
(ii) -14 > -15
(iv) -15 >=15
Ans. (i) True
(ii) False
(iii) True
(iv) False
27. Write logical expressions corresponding to the following statements in Python and evaluate the expressions
(assuming values of variables as num1, num2, num3, first, middle, last: (NCERT)
(a) The sum of 20 and -10 is less than 12.
(b) num3 is not more than 24.
(c) 6.75 is between the values of integers num1 and num2.
(d) The string 'middle' is larger than the string 'first' and smaller than the string last'.
(e) List Stationery is empty.
Ans. Expressions:
(a) 20+ (-10) < 12
(b) not (num3 > 24)
(c) (6.75 > numl) and (6.75 < num2 )
(d) (middle > first) and (middle < last)
(e) Stationery == | )OR len(Stationery) == 0
28. Ayear is a leap year if it is divisible by 4,except that years divisible by 100 are not leap years unless theyare
also divisible by 400. Write a program that asks the user for a year and print whether it is a leap year or not.
Ans. year = int (input ("Please Enter the Year Number you wish: ") )
if year%400 == 0or year%4 == 0 and year%100 != 0 :
print (year, "is a Leap Year")
else:

print (year, "is Not a Leap Year")


29. Write a Python program that accepts cost price and quantity of pencil from the user. Calculate and
display total price.
Ans. costprice = int (input ('Enter cost price of pencil: '))
gty =int (input ('Enter quantity: ' )
totalprice-costprice* gty
print ("Total price is:", totalprice)
30. Assume that a ladder is put upright against a wall. Let variables length and angle store the length of the
ladder and the angle that it forms with the ground as it leans against the wall. Write a Python program to
compute the height reached by the ladder on the wall for the following values of length and angle:
(a) 16 feet and 75 degrees (b) 20feet and 0 degree
(c) 24 feet and 45 degrees (d) 24 feet and 80 degrees (NCERT)
Ans. import math
length =int (input ("Enter the length of ladder: ") )
angind =int (input ("Enter the angle in degree: "))
anginr = math. radians(angind)
sin = math.sin (anginr)
height = round (length * sin, 2)
print ("The height reached by ladder ", height)
31. Write a program that asks the user to enter their name and age. Print a message addressed to the user
that tells the user the year in which they will turn 100 years old. (NCERT)
Ans. nm = input ("Enter Your Name")
age = int (input ("Enter Your age") )
yr =2023 + (100- age) #Taking 2023 as Current Year
print (nm, ":You will turn 100 in", yr)
32. Differentiate between Syntax and Run-time errors. Give an appropriate example.
Ans. Syntax Error: Violation of formal rules of a programming language such as misspelling a keyword or incorrect
indentation, etc., results in syntax error.
For example,
len ('hel lo') = 5
File "<stdin>", 1ine 1
SyntaxError: can't assign to function call
Run-time Error: These errors are generated during a program execution due to resource limitation such as
division by zero, trying to access an identifier or file which doesn't exists, etc. Python has provision of
check points to handle these errors known as Exception Handling.
For example,
a=10
b=0
c=a/b
Would result in
ZeroDivisionError: division by zero
33. Explain the concept of R-value and L-value with example.
Ans. In a normal expression, the variable to the left side of an assignment operator refers to L-Val..
(left-value) because it resides in memory and is addressable, and an expression after the assignment
operator refers to R-value (right-value). It does not represent an object occupying some identifiable locatio
in memory.
For example, X=1 # X is an L-value
Y=20 # Y is an L-value
Z=X+Y # X+Y is an R-value
34. Write the output of the following: (NCERT)
(a) num1 = 4
num2 = num1 + 1
num1 =
print (numl, num2)
(b) nunl, num2 = 2, 6
numl, num2 = num2, num1 + 2
print (numl, num2)
(c) numl, num2 = 2, 3
num3, num2 = numl, num3 + 1
print (num1, num2,, num3)
Ans. (a) 2, 5
(b) 6, 4
(c) NameError: name 'num3 is not defined

35. Write a program to swap two numbers using a third variable. (NCERT)
Ans. a = int (input ("Enter First Number"))
b= int(input ("Enter Second Number"))
print ("Before Swapping Values are")
print ("Value of First Variable a is", a)
print ("Value of Second Variable b is", b)
C= a

a = b
b = C

print ("After Swapping Values are")


print ("Value of First Variable a is", a)
print ("Value of Second Variable b is", b)
36. Write a program toswap two numbers without using athird variable. (NCERT)
Ans. a = int (input ("Enter First Number"))
b = int (input ("Enter Second Number") )
print ("Before Swapping Values are")
print ("Value of First Variable a i s , a)
print ("Value of Second Variable b is", b)
a = a + b
b = a - b
a= a - b

print ("After Swapping Values are")


print ("Value of First Variable a is", a)
print ("Value of Second Variable b is", b)
OR

You might also like