Ass 1 Ans

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

Q.1) What is single line and multiline comment?

Ans Anything that is written in a single line after '#' is considered as a comment. The syntax for writing
single-line comments is: # comments here. There are two ways of using single-line comments in Python.
You can use it before the code or next to the code.

2) Write python program swapping of two numbers?

Ans x = 10

y = 50

temp = x

x=y

y = temp

print("Value of x:", x)

print("Value of y:", y)

3) What is literal?

Ans literals are a data type and can hold any value type, such as strings, numbers, and more.

4) Explain following terms:

a)Indentation

Ans White spaces at the beginning of line called indentation. In python indentation is used to associate
and group statement.(:)

a=20
b=10
if(a==b):
print("Equal“)
else:
print("Not equal")
if(a>b):
print("A is big")
else:
print("B is big")

b) Reserved Words
• Ans Reserved words (also called keywords) are defined with predefined meaning an syntax in
the language.
• These keywords have to be used to develop programming instructions.
• Reserved words can’t be used as identifiers for other programming elements like name of
variable, function etc.
• Reserved words: Total -35

c) comment
Ans Comments in Python are identified with a hash symbol, #, and extend to the end of the line.

5)Write python program for addition of two numbers?


Ans
x=5
y = 10
c=x+y
print("Add of 2 no is ",c)

6) Explain mutable and immutable data types


Ans
Mutable objects in Python are those that can be changed after they are created, like lists or dictionaries.
Immutable objects, on the other hand, cannot be changed after they are created, such as strings,
integers, or tuples.

7) Explain input and output operation with example


Ans
INPUT

• In Python the input() function is used to take input from the user.
• To take input from users, Python makes use of input() function. The input() prompts the user to
provide some information on which the program can work and give the result.
• However, we must always remember that the input() function takes input as a string. So
whether you input a number or a string, it is treated as a string only.
OUTPUT
• In Python, we can simply use the print() function to print output.
8) Explain features of python programming language.
Ans
• Simple – Simple and small language, Feel like reading English.
• Easy to learn- Structure of program is simple, uses few keywords and clearly defined syntax.
• Free and open source- Anyone freely distribute it, read the source code, edit, and use the code
to write new program
• High-level language- Programmer does not need to worry about low level details like managing
memory.
• Interactive- Programmer can easily interact with interpreter or compiler directly at python
prompt to write their program
• Portable or Cross platform- Program behaves same on the wide variety of hardware platform,
Program work on any of the operating system like Windows, Linux, Solaris etc

9) What is identifier? Explain rules for naming identifier


Ans
• Variable are example of identifiers. Identifiers as the name suggests, are name given to identify
something. This something can be a variable, function, class, module, or other object.
For naming any identifier, there are some basic rules that you must follow.
• The first character of an identifier must be an underscore(‘_’) or a letter(upper or lower case)
• The rest of identifier name can be underscore(_), letter(upper or lowercase), or digits(0-9).
• Identifier names are case sensitive. For example, myvar and myVar are not same.
• Punctuation character such as @, $, and % are not allowed within identifiers.
• Keyword not allowed in variable name.
• Ex- Valid Identifier- sum, _my_var, num1, r, var_20, First, etc.
• Ex- Invalid identifier- 1num, my-var, %check, Basic Sal, H#R&A etc.

10) Explain following operators in python


a) Arithmetic operators
Python Arithmetic operators are used to perform basic mathematical operations like addition,
subtraction, multiplication, and division.
Operator Description Syntax

Addition: adds two


+ x+y
operands

– Subtraction: subtracts two x–y


Operator Description Syntax

operands

Multiplication: multiplies
* x*y
two operands

Division (float): divides the


/ x/y
first operand by the second

Division (floor): divides the


// x // y
first operand by the second

Modulus: returns the


remainder when the first
% x%y
operand is divided by the
second

Power: Returns first raised


** x ** y
to power second

b) 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 Example

Returns True if
and both the operands x and y x>7 and x>10
are true

