Python 2
Python 2
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:
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
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
.
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.
To determine the data type of an object, the type() function can be used.
Q) Expression in Python with Example and Types
5 + 3
or
x * y
, where
x
and
y
are variables.
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:
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 = " ")
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
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:
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.
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
Parameter Description
iterable Required. Any iterable (list, set,
tuple, etc.)
Example:
my_list = ['apple', 'banana', 'cherry', 'apple']
my_list.remove('apple')
print(my_list) # Output: ['banana', 'cherry', 'apple']
Example:
my_list = ['apple', 'banana', 'cherry']
removed_item = my_list.pop(1)
print(removed_item) # Output: 'banana'
print(my_list) # Output: ['apple', 'cherry']
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: []
Example:
my_list = ['apple', 'banana', 'cherry', 'date']
my_list[1:3] = [] # Delete elements at index 1 and 2
print(my_list) # Output: ['apple', 'date']
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.
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)
# 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
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.
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}
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.
• 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.
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
Program 10:
import math
a = float(input('Enter a'))
b = float(input('Enter b'))
c = float(input('Enter c'))
root2 = (-b-math.sqrt(dis))/(2*a)
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.
Program 13a:
Write a Python script that reads the numeric grade of a
student and print its equivalent letter grade as given below:
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:
n = int(input('Enter a number'))
for i in range(1,10+1):
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.
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.