Nothing Special   »   [go: up one dir, main page]

Python 2

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

PART-A

Q) Defining a Python Function

To define a function in Python, you start with the keyword "def" followed by the function
name and parentheses. Inside the parentheses, you can specify input parameters. The
function block is indicated by a colon and is indented.

Q) Python Functions

Python functions are defined using the keyword def followed by the function name and
parentheses. Input parameters are placed within these parentheses, and the code block
within the function is indented and starts with a colon. The return statement exits a
function, optionally passing back an expression to the caller.

There are two basic types of functions in Python: built-in functions that are part of the
language like min(), max(), len(), and abs(), and user-defined functions created by the
programmer using the def keyword followed by the function name.

Lambda functions in Python are small anonymous functions that can take any number of
arguments but can only have one expression. An example of a lambda function is x = lambda a, b:
a * b.

Q) Identifier Definition:

An identifier is a sequence of characters used to name a program element. It can contain


letters, digits, and underscores, but must start with a letter or underscore. Identifiers in
Python are case sensitive.

Q) Keywords in Python

Keywords in Python are predefined identifiers with specific meanings in the programming
language. They cannot be used as regular identifiers in code.

For example, some keywords in Python include True, False, None, and, or, if, else, def,
class, and many more.
Q) Python Variables: Mutable and Immutable

Mutable vs. Immutable Types:


In Python, some values can be modified (mutable), while others cannot (immutable).
Immutable types like integers, floating-point numbers, and strings cannot be altered
once assigned a value. To change the value of a variable containing an immutable type,
a new value must be assigned.

Variable Names and Types:


Variables in Python are names used to refer to memory locations and hold values.
Python is a type-inferred language, meaning it automatically determines variable types.
Variable names must follow specific rules, such as starting with a letter or underscore
and being case-sensitive.

Data Types in Python:


Python has various built-in data types, including text types (str), numeric types (int, float,
complex), sequence types (list, tuple, range), and more. Each data type serves different
purposes and can be identified using the type() function in Python.

Arithmetic Operators:
Arithmetic operators in Python include addition, subtraction, multiplication, division,
modulus, exponentiation, and truncating division. For example,
x = 5
,
y = 10
,
x + y
would result in
15
Relational Operators:
Relational operators in Python are used for comparing values and include greater than,
greater than or equal to, less than, less than or equal to, equal to, and not equal to. For
example,
a > b
would return
True
if
a
is greater than
b
.

Logical Operators:
Logical operators like
and
,
or
, and
not
are used to combine conditional statements in Python. For instance,
x > 3 and x < 10
would return
True
if
x
is greater than 3 and less than 10.
Membership Operators:
Membership operators
in
and
not in
are useful to check for membership in sequences like strings, lists, tuples, and
dictionaries. If an element is found in the sequence, the
in
operator returns
True
.

Unary and Binary Operators:

Operators in Python can be unary (acting on a single variable) or binary (acting on two
variables). Unary operators work on a single variable, while binary operators work on two
variables.

Q) Data Types in Python

Python has various built-in data types categorized as follows:

• Text Type: str


• Numeric Types: int, float, complex
• Sequence Types: list, tuple, range
• Mapping Type: dict
• Set Types: set, frozenset
• Boolean Type: bool
• Binary Types: bytes, bytearray, memoryview

To determine the data type of an object, the type() function can be used.
Q) Expression in Python with Example and Types

Expression in Python: An expression in Python is a combination of values, variables,


and operators that results in a single value. Examples of expressions include arithmetic
expressions like

5 + 3
or
x * y
, where
x
and
y
are variables.

Types of Expressions: There are different types of expressions in Python, such as


arithmetic expressions, logical expressions, relational expressions, and more. Each type
serves a specific purpose in Python programming.

Q) Control Structures with Suitable Example

Sequential Control Structure: Sequential control structure executes instructions in the


order they are written without any jump of control. It follows a linear flow from one
instruction to the next.

a = 10
b=a
print(“ a = b ”)
Indentation in Python: Indentation refers to the space that are
used in the beginning of a statement.
Statements within the same indentation belongs to the same
group called suite.
Note: By default, Python uses 4 spaces for indentation.

Selective Control Structure: Selective control structure selectively executes instructions based
on conditions. Examples include 'if', 'if-else', 'if-elif-else' statements where different paths are
taken based on the conditions