Returns True if
or either of the x or y x<7 or x>15
operands is true

Returns True if the


not not x not(x>7 and x> 10)
operand is false

c) Membership operators
The Python membership operators test for the membership of an object in a sequence, such as
strings, lists, or tuples. Python offers two membership operators to check or validate the
membership of a value. They are as follows:
Membership
Operator Description Syntax

Returns True if the value exists in a


in Operator value in sequence
sequence, else returns False

Returns False if the value exists in a value not


not in Operator
sequence, else returns True in sequence

d) Relational operators
The different types of Comparison Operators in Python are as follows:
Operator Description Syntax

Python Equality
== Equal to: True if both operands are equal a == b
Operators

Inequality Not equal to: True if operands are not


!= a != b
Operators equal

Greater than: True if the left operand is


Greater than Sign > a>b
greater than the right

Less than: True if the left operand is less


Less than Sign < a<b
than the right

Greater than or equal to: True if left


Greater than or
>= operand is greater than or equal to the a >= b
Equal to Sign
right

Less than or Equal Less than or equal to: True if left


<= a <= b
to Sign operand is less than or equal to the right

11) Explain different data types used in python.


Ans
 Numbers:
Numeric data type can belong to following different numerical types :
 Integers Numbers- int
• Both positive and negative number including 0.
• There Should not be any fraction part.
Ex- 3, -5, -7, 0, 100, 350
 Complex Numbers- complex
• In the forms of real part and imaginary part of complex number.
• The numerals will be in the form of a+bj, where a is the real part and b is the imaginary part.
Where a and b are int or float value.
• 1. e.g. a=10+20j, b= 2.3+3.14j
2. e.g. k=7j - real part is 0 here.
Other than j not allowed.
• We can perform operation on complex numbers- a+b, a-b, a*b, a/b.
 Boolean- bool
- There are only two Boolean type in Python. They are True and False.
- a = True - True represent value 1
- b = False - False represent value 0
 String- str
• A string is a group of characters. If you want to use text in python, you have to use a string.
• Using single quotes- Ex. ‘Hello’
• Using double quotes- Ex. “Hello”
• Using triple single quotes or triple double quotes- ‘’’Hello ‘’’
-By using triple quotes we can write multi-line strings or display in the desired way.
‘’’Hello,
How
are
You?’’’

12) Explain else using loops


Ans
Else with loop is used with both while and for loop. The else block is executed at the end of loop means
when the given loop condition is false then the else block is executed. So let’s see the example of while
loop and for loop with else below.

i=0
while i<5:
i+=1
print("i =",i)
else:
print("else block is executed")

Output i = 1
i=2
i=3
i=4
i=5
else block is executed

13) Explain while loop with example


Ans
Python While Loop is used to execute a block of statements repeatedly until a given condition is
satisfied. When the condition becomes false, the line immediately after the loop in the program is
executed.
Syntax of while loop in Python
while expression:
statement(s)
example
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
output
Hello Geek
Hello Geek
Hello Geek

14) Explain nested if with example


Ans
In Python a Nested if statement, we can have an if…elif…else statement inside another if…elif…else
statement. This is called nesting in computer programming.
Example
i = 0;
# if condition 1
if i != 0:
# condition 1
if i > 0:
print("Positive")

# condition 2
if i < 0:
print("Negative")
else:
print("Zero")
output
zero

15) Describe following with example


a) break -- To break out of loop

b) continue – to continue to the next iteration of loop

c) pass – a null statement, a statement that will be do nothing

16) What is list? Explain following operations of list


Ans
If we want group of items in single entity.
List is Mutable.
List is an ordered sequence of items.
Insertion order is preserved and duplicates is allowed
e. g. list = [10,20,30,’Python’,10]

17) Explain if..elif..else statement


Ans if – to make a conditional statement

elif – used in conditional statement same as if else

else – used in conditional statement

18) Explain different Dictionary methods.


