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

6/26/22, 2:23 AM Untitled9 - Jupyter Notebook

Questions for assignment.

1. Write a program to enter the age of a person and


print that the person is eligible for voting or not.
In [1]:

# *Here, we are implementing a program, it willread age from the user and check
# whether person is eligible for voting or not.

# *This is a simple if else example in the python - Here, we will read the age
# of the person by using input() function and convert the entered age value to
# the integer by using int() function. Then we will check the condition, whether
# age is greater than or equal to 18 or not - if age is greater than or equal to
# 18, the person will be eligible for voting.

#input age
age = int(input("Enter age : "))

# condition to check voting eligibility


if age >= 18:
print("Eligible for Voting!")

else:
print("Not Eligible for Voting!")

Enter age : 19

Eligible for Voting!

2. Write a program to enter three numbers as input and


print the biggest number.
In [ ]:

# In this program, we discuss a simple python program which finds the biggest
# number out of the three input numbers.
# Here we use elif statement to compare 3 numbers and find biggest
# numbers outof them.

localhost:8888/notebooks/Untitled9.ipynb?kernel_name=python3#*-Write-a-python-program-to-print-the-following-pattern-using-loop-concept 1/11
6/26/22, 2:23 AM Untitled9 - Jupyter Notebook

In [8]:

# This statement ask user to enter three numbers and stores the user enteres
# value in variables num1, num2 and num3.

num1 = int(input("Enter first number : "))


num2 = int(input("Enter second number : "))
num3 = int(input("Enter third number : "))

if (num1 >= num2) and (num1 >= num3):


biggest = num1

elif (num2 >= num1) and (num2 >= num3):


biggest = num2

else:
biggest = num3

print("The biggest number is :", biggest)

Enter first number : 49

Enter second number : 19

Enter third number : 81

The biggest number is : 81

3. Write a python code to enter base and height of a


triangle and print the area of triangle.
In [ ]:

# *This program allows the user to enter the base and height of a triangle.
# By using the base and height values, it finds the area of a triangle.
# The mathematical formula to find Area of a triangle using base and height:
# Area = (base * height) / 2.

localhost:8888/notebooks/Untitled9.ipynb?kernel_name=python3#*-Write-a-python-program-to-print-the-following-pattern-using-loop-concept 2/11
6/26/22, 2:23 AM Untitled9 - Jupyter Notebook

In [9]:

# taking the input values of base and height.

base = float(input("Please enter the base of a Triangle :"))


height = float(input("Please enter the height of a Triangle:"))

# Calculate the area

area = (base*height) / 2

print("Area of Triangle using", base, "and", height, " = ", area)

Please enter the base of a Triangle :49

Please enter the height of a Triangle:19

Area of Triangle using 49.0 and 19.0 = 465.5

4. Write a python program to sum all the numbers in a


list using function.
Using sum()method

In [14]:

# program to find sum of all the numbers in a list

# creating a list
list1 = [49, 19, 81, 31, 10, 99]

# using sum() function


total = sum(list1)

#printing total value


print("Sum of all the numbers in a list is :", total)

Sum of all the numbers in a list is : 289

Using Recursive way

localhost:8888/notebooks/Untitled9.ipynb?kernel_name=python3#*-Write-a-python-program-to-print-the-following-pattern-using-loop-concept 3/11
6/26/22, 2:23 AM Untitled9 - Jupyter Notebook

In [13]:

# Python program to find sum of all numbers in list using recursion

# creating a list
list1 = [3, 4, 2001, 31, 10, 99 ]

# creating sum_list function


def sumOfList(list, size):
if (size == 0):
return 0
else:
return list[size - 1] + sumOfList(list, size - 1)

# Driver code
total = sumOfList(list1, len(list1))

print("Sum of all numbers in list is :", total)

Sum of all numbers in list is : 2148

5. Write a python code to print the following pattern


1 1 1 1 1

2 2 2 2 2

3 3 3 3 3

4 4 4 4 4

5 5 5 5 5

In [28]:

# square pattern

for i in range(5):
for j in range(5):
print(i+1, end='')
print()

11111

22222

33333

44444

55555

6. Write a Python program to enter a number from


keyboard and find its factorial. Show the input and
output also.

localhost:8888/notebooks/Untitled9.ipynb?kernel_name=python3#*-Write-a-python-program-to-print-the-following-pattern-using-loop-concept 4/11
6/26/22, 2:23 AM Untitled9 - Jupyter Notebook