Example:

x = int(input(“Enter any number”))


if x%2 == 0:
print(“Even number”)
else:
print(“Odd number”)

Iterative Control Structure: Iterative control structure repeats a set of statements in a loop
until a condition is met. Examples include 'while' loop, 'for' loop, 'break', and 'continue'
statements for looping and controlling the flow of execution.

Example 1:
Iterating through list using for loop
L = [1,5,6,4,7,1,2,3,7]
for i in L:
print(I)
Example 2:
L = [1,5,6,4,7,1,2,3,7]
for i in L:
print(i, end = " ")

Q) Explanation of the range() function

The
range()
function in Python is used to generate a sequence of numbers. It can define the start, stop, and
step size, with the default step size being 1. The numbers generated by
range()
are not stored in memory.
When used in a
for
loop,
range()
helps iterate over a sequence of numbers. It is a useful tool for creating loops that run a specific
number of times based on the given range.

PART-B

Q) Explanation of Strings with Examples

String Definition:
A string is a sequence of characters enclosed within single, double, or triple quotes. For
example, 'Hello', "Smith, John", and "Baltimore, Maryland" are string literals.

String Usage:
Strings are commonly used for representing text data in programming. They can be
manipulated, formatted, and displayed in various ways within a program.

String Example:
An example of using a string in Python is:

name = 'Alice'
print('Hello, ' + name)
In this example, the variable
name
stores the string 'Alice', which is then concatenated with 'Hello, ' and printed to the console.
OUTPUT (Hello, Alice)
Accessing Strings:

• Strings are stored as individual characters in a contiguous memory location.


• Both forward and backward indexing are supported in Python strings.

Example:
my_string = "Python"
print(my_string[0]) # Output: P (forward indexing)
print(my_string[-1]) # Output: n (backward indexing)

1. Concatenating Strings:
o Strings can be concatenated using the + operator.

Example:
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: John Doe

2. String Slicing:
o Substrings can be extracted using slicing with the syntax [start:stop:step].

Example:
my_string = "Python Programming"
print(my_string[0:6]) # Output: Python
3. String Methods:
o Python provides a variety of built-in methods to manipulate strings, such
as upper(), lower(), replace(), split(), etc.

Example:
my_string = "Hello, World!"
print(my_string.upper()) # Output: HELLO, WORLD!

4. Deleting Strings:
o While individual characters in a string cannot be deleted, the entire string can be deleted using
the del keyword.

Example:
my_string = "Python"
del my_string
# After deletion, trying to access my_string will raise an error.

Q) list slicing (adding elements to a list )

List slicing in Python allows you to access a range of elements from a list and also update multiple
elements by using slice assignment. Here is an explanation along with examples of adding elements
to a list using list slicing:
1. List Slicing for Adding Elements:
o List slicing can be used to add elements to a list by specifying the slice range where the new
elements should be inserted.
o By using slice assignment, you can update multiple elements in a list at once.
2. append() – The append() method appends an element to the end of the list.

3. Syntax: list.append(element)
4. Parameter Values

Parameter Description

element Required. An element of any


type (string, number etc.)
5. extend() – The extend() method adds the specified list elements (or any iterable) to the
end of the current list.
6. Syntax: list.extend(iterable)

Parameter Description
iterable Required. Any iterable (list, set,
tuple, etc.)

Q) Deleting from a list (various methods with example)


Deleting elements from a list in Python can be done using various methods such
as remove(), pop(), del, and slicing. Here are examples of each method for deleting elements from
a list:

1. Using remove() Method:


o The remove() method removes the specified item from the list.

Example:
my_list = ['apple', 'banana', 'cherry', 'apple']
my_list.remove('apple')
print(my_list) # Output: ['banana', 'cherry', 'apple']

2. Using pop() Method:


o The pop() method removes the item at the specified index. If no index is specified, it removes the
last item.

Example:
my_list = ['apple', 'banana', 'cherry']
removed_item = my_list.pop(1)
print(removed_item) # Output: 'banana'
print(my_list) # Output: ['apple', 'cherry']

3. Using del Keyword:


o The del keyword is used to delete elements from a list or the entire list.

Example:
my_list = ['apple', 'banana', 'cherry']
del my_list[1]
print(my_list) # Output: ['apple', 'cherry']
del my_list[0:2]
print(my_list) # Output: []