Ans
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered, changeable and do not allow duplicates key.
• Dictionaries are written with curly brackets, and have keys and values
• In Python, a dictionary can be created by placing a sequence of elements within curly {} braces,
separated by ‘comma’.
Example:
dict={1:”apple”,2:”cherry”,3:”mango”,4:”melon”}
print(dict)
Output:
{1:”apple”,2:”cherry”,3:”mango”,4:”melon”}

19)Explain tuple with example?


Ans
• Tuples are used to store multiple items in a single variable.
• A tuple is a collection which is ordered and immutable i.e unchangeable.
• Tuple allow duplicate value or item.
• Tuples are written with round brackets. ( )
Example-
t1 = ("apple", "banana", "cherry")
print(t1)
t2=(‘A’,10,20,’B’)
Print(t2)
Create a Tuple:
mytuple = (‘apple’, ‘banana’, ‘cherry’)
print(mytuple)
Output :
('apple', 'banana', 'cherry')
Accessing Tuple Items :
mytuple = ("apple", "banana", "cherry")
print(mytuple[1])
Output :
banana

Programs
Q.1) Write a python program to check whether number is positive,
negative or zero?
# Python program to check whether
# the number is positive, negative
# or equal to zero

def check(n):

# if the number is positive


if n > 0:
print("Positive")

# if the number is negative


elif n < 0:
print("Negative")

# if the number is equal to


# zero
else:
print("Equal to zero")

# Driver Code
check(5)
check(0)
check(-5)

Q.2) Write a python program to print factorial of a number?


# Python 3 program to find
# factorial of given number
def factorial(n):

# single line to find factorial


return 1 if (n==1 or n==0) else n * factorial(n - 1)

# Driver Code
num = 5
print("Factorial of",num,"is",factorial(num))

Q.3) Write a python program to print sum of 1-10 numbers?


num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate un till zero
while(num > 0):
sum += num
num -= 1
print("The sum is",sum)
output 55

Q.4) Write a python program to find maximum of three numbers?


def maximum(a, b, c):

if (a >= b) and (a >= c):


largest = a
elif (b >= a) and (b >= c):
largest = b
else:
largest = c

return largest

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


b = int(input("Enter a number: "))
c = int(input("Enter a number: "))

# Call the function to find the maximum and then print the result
print("The maximum of", a, ",", b, "and", c, "is", maximum(a, b, c))

Q.5) Write a program in Python to find whether gives is even or odd.?


def check_even_odd(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"
# Taking input from the user
num = int(input("Enter a number: "))

# Calling the function to check whether the number is even or odd


result = check_even_odd(num)

# Displaying the result


print("The number", num, "is", result)

Q.6) Write a program to swap two numbers.?


def swap_numbers(a, b):
print("Before swapping:")
print("a =", a)
print("b =", b)
# Swapping the values
a, b = b, a
print("After swapping:")
print("a =", a)
print("b =", b)
# Taking input from the user
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
# Calling the function to swap the numbers
swap_numbers(num1, num2)

Q.7) Write a program to generate a Fibonacci series of ‘n’ numbers


def generate_fibonacci(n):
fibonacci_series = []

# First two numbers of Fibonacci series


a, b = 0, 1

# If n is less than or equal to 0, no Fibonacci series can be generated


if n <= 0:
return "Please enter a positive integer for 'n'"
# If n is 1, return the first Fibonacci number
elif n == 1:
return [a]
# If n is 2, return the first two Fibonacci numbers
elif n == 2:
return [a, b]
else:
# Generating Fibonacci series for n > 2
fibonacci_series = [a, b]
for _ in range(2, n):
c=a+b
fibonacci_series.append(c)
a, b = b, c
return fibonacci_series

# Taking input from the user


num_terms = int(input("Enter the number of terms for Fibonacci series: "))

# Calling the function to generate Fibonacci series


fib_series = generate_fibonacci(num_terms)

# Displaying the Fibonacci series


print("Fibonacci series of", num_terms, "numbers:", fib_series)

Q.8) Write a program in Python to find no is Prime or not?


def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
number = int(input("Enter a number to check if it's prime: "))
if is_prime(number):
print(number, "is a prime number")
else:
print(number, "is not a prime number")

