0% found this document useful (0 votes)
21 views13 pages

QB CT 1

The document covers various aspects of Python programming, including identity operators, differences between lists and tuples, local and global variables, and features of Python. It explains data types, decision-making statements, and provides examples of built-in functions for lists and sets. Additionally, it discusses creating and accessing dictionaries, as well as programming examples for calculating factorials and the sum of digits.

Uploaded by

shrikantmore3896
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views13 pages

QB CT 1

The document covers various aspects of Python programming, including identity operators, differences between lists and tuples, local and global variables, and features of Python. It explains data types, decision-making statements, and provides examples of built-in functions for lists and sets. Additionally, it discusses creating and accessing dictionaries, as well as programming examples for calculating factorials and the sum of digits.

Uploaded by

shrikantmore3896
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

2M

1. List identity operators in python.


• is
• is not
2. Give two differences between list and tuple.

3. Explain Local and Global variable.


• Local variable: is defined inside a function and can only be accessed within that
function. It has a limited scope, meaning it exists only during the function's
execution and is destroyed once the function completes. On the other hand,
• Global variable: is defined outside any function and can be accessed from
anywhere in the program. It has a broader scope, available throughout the entire
program, and exists as long as the program is running.

4. List features of Python.


• Easy to Learn and Use
• High-Level Language
• Interpreted Language
• Dynamically Typed
• Cross-Platform
• Extensive Standard Library
• Object-Oriented
• Extensible
• Garbage Collection
• Support for Multiple Paradigms
• Large Community and Ecosystem
• Integrated with Other Technologies
• Readable and Maintainable Code
5. Describe membership operators in python.

6. Write down the output of the following Python code


>>>indices=['zero','one','two','three','four','five']
>>>indices[:4]
>>>indices[:-2]
['zero', 'one', 'two', 'three'] ['zero', 'one', 'two', 'three']

7. Enlist applications for python programming.


• Web Development
• Data Science and Analytics
• Machine Learning and Artificial Intelligence
• Automation and Scripting
• Game Development
• Desktop GUI Applications
• Network Programming
• Scientific Computing
• Embedded Systems
• Cybersecurity
• Education
• Financial and Trading Applications
• Cloud Computing
• Natural Language Processing (NLP)
• Testing and Quality Assurance

8. Write the use of elif keyword in python.


The elif keyword in Python is used to check multiple conditions in an if-else chain. It
stands for "else if" and allows you to test additional conditions if the previous ones
are false. It avoids the need for nested if statements and makes the code cleaner.

9. Describe the Role of indentation in python.


In Python, indentation is used to define code blocks, such as loops, conditionals,
functions, and classes. It replaces the need for curly braces ({}) in other languages.
Proper indentation is essential for Python to understand the structure of the code.
Incorrect indentation leads to errors like IndentationError. Indentation also improves
code readability and visually represents the flow of the program.

10. Enlist any four data structures used in python.


• List
• Tuple
• Dictionary
• Set

11. Write syntax for a method to sort a list.


list_name.sort()

12. What is dictionary?


A dictionary in Python is an unordered collection of items. It is a mutable, flexible
data structure that stores data in key-value pairs. Each key in a dictionary is unique,
and it is used to access the associated value.

4M
1. Explain four Buit-in tuple functions python with example
• cmp(tuple1, tuple2):Compares elements of both tuples.
• len(tuple):Gives the total length of the tuple.
• max(tuple):Returns item from the tuple with max value.
• min(tuple):Returns item from the tuple with min value.
• tuple(seq):Converts a list into tuple.

