Python UNIT-1
Python UNIT-1
Python UNIT-1
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.
Output:
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.
Output:
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:
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:
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
a % b
Example:
x = 10
y = 2
mod = x % y
print("Modulo of the numbers: ", mod)
Output:
name = "Fred"
print("Name: {0} ".format(name))
Output:
Name: Fred
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
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'>
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:
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:
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)
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)
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.
Output:
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:
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:
Output:
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