Q.9) Write a program for multiplication tables of numbers from 1 to


10?
def multiplication_tables():
for i in range(1, 11): # Loop through numbers from 1 to 10
print(f"Multiplication table for {i}:")
for j in range(1, 11): # Loop through multiples from 1 to 10
print(f"{i} * {j} = {i * j}")
print() # Empty line after each table
# Calling the function to print multiplication tables
multiplication_tables()

Q.10) Write a program for accepting two numbers and performing


addition, Substraction,Multiplication,Division
def perform_operations(num1, num2):
# Addition
addition = num1 + num2
print("Addition:", num1, "+", num2, "=", addition)

# Subtraction
subtraction = num1 - num2
print("Subtraction:", num1, "-", num2, "=", subtraction)

# Multiplication
multiplication = num1 * num2
print("Multiplication:", num1, "*", num2, "=", multiplication)

# Division
if num2 != 0: # Check if the second number is not zero to avoid division by zero error
division = num1 / num2
print("Division:", num1, "/", num2, "=", division)
else:
print("Division by zero is not allowed")

# Taking input from the user


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Calling the function to perform operations


perform_operations(num1, num2)

Q.11) Write a program to calculate square of number?


Ans def calculate_square(number):
return number ** 2

# Taking input from the user


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

# Calling the function to calculate the square


square = calculate_square(num)

# Displaying the result


print("The square of", num, "is", square)

Q.12) Calculate cube of given no?


def calculate_cube(number):
return number ** 3
num = float(input("Enter a number: "))
cube = calculate_cube(num)
print("The cube of", num, "is", cube)

Q.13) Write a program find greatest no among three no?


def find_greatest(a, b, c):
greatest = a
if b > greatest:
greatest = b

if c > greatest:
greatest = c

return greatest
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

greatest_num = find_greatest(num1, num2, num3)

print("The greatest number among", num1, ",", num2, ", and", num3, "is", greatest_num)

Q.14) Write Python Program Print message 10 times?


def print_message(message, times):
for _ in range(times):
print(message)

# Taking input from the user


message = input("Enter the message to print: ")

# Calling the function to print the message 10 times


print_message(message, 10)
Q.15) Write Python Program to accept number from user and print
factorial of it
def factorial(n):
if n == 0 or n == 1:
return 1
else:
result = 1
for i in range(2, n + 1):
result *= i
return result

number = int(input("Enter a number to calculate its factorial: "))


# Calling the function to calculate factorial
fact = factorial(number)

print("The factorial of", number, "is", fact)

Q.16)Write a program to print following Patteran

**

***

****

*****
def print_pattern(rows):
for i in range(1, rows + 1):
for j in range(i):
print("*", end=" ")
print()

num_rows = int(input("Enter the number of rows for the pattern: "))

# Calling the function to print the pattern


print_pattern(num_rows)

Q.17) Perform following Methods of tuple

a) Accessing value
# Define a tuple
my_tuple = (10, 20, 30, 40, 50)

# Accessing values using indexing


first_element = my_tuple[0]
second_element = my_tuple[1]
third_element = my_tuple[2]
# Printing the accessed values
print("First element:", first_element)
print("Second element:", second_element)
print("Third element:", third_element)

b) Display values
# Define a tuple
my_tuple = (10, 20, 30, 40, 50)

# Displaying all values of the tuple


print("Values of the tuple:")
print(my_tuple)

c)Delete values
# Define a tuple
my_tuple = (10, 20, 30, 40, 50)

# Display the tuple before deletion


print("Original tuple:", my_tuple)

# Deleting the entire tuple


del my_tuple

# Try to display the tuple after deletion (this will raise an error because the tuple no longer exists)
print("Tuple after deletion:", my_tuple) # This will raise a NameError

d)len() function
# Define a tuple
my_tuple = (10, 20, 30, 40, 50)

tuple_length = len(my_tuple)

# Display the length of the tuple


print("Length of the tuple:", tuple_length)

