Python UNIT-1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

20ES2103B: PYTHON PROGRAMMING

UNIT – 1: BASICS OF PYTHON


QUESTION BANK
1. Explain the primary data types in Python along with variable assignments.
Ans.
Data types are the classification or categorization of data items. It represents the kind of value
that tells what operations can be performed on a particular data. Since everything is an object
in Python programming, data types are actually classes and variables are instance (object) of
these classes.
i) Integers: This value is represented by int class. It contains positive or negative whole
numbers (without fraction or decimal). In Python there is no limit to how long an integer value
can be.
x = 325
print("Number: ", x)
print(type(x))

Output:

Number: 325
<class 'int'>

ii) Float: This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point.

x = 8.43
print("Float: ", x)
print(type(x))

Output:

Float: 8.43
<class 'float'>

iii) String: Strings are arrays of bytes representing Unicode characters. A string is a collection
of one or more characters put in a single quote, double-quote or triple quote. In python there
is no character data type, a character is a string of length one. It is represented by str class.

x = "Python"
print("String: ", x)
print(type(x))

Output:

String: Python
<class 'str'>
iv) Lists: They are just like the arrays, declared in other languages which is an ordered
collection of data. It is very flexible as the items in a list do not need to be of the same type.

x = ["Fork", "and", "Knife"]


print("List: ", x)
print("First element: ", x[0])
print("Middle element: ", x[1])
print("Last element: ", x[2])
print(type(x))

Output:

List: ['Fork', 'and', 'Knife']


First element: Fork
Middle element: and
Last element: Knife
<class 'list'>

v) Tuples: Just like list, tuple is also an ordered collection of Python objects. The only
difference between type and list is that tuples are immutable i.e., tuples cannot be modified
after it is created. It is represented by tuple class. Tuples are created by placing a sequence
of values separated by ‘comma’ with or without the use of parentheses for grouping of the
data sequence.

x = ("Fork", "and", "Knife")


print("Tuple: ", x)
print("First element: ", x[0])
print("Middle element: ", x[1])
print("Last element: ", x[2])
print(type(x))

Output:

Tuple: ('Fork', 'and', 'Knife')


First element: Fork
Middle element: and
Last element: Knife
<class 'tuple'>

vi) Sets: It is an unordered collection of data type that is iterable, mutable and has no duplicate
elements. The order of elements in a set is undefined though it may consist of various
elements.
Sets can be created by using the built-in set() function with an iterable object or a sequence
by placing the sequence inside curly braces, separated by ‘comma’. Type of elements in a set
need not be the same, various mixed-up data type values can also be passed to the set.
x = set(["Fork", "and", "Knife"])
print("Set: ", x)
print("Elements of set: ")
for i in x:
print(i)
print(type(x))

Output:

Set: {'and', 'Fork', 'Knife'}


Elements of set:
and
Fork
Knife
<class 'set'>

vii) Dictionary: It is an unordered collection of data values, used to store data values like a
map, which unlike other Data Types that hold only single value as an element, Dictionary holds
key:value pair. Key-value is provided in the dictionary to make it more optimized. Each key-
value pair in a Dictionary is separated by a colon (:), whereas each key is separated by a
‘comma’. A dictionary can be created by placing a sequence of elements within curly {} braces.
x = {1: 'Fork', 2: 'and', 3: 'Knife'}
print("Dictionary: ", x)
print("Middle element: ", x.get(2))
print(type(x))

Output:

Dictionary: {1: 'Fork', 2: 'and', 3: 'Knife'}


Middle element: and
<class 'dict'>

2. List out the primary keywords in Python along with their functionalities.
Ans.
Keyword Description
and A logical operator
as To create an alias
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception occurs
False Boolean value, result of comparison operations
finally Used with exceptions, a block of code that will be executed no matter if
there is an exception or not
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
None Represents a null value
nonlocal To declare a non-local variable
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement
while To create a while loop
with Used to simplify exception handling
yield To end a function, returns a generator

3. List out the primary operators in Python along with descriptions.


Ans.
Operator Description
** Exponentiation
~ Complement
+ Unary plus
- Unary minus
* Multiply
/ Divide
% Modulo
// Floor division
+ Addition
- Subtraction
>> Right bitwise shift
<< Left bitwise shift
& Bitwise 'AND'
^ Bitwise exclusive `OR'
| Bitwise regular `OR'
<= Comparison operators
<
>
>=
<> Equality operators
==
!=
= %= Assignment operators
/= //=
-= +=
*= **=
is Identity operators
is not
in Membership operators
not in
not Logical operators
or
and
4. What is the modulo ‘%’ operator in Python? How is it used?
Ans.
Modulo: Given two positive numbers, a and b, a modulo b (a % b, abbreviated as a mod b)
is the remainder of the Euclidean division of a by b, where a is the dividend and b is the divisor.
Syntax:

a % b

Example:

x = 10
y = 2
mod = x % y
print("Modulo of the numbers: ", mod)
Output:

Modulo of the numbers: 0

5. Discuss the various String Operations in Python.


Ans.
i) String formatting:
You can use format() function to print a string within a print() statement with formatting.

name = "Fred"
print("Name: {0} ".format(name))

Output:
Name: Fred

ii) String indexing:


Individual characters of a String can be accessed by using the method of Indexing. Indexing
allows negative address references to access characters from the back of the String, e.g., -1
refers to the last character, -2 refers to the second last character and so on.

name = "Fred"
print("Name: ", name)
print("First letter: ", name[0])
print("Last letter: ", name[-1])

Output:

Name: Fred
First letter: F
Last letter: d
iii) String slicing:
To access a range of characters in the String, method of slicing is used. Slicing in a String is
done by using a Slicing operator (colon).

name = "Fredric"
print("Name: ", name)
print("Sides sliced: ", name[2:-1])
print("Left sliced ", name[3:])
print("Right sliced: ", name[:5])

Output:

Name: Fredric
Sides sliced: edri
Left sliced dric
Right sliced: Fredr

iv) String replacing:


A string can be easily replaced by assigning another string to the same variable, thanks to
Python’s line-to-line execution.

name = "Fredric"
name = "Julie"
print("Name: ", name)

Output:

Name: Julie

6. Briefly explain:
i. Boolean expressions
ii. Logical operators
iii. Comparison operators
Ans.
i) Boolean expressions:
The Python Boolean type has only two possible values – True and False.
The value evaluates to True if the condition is true, or evaluates to False if the condition is
false.
The type() of both False and True is bool.
x = 6 == 6 # 6 == 6 is True
print("6 == 6 is", x)
print(type(x))
y = 8 < 5 # 8 < 5 is False
print("8 < 5 is", y)
print(type(y))

Output:

6 == 6 is True
<class 'bool'>
8 < 5 is False
<class 'bool'>

ii) Logical operators:


In Python, Logical operators are used on conditional statements (either True or False). They
perform Logical AND, Logical OR and Logical NOT operations.

OPERATOR DESCRIPTION SYNTAX


and Logical AND: True if both the operands are true x and y
or Logical OR: True if either of the operands is true x or y
not Logical NOT: True if operand is false not x

Example:

a = 5
b = 6
c = 8
and_op = b > a and b == c # b > a is True but b == c is False
print("b > a and b == c is", and_op)

d = 3
e = 4
f = 4
or_op = e > d or e == f # e > d is False, e == f is True
print("e > d or e == f is", or_op)

d = True
not_op = not d # not a is False
print("not d is", not_op)
Output:

b > a and b == c is False


e > d or e == f is True
not d is False

iii) Comparison operators:

Operator Name Example


== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

7. Define the syntax of if…else statement and make use of it to check if a number is
even or odd.
Ans.
An if…else statement is used to make a choice between two alternatives. The code executes
the statements based on if the condition is True or False.
Syntax:

if (condition):
statement(s)
else:
statement(s)

Even or odd:

x = int(input("Enter a number: "))


if x % 2 == 0:
print("Even number")
else:
print("Odd number")
Output:

Enter a number: 6
Even number

Enter a number: 5
Odd number

8. Define the syntax of else…if statement and make use of it to check if a number is
positive, negative or zero.
Ans.
An else…if statement is used to make a decision between many alternatives. The code
executes the statements of only the true condition among all other conditions.
Syntax:

if (condition1):
statement(s)
elif(condition2):
statement(S)
.
.
else:
statement(s)

Positive, negative or zero:

num = int(input("Enter a number: "))


if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

Output:

Enter a number: 5
Positive number

Enter a number: 0
Zero

Enter a number: -7
Negative number
9. Define the syntax of ‘nested’ if statement and make use of it to find the biggest of
three numbers.
Ans.
If an if…else statement is nested with another if…else statement, then it is called ‘nested’
if statement.

Syntax:

if (condition1):
if (condition2):
statement(s)
else:
statement(s)
else:
statement(s)

Biggest of three numbers:

a = int(input("Enter a : "))
b = int(input("Enter b : "))
c = int(input("Enter c : "))
if a > b:
if a > c:
print("a is big")
else:
print("b is big")
else:
if b > c:
print("b is big")
else:
print("c is big")