In [29]:

# Python program to find the factorial of a number provided by the user.

# take input from the user

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

factorial = 1

# check if the number is negative, positive or zero

if num < 0:
print("Sorry, factorial does not exist for negative numbers")

elif num == 0:
print("The factorial of 0 is 1")

else:
for i in range(1, num + 1):
factorial = factorial*i
print("The factorial of", num, "is", factorial)

Enter a number: 6

The factorial of 6 is 720

7. Write a python code to show how classes are created


and methods are called.
In [ ]:

# In method implementation, if we use only class variables, we should declare


# such methods as class methods. The class method has a cls as the first
# parameter, which refers to the class.

# Class methods are used when we are dealing with factory methods.
# Factory methods are those methods that return a class object for different
# use cases.Thus, factory methods create concrete implementations of a common
# interface.

# The class method can be called using ClassName.method_name() as well as by


# using an object of the class.

localhost:8888/notebooks/Untitled9.ipynb?kernel_name=python3#*-Write-a-python-program-to-print-the-following-pattern-using-loop-concept 5/11
6/26/22, 2:23 AM Untitled9 - Jupyter Notebook

In [38]:

from datetime import date

# Creating a class

class Student:
def __init__(self, name, age): # Constructor to initialize
self.name = name # Instance variables
self.age = age

@classmethod
def calculate_age(cls, name, birth_year): # cls refer to the Class
# calculate age an set it as a age
# return new object
return cls(name, date.today().year - birth_year) # Access Class Variables

def show(self):
print(self.name + "'s age is: " + str(self.age)) # Modify Class Variables

David = Student("David", 25)


David.show() # Call Class Method

# create new object using the factory method


Jason = Student.calculate_age("Jason", 1980)
Jason.show()

David's age is: 25

Jason's age is: 42

8. What do you understand by inheritance? Explain


various types of inheritance used in python.
Inheritance is a process of obtaining properties and characteristics (variables and methods) of another class. In
this hierarchical order, the class which inherits another class is called subclass or child class, and the other
class is the parent class.

Inheritance is categorized based on the hierarchy followed and the number of parent classes and subclasses
involved.

There are five types of inheritances:

1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchial Inheritance
5. Hybrid Inheritance

1. Single Inheritance :
This type of inheritance enables a subclass or derived class to inherit properties and
characteristics of the parent class, this avoids duplication of code and improves code reusability.

localhost:8888/notebooks/Untitled9.ipynb?kernel_name=python3#*-Write-a-python-program-to-print-the-following-pattern-using-loop-concept 6/11
6/26/22, 2:23 AM Untitled9 - Jupyter Notebook

2. Multiple Inheritance :
This inheritance enables a child class to inherit from more than one parent class. This
type of inheritance is not supported by java classes, but python does support this kind of inheritance. It has
a massive advantage if we have a requirement of gathering multiple characteristics from different classes.

3. Multilevel Inheritance :
In multilevel inheritance, the transfer of the properties of characteristics is done to
more than one class hierarchically. To get a better visualization we can consider it as an ancestor to
grandchildren relation or a root to leaf in a tree with more than one level.

4. Hierarchical Inheritance :
This inheritance allows a class to host as a parent class for more than one child
class or subclass. This provides a benefit of sharing the functioning of methods with multiple child classes,
hence avoiding code duplication.

5. Hybrid Inheritance :
An inheritance is said hybrid inheritance if more than one type of inheritance is
implemented in the same code. This feature enables the user to utilize the feature of inheritance at its best.
This satisfies the requirement of implementing a code that needs multiple inheritances in implementation.

9. What are the various IO exceptions and how these


exceptions are handled?
An exception is an event that occurs during the execution of programs that disrupt the normal flow of execution
(e.g., KeyError Raised when a key is not found in a dictionary.) An exception is a Python object that represents
an error..

In Python, an exception is an object derives from the BaseException class that contains information about an
error event that occurred within a method. Exception object contains:

1. Error type (exception name)


2. The state of the program when the error occurred
3. An error message describes the error event.

Exception are useful to indicate different types of possible failure condition.

For example, bellow are the few standard exceptions

1. FileNotFoundException
2. ImportError
3. RuntimeError
4. NameError
5. TypeError