e)max() function
# Define a tuple
my_tuple = (10, 20, 30, 40, 50)
max_value = max(my_tuple)

# Display the maximum value


print("Maximum value in the tuple:", max_value)

f) min() function
# Define a tuple
my_tuple = (10, 20, 30, 40, 50)

min_value = min(my_tuple)

# Display the minimum value


print("Minimum value in the tuple:", min_value)

Q.18) Dictionary Operation

1) Repetition (Multiplication):
You can use the repetition operator `*` to repeat a tuple a certain number of times.
# Define a tuple
my_tuple = (1, 2, 3)

# Repeat the tuple three times


repeated_tuple = my_tuple * 3

# Display the repeated tuple


print("Repeated tuple:", repeated_tuple)
Output:
Repeated tuple: (1, 2, 3, 1, 2, 3, 1, 2, 3)

2) Concatenation:
You can use the concatenation operator `+` to concatenate two or more tuples.
# Define two tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)

# Concatenate the tuples


concatenated_tuple = tuple1 + tuple2

# Display the concatenated tuple


print("Concatenated tuple:", concatenated_tuple)

Output:
Concatenated tuple: (1, 2, 3, 4, 5, 6)

3) Membership:
You can use the membership operator `in` to check if an element exists in a tuple.
# Define a tuple
my_tuple = (1, 2, 3, 4, 5)

# Check if 3 exists in the tuple


if 3 in my_tuple:
print("3 exists in the tuple")
else:
print("3 does not exist in the tuple")

Output:
3 exists in the tuple

4) Length:
You can use the `len()` function to find the length of a tuple.
# Define a tuple
my_tuple = (1, 2, 3, 4, 5)

# Find the length of the tuple


tuple_length = len(my_tuple)

# Display the length of the tuple


print("Length of the tuple:", tuple_length)
Output:
Length of the tuple: 5

Q.19) Perform following Methods of List


a) Accessing value
# Creating a list
my_list = [10, 20, 30, 40, 50]

# Accessing value at a specific index


index = 4
value = my_list[index]
print(f"Value at index {index}: {value}")

Output -- 50
b) Display list
# Creating a list
my_list = [10, 20, 30, 40, 50]

# Displaying the list


print("List contents:", my_list)
Output -- List contents: [10, 20, 30, 40, 50]

c) Add element in list


my_list = [1, 2, 3, 4]
my_list.append(5)
print(my_list)
Output: [1, 2, 3, 4, 5]

d) Delete list element


my_list = [1, 2, 3, 4, 5]
del my_list[2] # Remove element at index 2 (third element)
print(my_list)
Output: [1, 2, 4, 5]

Q.20) Dictionary Operation


a) creating dictionary
# Method 1: Using curly braces and specifying key-value pairs
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

# Method 2: Using the dict() constructor and passing key-value pairs as arguments
my_dict = dict(key1='value1', key2='value2', key3='value3')

# Method 3: Using a list of tuples where each tuple represents a key-value pair
my_dict = dict([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])

# Method 4: Using a list of two-element lists where each list represents a key-value
pair
my_dict = dict([['key1', 'value1'], ['key2', 'value2'], ['key3', 'value3']])

# Method 5: Using a dictionary comprehension


my_dict = {key: value for key, value in [('key1', 'value1'), ('key2', 'value2'), ('key3',
'value3')]}

# Method 6: Starting with an empty dictionary and adding key-value pairs


my_dict = {}
my_dict['key1'] = 'value1'
my_dict['key2'] = 'value2'
my_dict['key3'] = 'value3'
print(my_dict)

b) Access elements
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
value = my_dict['key2']
print(value)
Output: value2

c) Update dictionary
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
my_dict['key2'] = 'new_value'
print(my_dict)
Output: {'key1': 'value1', 'key2': 'new_value', 'key3': 'value3'}

e) Delete element in dictionary


my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
del my_dict['key2']
print(my_dict)
Output: {'key1': 'value1', 'key3': 'value3'}

You might also like