2. List Data types used in python. Explain any two with example.
Python has several built-in data types. Some of the common ones include:
• Numeric Types: int, float, complex
• Sequence Types: list, tuple, range
• Text Type: str
• Mapping Type: dict
• Set Types: set, frozenset
• Boolean Type: bool
• Binary Types: bytes, bytearray, memoryview
• None Type: NoneType
• Explanation of Two Data Types:
• int (Integer):This data type represents whole numbers (both positive
and negative) without any decimal points.
Example:
age = 25 # Here, 'age' is an integer.
print(type(age))
# Output: <class 'int'>
• str (String):
This data type represents a sequence of characters enclosed in either single
quotes (') or double quotes (").
Example:
name = "John Doe" # 'name' is a string.
print(type(name)) # Output: <class 'str'>
print(name) # Output: John Doe

3. Explain membership and assignment operators with example.


• Membership Operator

• Assignment Operator
4. Explain indexing and slicing in list with example.
Indexing and Slicing in Lists:
In Python, indexing and slicing are used to access elements from a list (or other
sequences like strings and tuples).

1. Indexing:
Indexing refers to accessing individual elements in a list by using their position (index)
in the list. In Python, list indices start at 0.
Example of Indexing:
# List of fruits
fruits = ['apple', 'banana', 'cherry', 'orange', 'grape']

# Accessing elements using indexing


print(fruits[0]) # Output: apple (first element, index 0)
print(fruits[3]) # Output: orange (fourth element, index 3)
print(fruits[-1]) # Output: grape (last element, index -1)
print(fruits[-2]) # Output: orange (second last element, index -2)

2. Slicing:
Slicing refers to accessing a range of elements in a list. You can specify a starting index,
an ending index, and an optional step.
The syntax for slicing is:
list[start:end:step]
• start: The index to start the slice (inclusive).
• end: The index to end the slice (exclusive).
• step: The step size (optional). It decides how many indices to skip.
Example of Slicing:
# List of fruits
fruits = ['apple', 'banana', 'cherry', 'orange', 'grape']

# Slicing examples
print(fruits[1:4]) # Output: ['banana', 'cherry', 'orange'] (from index 1 to 3)
print(fruits[:3]) # Output: ['apple', 'banana', 'cherry'] (from the start to index 2)
print(fruits[2:]) # Output: ['cherry', 'orange', 'grape'] (from index 2 to the end)
print(fruits[::2]) # Output: ['apple', 'cherry', 'grape'] (every second element)
print(fruits[1:5:2]) # Output: ['banana', 'orange'] (from index 1 to 4, step 2)

5. Explain decision making statements If- else, if- elif- else with example.
Decision Making Statements: if-else and if-elif-else
In Python, decision-making statements are used to execute a block of code based on
certain conditions. The primary decision-making statements are:
• if statement: Executes a block of code if the condition is True.
• else statement: Executes a block of code if the condition in the if statement is
False.
• elif (short for "else if") statement: Checks another condition if the if condition is
False.

• if-else Statement:
The if-else statement allows you to check if a condition is True. If it is, the code under
if is executed; if it is False, the code under else is executed.
Syntax:
if condition:
# code to execute if condition is True
else:
# code to execute if condition is False
Example:
age = 18

# Using if-else statement


if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Output:
You are an adult.
In this example:
• The condition age >= 18 is True, so the code under the if block executes, and the
message "You are an adult." is printed.
• If age were less than 18, the code under the else block would have executed.

• if-elif-else Statement:
The if-elif-else statement is used when there are multiple conditions to check. You can
use multiple elif blocks to check for different conditions, and the first one that
evaluates to True will execute its block of code. If none of the conditions are True, the
else block will be executed.
Syntax:
if condition1:
# code to execute if condition1 is True
elif condition2:
# code to execute if condition2 is True
elif condition3:
# code to execute if condition3 is True
else:
# code to execute if all conditions are False
Example:
score = 75

# Using if-elif-else statement


if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Output:
Grade: C
In this example:
• The program checks the value of score and finds that it is 75.
• It first checks if score >= 90, which is False.
• Then, it checks if score >= 80, which is also False.
• It checks the next condition score >= 70, which is True, so the message "Grade: C"
is printed.
• The else block is not executed because one of the conditions was True.

6. Explain membership and Identity operators in Python.


• Membership Operator

• Identity Operator
7. Write the output of the following:
>>> a = [2, 5, 1, 3, 6, 9, 7 ]
>>> a [ 2 : 6] = [ 2, 4, 9, 0]
print (a)

b. >>> b = [ “Hello” , “Good” ]

>>> b. append ( “python” )


>>> print (b)

c. >>> t1 = [ 3, 5, 6, 7 ] >>> print (t 1 [2])

>>> print (t 1 [–1])

>>> print (t 1 [2 :])


>>> print (t 1 [:])
a. [2, 5, 2, 4, 9, 0, 7]
b. ['Hello', 'Good', 'python']
c. 6
7
[6, 7]
[3, 5, 6, 7]

8. Explain creating Dictionary and accessing Dictionary Elements with example


Creating a Dictionary in Python:
A dictionary in Python is an unordered collection of data stored in key-value pairs.
Each key is unique and maps to a value. Dictionaries are defined using curly braces
{}, with each key-value pair separated by a colon : and pairs separated by commas.
Syntax:
dictionary = {key1: value1, key2: value2, key3: value3, ...}
Example of Creating a Dictionary:
# Creating a dictionary with key-value pairs
person = {
'name': 'John',
'age': 30,
'city': 'New York'
}

print(person)
Output:
{'name': 'John', 'age': 30, 'city': 'New York'}
In this example:
• The key 'name' maps to the value 'John'.
• The key 'age' maps to the value 30.
• The key 'city' maps to the value 'New York'.

Accessing Dictionary Elements:


You can access the elements of a dictionary by using the key inside square brackets
[]. You can also use the get() method to access a value.
1. Accessing Using Square Brackets ([]):
The key is passed inside square brackets to get the associated value.
2. Accessing Using get() Method:
The get() method returns the value for the given key, and it allows you to provide a
default value if the key is not found.
Example:
# Accessing dictionary elements
print(person['name']) # Output: John (accessing by key 'name')
print(person['age']) # Output: 30 (accessing by key 'age')

# Using get() method


print(person.get('city')) # Output: New York (accessing by key 'city')
print(person.get('country', 'Not Found')) # Output: Not Found (key 'country'
doesn't exist)
Output:
John
30
New York
Not Found
9. Write a Python program to find the factorial of a number provided by the user.
# Function to calculate factorial
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i # Multiply result by the current number
return result
# Taking input from the user
num = int(input("Enter a number to find its factorial: "))

# Checking if the number is negative


if num < 0:
print("Factorial does not exist for negative numbers.")
else:
# Calculating factorial
result = factorial(num)
print(f"The factorial of {num} is {result}.")

10. Write a Python program to calculate sum of digit of given number using function
# Function to calculate the sum of digits
def sum_of_digits(number):
total = 0
while number > 0:
total += number % 10 # Add the last digit to the total
number //= 10 # Remove the last digit
return total

# Taking input from the user


num = int(input("Enter a number to calculate the sum of its digits: "))

# Calling the function to calculate the sum of digits


result = sum_of_digits(num)

print(f"The sum of digits of {num} is {result}.")

11. Differentiate between list and Tuple


12. Explain any four set function with example
Here's a short explanation of the four set functions:
• add(): Adds a single element to a set (duplicates are not allowed).
Ex: my_set.add(4) # Adds 4 to the set
• remove(): Removes a specified element from the set. Raises a KeyError if the
element is not found.
Ex: my_set.remove(3) # Removes 3 from the set
• union(): Combines two sets and returns a new set with all unique elements from
both sets.
Ex: result = set1.union(set2) # Returns elements from both set1 and set2
• intersection(): Returns a new set with elements that are common to both sets.
Ex: result = set1.intersection(set2) # Returns elements common to both set1 and
set2
13. Explain four built-in list functions.
Here are four built-in list functions in Python, explained briefly:
• append(): Adds an element to the end of the list.
Ex: my_list.append(5) # Adds 5 to the end of the list
• extend(): Adds all elements from another iterable (like a list) to the end of the
current list.
Ex: my_list.extend([6, 7]) # Adds 6 and 7 to the list
• insert(): Inserts an element at a specific index in the list.
Ex: my_list.insert(2, 10) # Inserts 10 at index 2
• remove(): Removes the first occurrence of a specified element.
Ex: my_list.remove(3) # Removes the first occurrence of 3 from the list

14. Explain use of Pass and Else keyword with for loops in python
• pass Keyword in Python
The pass keyword is a null operation. It is used when a statement is syntactically
required but you do not want to execute any code. It’s often used as a placeholder for
future code or when a loop or condition doesn’t require any action.
Example using pass in a for loop:
for i in range(5):
if i == 3:
pass # No action taken when i is 3
else:
print(i) # Prints numbers except 3
Output:
0
1
2
4
• else Keyword with for Loop
The else keyword in a for loop executes a block of code if the loop completes
normally (i.e., without encountering a break statement). It is typically used for
situations where you need to check if a loop completed fully without interruption.
Example using else with for loop:
for i in range(5):
if i == 3:
print("Found 3, exiting loop.")
break # Exits the loop
else:
print("Loop completed without break.")

# Second loop where no break occurs


for i in range(5):
print(i)
else:
print("Loop completed without break.")
Output:
Found 3, exiting loop.
0
1
2
3
4
15. Write the output of the following:
T = (‘spam’, ‘Spam’, ‘SPAM!’, ‘SaPm’)
print (T[2])
print (T[-2])
print (T[2:])
print (List (T))
SPAM!
SPAM!
('SPAM!', 'SaPm')
['spam', 'Spam', 'SPAM!', 'SaPm']
16. Write python program to perform following operations on set.
a. Create set of five elements
b. Access set elements
c. Update set by adding one element
d. Remove one element from set.
# a. Create a set of five elements

my_set = {10, 20, 30, 40, 50}

# b. Access set elements (sets do not support indexing, so we can iterate


through the set)

print("Accessing set elements:")

for element in my_set:

print(element)

# c. Update set by adding one element

my_set.add(60) # Adds 60 to the set

print("\nUpdated set after adding an element:")

print(my_set)

# d. Remove one element from set

my_set.remove(20) # Removes 20 from the set

print("\nUpdated set after removing an element:")

print(my_set)

You might also like