4. Using List Slicing to Delete Elements:


o List slicing can be used to delete elements by specifying the slice range.

Example:
my_list = ['apple', 'banana', 'cherry', 'date']
my_list[1:3] = [] # Delete elements at index 1 and 2
print(my_list) # Output: ['apple', 'date']

5. Using clear() Method:


o The clear() method removes all items from the list.

Example:
my_list = ['apple', 'banana', 'cherry']
my_list.clear()
print(my_list) # Output: []

By using these methods, you can easily delete elements from a list based on your requirements.

Q )Tuples(definition with an example)

Definition of Tuples: A tuple in Python is an immutable collection of elements, similar to a list, but
once created, its elements cannot be changed, added, or removed. Tuples are defined using
parentheses () and can contain elements of different data types. Tuples are commonly used to store
related pieces of information that should not be modified.
Example of Tuples:

# Creating a tuple
student = ('Alice', 25, 'Computer Science', 3.8)

# Accessing tuple elements


print(student[0]) # Output: 'Alice'
print(student[2]) # Output: 'Computer Science'

# Iterating over a tuple


for item in student:
print(item)

# Tuple unpacking
name, age, major, gpa = student
print(name) # Output: 'Alice'
print(age) # Output: 25
print(major) # Output: 'Computer Science'
print(gpa) # Output: 3.8
In the example above:

• A tuple named student is created with elements representing a student's name, age, major, and
GPA.
• Elements of the tuple can be accessed using index positions.
• The for() loop demonstrates iterating over the tuple.
• Tuple unpacking is used to assign individual elements of the tuple to separate variables for easy
access

Q) What are the methods available to delete elements from a list?


(differentiate between discard and remove method).

In Python, there are several methods available to delete elements from a list. Two common methods
are remove() and pop(). Additionally, when working with sets,
the discard() and remove() methods are used to delete elements.

Comparison between discard() and remove() methods.

1. remove() Method:
o The remove() method is used to remove a specified element from a set. If the element is not
present in the set, a KeyError is raised.

Example:
my_set = {1, 2, 3, 4, 5}
my_set.remove(3)
print(my_set) # Output: {1, 2, 4, 5}

2. Discard() Method:
o The discard() method is also used to remove a specified element from a set. However, if the
element is not present in the set, no error is raised.

Example:
my_set = {1, 2, 3, 4, 5}
my_set.discard(3)
print(my_set) # Output: {1, 2, 4, 5}

my_set.discard(6) # No error raised


print(my_set) # Output: {1, 2, 4, 5}

3. Difference between discard() and remove():


o remove(): Raises a KeyError if the element is not present in the set.
o discard(): Does not raise any error if the element is not present in the set; it simply does nothing.

4. Additional Method for Lists:


o In lists, the pop() method is commonly used to remove an element at a specified index and return
its value.

EXAMPLE: my_list = [1, 2, 3, 4, 5]


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

Q) Dictionaries with example

Dictionaries in Python: Dictionaries in Python are unordered collections of key-value pairs. Each key
in a dictionary is unique and is used to access its corresponding value. Dictionaries are defined using
curly braces “{}” and consist of key-value pairs separated by a colon “:”. Dictionaries are mutable,
allowing for the addition, modification, and deletion of key.

# Creating a dictionary of student information


student = {
'name': 'Alice',
'age': 25,
'major': 'Computer Science',
'gpa': 3.8
}

# Accessing dictionary elements


print(student['name']) # Output: 'Alice'
print(student['major']) # Output: 'Computer Science'

# Modifying dictionary values


student['age'] = 26
print(student['age']) # Output: 26

# Adding a new key-value pair


student['year'] = 3
print(student) # Output: {'name': 'Alice', 'age': 26, 'major': 'Computer
Science', 'gpa': 3.8, 'year': 3}

# Removing a key-value pair


del student['gpa']
print(student) # Output: {'name': 'Alice', 'age': 26, 'major': 'Computer
Science', 'year': 3}

# Iterating over dictionary keys and values


for key, value in student.items():
print(key, ':', value)

In the example above:

• A dictionary named student is created with key-value pairs representing student information.
• Elements in the dictionary are accessed using their keys.
• Values in the dictionary can be modified by assigning new values to the corresponding keys.
• New key-value pairs can be added to the dictionary using assignment.
• Key-value pairs can be removed from the dictionary using the del keyword.
• The items() method is used to iterate over the dictionary and access both keys and values.