Output:

Enter a : 7
Enter b : 4
Enter c : 3
a is big
10. Using try and except, write a program to convert Celsius to Fahrenheit, but when
a string is given as input, print a warning message.
Ans.

inp = input("Enter Fahrenheit: ")


try:
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print("In Celsius: ", cel)
except:
print("You entered a string! Please enter a number")

Output:

Enter Fahrenheit: 34.5


In Celsius: 1.3888888888888888

Enter Fahrenheit: ninety


You entered a string! Please enter a number

11. Briefly explain the short-circuit evaluation of logical expressions in Python.


Ans.
When Python is processing a logical expression such as x >= 2 and (x/y) > 2, it evaluates
the expression from left to right. Because of the definition of and, if x is less than 2, the
expression x >= 2 is False and so the whole expression is False regardless of whether
(x/y) > 2 evaluates to True or False.

When Python detects that there is nothing to be gained by evaluating the rest of a logical
expression, it stops its evaluation and does not do the computations in the rest of the logical
expression. When the evaluation of a logical expression stops because the overall value is
already known, it is called short-circuiting the evaluation.

>>> x = 6
>>> y = 2
>>> x >= 2 and (x/y) > 2
True
>>> x = 1
>>> y = 0
>>> x >= 2 and (x/y) > 2
False
>>> x = 6
>>> y = 0
>>> x >= 2 and (x/y) > 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>
The third calculation failed because Python was evaluating (x/y) and y was zero, which
causes a runtime error. But the second example did not fail because the first part of the
expression x >= 2 evaluated to False so the (x/y) was not ever executed due to the short-
circuit rule and there was no error.

>>> x = 1
>>> y = 0
>>> x >= 2 and y != 0 and (x/y) > 2
False
>>> x = 6
>>> y = 0
>>> x >= 2 and y != 0 and (x/y) > 2
False
>>> x >= 2 and (x/y) > 2 and y != 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

• In the first logical expression, x >= 2 is False so the evaluation stops at the and. In the
second logical expression, x >= 2 is True but y != 0 is False so we never reach (x/y).
• In the third logical expression, the y != 0 is after the (x/y) calculation so the expression
fails with an error.
• In the second expression, we say that y != 0 acts as a guard to insure that we only
execute (x/y) if y is non-zero.
12. Define the syntax of while loop and make use of it to find the sum of ‘n’ natural
numbers.
Ans.
A while loop is used to execute a block of statements repeatedly until a given condition is
satisfied. And when the condition becomes false, the line immediately after the loop in the
program is executed. While loop falls under the category of indefinite iteration. Indefinite iteration
means that the number of times the loop is executed isn’t specified explicitly in advance.
Syntax:

while expression:
statement(s)
Sum of ‘n’ natural numbers:

n = int(input("Enter n: "))
total = 0
while n > 0:
total = total + n
n = n - 1
print("Total is: ", total)

Output:

Enter n: 10
Total is: 55

13. Define the syntax of for loop and make use of it to print all the numbers between
two intervals a and b.
Ans.
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a
set, or a string).
Syntax:

for variable in range(upper, lower):


statement(s)

Printing all the numbers between two intervals a and b:

a = int(input("Enter a: "))
b = int(input("Enter b: "))
for i in range(a, b + 1):
print(i)

Output:

Enter a: 23
Enter b: 27
23
24
25
26
27
14. i) Make a countdown from number 20 but stop the countdown at the number
provided as input using the break statement.
ii) Print each letter in the word “indivisibilities” except the i’s using
continue statement.

Ans.
i) Source code:

stop = int(input("Enter stopping number: "))


count = 20
while count > 0:
if count == stop:
break
else:
print(count)
count = count - 1
print(stop)

Output:

Enter stopping number: 5


20
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
ii) Source code:

word = "indivisibilities"
for letter in word:
if letter == "i":
continue
print("Current Letter: ", letter)

Output:

Current Letter: n
Current Letter: d
Current Letter: v
Current Letter: s
Current Letter: b
Current Letter: l
Current Letter: t
Current Letter: e
Current Letter: s

15. List out the key features of Python programming language which make it stand
out of all the other high-level languages.
Ans.

• Easy Language
• Readable
• Interpreted Language
• Dynamically-Typed Language
• Object-Oriented
• Popular and Large Community Support
• Open-Source
• Large Standard Library
• Platform-Independent
• Extensible and Embeddable
• GUI Support

 THE END 


(Prepared by Department of EIE)

You might also like