1. Standardized error handling: Using built-in exceptions or creating a custom exception with a more precise
name and description, you can adequately define the error event, which helps you debug the error event.
2. Cleaner code: Exceptions separate the error-handling code from regular code, which helps us to maintain
large code easily.
3. Robust application: With the help of exceptions, we can develop a solid application, which can handle error
event efficiently.

localhost:8888/notebooks/Untitled9.ipynb?kernel_name=python3#*-Write-a-python-program-to-print-the-following-pattern-using-loop-concept 7/11
6/26/22, 2:23 AM Untitled9 - Jupyter Notebook

4. Exceptions propagation: By default, the exception propagates the call stack if you don’t catch it. For
example, if any error event occurred in a nested function, you do not have to explicitly catch-and-forward it;
automatically, it gets forwarded to the calling function where you can handle it.
5. Different error types: Either you can use built-in exception or create your custom exception and group them
by their generalized parent class, or Differentiate errors by their actual class.

10. What do you understand by typecasting? Explain


various functions used for typecasting in python.
Type Casting is the method to convert the variable data type into a certain data type in order to the operation
required to be performed by users. In this article, we will see the various technique for typecasting.

There can be two types of Type Casting in Python –

1. Implicit Type Casting


2. Explicit Type Casting

Type Casting is a process in which we convert a literal of one type to another.

Inbuilt functions int(), float() and str() shall be used for typecasting.

1. "int()" can take a float or string literal as argument and returns a value of class 'int' type.
2. "float()" can take an int or string literal as argument and returns a value of class 'float' type.
3. "str()" can take a float or int literal as argument and returns a value of class 'str' type.

Type Cast int to float and string


In this example, we shall take an integer literal assigned to a variable. Then we shall
typecast this integer to float using float() function.

We shall print both the value and type of the float and string variables.

In [40]:

#integer
n = 100

#float
f = float(n)
print(f)
print(type(f))

#string
s = str(n)
print(s)
print(type(s))

100.0

<class 'float'>

100

<class 'str'>

Type Cast float to int and string


localhost:8888/notebooks/Untitled9.ipynb?kernel_name=python3#*-Write-a-python-program-to-print-the-following-pattern-using-loop-concept 8/11
6/26/22, 2:23 AM Untitled9 - Jupyter Notebook

In the following program, we shall initialize a variable with float value. In the next
statement, we typecast this float to integer using int(). Later we typecast the float to
string.

In [41]:

#float
f = 100.05

#integer
n = int(f)
print(n)
print(type(n))

#string
s = str(f)
print(s)
print(type(s))

100

<class 'int'>

100.05

<class 'str'>

Type Cast string to int and float


In this example, we shall use int() and float() to typecast a string literal to integer
and float.

In [43]:

#string
s = '132'

#typecast to integer
n = int(s)
print(n)
print(type(n))

#typecast to float
f = float(s)
print(f)
print(type(f))

132

<class 'int'>

132.0

<class 'float'>

11. Write a python program to print the following


pattern using loop concept -
*

* *

* * *

* * * *

* * * * *

localhost:8888/notebooks/Untitled9.ipynb?kernel_name=python3#*-Write-a-python-program-to-print-the-following-pattern-using-loop-concept 9/11
6/26/22, 2:23 AM Untitled9 - Jupyter Notebook

In [51]:

# Implementing for loop


# Function to demonstrate printing pattern triangle
def triangle(n):

# number of spaces
k = n - 1

# outer loop to handle number of rows


for i in range(0, n):

# inner loop to handle number spaces


# values changing acc. to requirement
for j in range(0, k):
print(end=" ")

# decrementing k after each loop


k = k - 1
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):

# printing stars
print("* ", end="")

# ending line after each row


print("\r")

# Driver Code
n = 5
triangle(n)

* *

* * *

* * * *

* * * * *

12. Write a python program to print the following


pattern using loop concept-
1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

localhost:8888/notebooks/Untitled9.ipynb?kernel_name=python3#*-Write-a-python-program-to-print-the-following-pattern-using-loop-concept 10/11
6/26/22, 2:23 AM Untitled9 - Jupyter Notebook

In [52]:

# square pattern
# implementing for loop
for i in range(5):
for j in range(5):
print(j+1, end='')
print()

12345

12345

12345

12345

12345

localhost:8888/notebooks/Untitled9.ipynb?kernel_name=python3#*-Write-a-python-program-to-print-the-following-pattern-using-loop-concept 11/11

You might also like