Dictionaries are versatile data structures in Python that allow for efficient storage and retrieval of
data based on unique keys.
PROGRAMS

Program 1:
Write a program that prompts a user to enter two different numbers.
Perform basic arithmetic operations based on the choices.

num1 = eval(input("Enter the first number: "))


num2 = eval(input("Enter the second number: "))
print("1: Addition")
print("2: Subtraction")
print("3: Multiplication")
print("4: Integer Division")
print("5: Float Division")
choice = int(input("Please Enter the Choice: "))
if(choice == 1):
print("Addition of ", num1, "and ", num2, " is: ", num1 + num2)
elif(choice == 2):
print("Subtraction of ", num1, "and ", num2, " is: ", num1 - num2)
elif(choice == 3):
print("Multiplication of ", num1, "and ", num2, " is: ", num1 * num2)
elif(choice == 4):
print("Integer Division of ", num1, "and ", num2, " is: ", num1 // num2)
elif(choice == 5):
print("Float Division of ", num1, "and ", num2, " is: ", num1 / num2)
else:
print("Sorry!!! Invalid Choice")

Program 4:

Write a program in Python to Find the area of a triangle from its sides
import math
a = int(input('Enter side 1 '))
b = int(input('Enter side 2 '))
c = int(input('Enter side 3 '))
s = float(a+b+c)/2
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
print('Area = ', area)
Program :6

Write a program in Python to Roots of a quadratic equation ax**2 + bx +


c = 0 given a,b and c

the ones digit'))


sum = int(ones * (2 ** 0))
tens = int(input('enter the tens digit'))
sum = int(sum + tens *(2**1))
hund = int(input('enter the hundreds digit'))
sum = int(sum + hund *(2**2))
th = int(input('enter the thousands digit'))
sum = int(sum + th*(2**3))
print('sum = ', sum)

Program 10:

import math

a = float(input('Enter a'))

b = float(input('Enter b'))

c = float(input('Enter c'))

dis = (b**2) - (4*a*c)

root1 = (-b+ math.sqrt(dis))/(2*a)

root2 = (-b-math.sqrt(dis))/(2*a)

print('Root 1 ', root1)

print('Root2 ', root2)


Program 11a:
Write a program in Python to Write a python program
to determine a number is even or odd.

x=int(input('Enter any number'))


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

Program 11b:
Write a python program to know whether a number is
positive or negative or zero.
x = int(input('Enter any number'))
if x<0:
print('Negative number')
elif x>0:
print('Positive number')
else:
print('Zero')

Program 12a:
Write a Program in Python to Read two
numbers num1 and num2 and find the largest of two and
find the largest of two and also check for equality.

num1 = int(input('Enter num1 '))


num2 = int(input('Enter num2 '))
if num1 > num2:
print('num1 is greater than num2',num1)
elif num1 < num2:
print('num2 is greater than num1',num2)
else:
print('num1 and num2 are equal')
Program 12b:
Write a Program in Python to Read three
numbers and find the largest of three.

num1 = int(input('Enter num1'))


num2 = int(input('Enter num2'))
num3 = int(input('Enter num3'))
if num1 > num2:
print('num1',num1)
elif num2 > num3:
print('num2',num2)
else:
print('num3',num3)

Program 13a:
Write a Python script that reads the numeric grade of a
student and print its equivalent letter grade as given below:

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


if G >= 90 and G <= 100:
print("A")
elif G >= 80 and G < 90:
print("B")
elif G >= 70 and G < 80:
print("C")
elif G >= 60 and G < 70:
print("D")
elif G >= 0 and G < 60:
print("F")
else:
print("Please enter a valid grade between 0 and 100.")
Program 14a:
Write a Python script to read the length and breadth of a
rectangular garden in centimeters. The program should also find the cost
of
fencing the garden, if the cost of fencing per cm Rs.168.
Program :
l = float(input("enter the length of the garden"))
b = float(input("enter the breadth of the garden"))
p = 2 * (l + b)
cost = p * 168
print('Perimeter of the garden is', p)
print('Cost of fencing the garden is', cost)

Program 15a:
Write a Program to read the three sides of a triangle
and check whether it is Equilateral, Isosceles or Scalene Triangle
a = int(input("ENter the first side"))
b = int(input("ENter the second side"))
c = int(input("ENter the third side"))
if ((a == b) and (a == c)):
print("Equilateral")
elif ((a == b) or (b == c) or (c == a)):
print("Isosceles Triangle")
else:
print("Scalene Triangle")
Program 16:
Write a Python script to read the x and y co-ordinate of
a point (x, y) and find the quadrant in which the point lies as given
below
x=int(input("enter x-axis: "))
y=int(input("enter y-axis: "))
if (x > 0 and y > 0):
print ("lies in First quadrant")
elif (x < 0 and y > 0):
print ("lies in Second quadrant")
elif (x < 0 and y < 0):
print ("lies in Third quadrant")
elif (x > 0 and y < 0):
print ("lies in Fourth quadrant")
elif (x == 0 and y > 0):
print ("lies at positive y axis")
elif (x == 0 and y < 0):
print ("lies at negative y axis")
elif (y == 0 and x < 0):
print ("lies at negative x axis")
elif (y == 0 and x > 0):
print ("lies at positive x axis")
else:
print ("lies at origin")

Program 19a:

Write a program to check if the given number is prime or not


num=int(input())
if num==1 or num==0:
print ("Neither prime nor composite")
else:
for i in range(2,num):
if (num%i==0):
print("Not Prime")
break
else:
print("Prime")
Program 20:
Write a Python program to construct the following pattern, using a
nested for loop.

n = int(input('Enter a number'))

for i in range(1,10+1):

print("{0} * {1} = {2}".format(n,i,n*i))

Program 21:
Write a Python program to Print first n terms of the fibonacci series.
a = 0
b = 1
n = int(input('enter the number of terms'))
if n == 1:
print(a)
elif n == 2:
print("{0} \n{1}".format(a,b))
else:
print("{0} \n{1}".format(a,b))
count = 2
while(count < n):
c = a + b
print(c)
count = count + 1
a = b
b = c
PROGRAM 23a:
Create a Python script that assists users in identifying the position of a
specific substring within a given main string. The script should prompt the
user to input both the main string and the substring, and then return the
index position of the substring within the main string. If the substring is
not found, it should return -1.

main_str=input("enter main string:")


sub_str=input("enter sub string:")
#Search for the sub-string
n=main_str.find(sub_str)
if n==-1:
print("sub string not found")
else:
print("sub string found @:",n)

PROGRAM 23b:
Write a Program in python that ask the user to input a string which
contains at-least 4 words. Capitalize first letter of each word and display
output by merging all capital letters in the string.

s=input()
a=s.title()
newstring=""
for i in a:
if i.isupper():
newstring+=i
print(newstring)

Program 24a:
Write a program in python to Search an element in a list

a = [1, 3, 5]
b = [2, 4, 6]
c = a + b
d = sorted(c)
d.reverse()
c[3] = 42
d.append(10)
c.extend([7, 8, 9])
print(c[0:3])
print(d[-1])
print(len(d))
Program 26a.
a. Create a tuple a which contains the first four positive integers and a tuple
b which contains the next four positive integers.
b. Create a tuple c which combines all the numbers from a and b in any
order.
c. Create a tuple d which is a sorted copy of c.
d. Print the third element of d.
e. Print the last three elements of d without using its length. Print the
length of d.

a = (1, 2, 3, 4)
b = (5, 6, 7, 8)
c = a + b
d=tuple(sorted(a))
print(d[2])
print(d[-3:])
print(len(d))

Program 27a:
creates a dictionary daily_temp containing the temperatures for Saturday
and Sunday. Then compares the temperatures of Saturday and Sunday and
prints a message indicating which day was warmer, or if both days had
equal temperatures.

daily_temp = {'sat': 25, 'sun': 28}


# Comparing temperatures of Saturday and Sunday
if daily_temp['sun'] > daily_temp['sat']:
print('Sunday was the warmer weekend')
elif daily_temp['sun'] < daily_temp['sat']:
print('Saturday was the warmer weekend')
else:
print('Saturday and Sunday were equally warm')
Program 27b:
Given an integer number ‘n’, write a program to generate a dictionary with
i and square of i, such that i is an integer between 1 and n(both included).
The program should then print the dictionary.

n = int(input('Enter the limit '))


d = dict()
for i in range(1,n+1):
d[i] = i * i
print(d)

You might also like