Q1. Differentiate B-W List and Tuples Sol.### Lists 1. Mutability Lists Are Mutable, Meaning You Can Change Their Content (Add, Remove, or Modify Elements) - 2. Syntax Defined Using Square Brackets
Q1. Differentiate B-W List and Tuples Sol.### Lists 1. Mutability Lists Are Mutable, Meaning You Can Change Their Content (Add, Remove, or Modify Elements) - 2. Syntax Defined Using Square Brackets
Sol.### Lists: Sol. Slicing is a technique in Python that allows you to access a Sol. Scripting language: Python is considered as
1. **Mutability**: Lists are mutable, specific portion (or "slice") of a sequence type, such as a list, tuple, scripting language as it is interpreted and it
meaning you can change their content or string. It enables you to retrieve a subset of elements without is used on the Internet to support other software.
(add, remove, or modify elements). altering the original sequence. Database connectivity: Python provides interface
2. **Syntax**: Defined using square ### Syntax: to connect its programs to all major
brackets, e.g., `my_list = [1, 2, 3]`. The basic syntax for slicing is: databases like Oracle, Sybase or MySQL.
3. **Performance**: Generally slower than ```python Scalable: Python programs are scalable since they
tuples due to their mutability. sequence[start:stop:step] can run on any platform and use the
4. **Methods**: Have many built-in ``` features of the new platform effectively.
methods like `append()`, `remove()`, and - **start**: The index to start the slice (inclusive). If omitted, defaults Interpreted: Python converts the source code into
`sort()`. to the beginning. an intermediate form called byte codes
5. **Use Cases**: Best suited for - **stop**: The index to end the slice (exclusive). If omitted, defaults and then translates this into the native language of
collections of items that may need to to the end of the sequence. your computer using PVM(Is s interpreter)
change during program execution. - **step**: The amount by which to increment the index. If omitted, and then runs it.
### Tuples: defaults to 1. Easy to learn: Python uses very few keywords.
1. **Immutability**: Tuples are immutable, Python has an extraordinarily simple syntax
meaning once they are created, their Q5. what will be the output of the following: and simple program structure.
content cannot be changed. "FIRST ONLINE TEST" Open Source: There is no need to pay for Python
2. **Syntax**: Defined using parentheses, print(str[2:10:2]) software. Python is FLOSS (Free/Library
e.g., `my_tuple = (1, 2, 3)`. print(str[::-1]) and Open Source Software). It can be free
3. **Performance**: Generally faster than Sol. The code snippet you provided has a small issue. The variable downloaded from www.python.org website. Its
lists, especially for iterations. `str` is a built-in type in Python, so it shouldn't be used as a variable source can be read, modified and used in
4. **Methods**: Have fewer built-in name. However, if we assume you meant to use the string directly, programs as desired by the programmers.
methods, mainly `count()` and `index()`. here's how it should look: High level language: When you write programs in
5. **Use Cases**: Ideal for fixed Python, you never need to bother about
collections of items, such as coordinates ```python the low-level details such as managing the memory
or records. s = "FIRST ONLINE TEST" used by your program, etc.
print(s[2:10:2]) # This slices the string
Q2. Differentiate b-w lists and dictionaries print(s[::-1]) # This reverses the string Q8. What is a tuple? Explain how to define and
Sol. ### Lists: ``` access the elements of the tuple.
1. **Structure**: Ordered collections of ### Outputs: Sol. A tuple is similar to list. A tuple contains group
items indexed by position (0, 1, 2, ...). 1. **`s[2:10:2]`**: of elements which can be different types. The
2. **Syntax**: Defined using square - This slice starts from index 2 up to (but not including) index 10, elements in the tuple are separated by commas
brackets, e.g., `my_list = [1, 2, 3]`. taking every 2nd character. and enclosed in parentheses (). The only
3. **Mutability**: Mutable, allowing - The substring from "FIRST ONLINE TEST" is: difference is that tuples are immutable. Tuples
changes to the contents (add, remove, - Index 2: 'R' once created cannot be modified. The tuple
modify elements). - Index 4: 'T' cannot change dynamically. That means a tuple
4. **Access**: Access elements using their - Index 6: 'O' can be treated as read-only list.
index, e.g., `my_list[0]`. - Index 8: 'N' ### Defining a Tuple
5. **Use Cases**: Best for maintaining - Therefore, the output will be: **`"RTON"`**. You can define a tuple by enclosing a comma-
sequences of items where order matters. 2. **`s[::-1]`**: separated sequence of values in parentheses `()`.
- This reverses the string. **Example**:
### Dictionaries: - The reversed string of "FIRST ONLINE TEST" is: **`"TSET ENIL ```python
1. **Structure**: Unordered collections of OTSIRF"`**. # Defining a tuple
key-value pairs, where each key is unique. ### Final Output: my_tuple = (1, "apple", 3.14, True)
2. **Syntax**: Defined using curly braces, ``` ```
e.g., `my_dict = {'key1': 'value1', 'key2': RTON You can also define a tuple without parentheses,
'value2'}`. TSET ENIL OTSIRF using just commas:
3. **Mutability**: Mutable, allowing ``` ```python
changes to the contents (add, remove, my_tuple = 1, "apple", 3.14, True
modify key-value pairs). Q6. What is the difference between interactive mode and script ```
4. **Access**: Access values using their mode in Python? For a single-element tuple, you need to include a
keys, e.g., `my_dict['key1']`. Sol. Interactive mode trailing comma:
5. **Use Cases**: Best for representing Interactive etymologically means “working simultaneously and ```python
associative arrays or mappings, where you creating impact of our work on the other’s work”. Interactive mode is single_element_tuple = (42,) # This is a tuple with
need to retrieve values based on unique based on this ideology only. In the interactive mode as we enter a one element
keys. command and press enter, the very next step we get the output. The ```
Q3. Wap to enter any number from user output of the code in the interactive mode is influenced by the last ### Accessing Elements of a Tuple
and count the digits command we give. Interactive mode is very convenient for writing You can access elements of a tuple using indexing,
Sol. # Get input from the user very short lines of code. In python it is also known as REPL which which starts at 0. You can also use negative
user_input = input("Enter a number: ") stands for Read Evaluate Print Loop. Here, the read function reads indexing to access elements from the end of the
# Validate if the input is a number the input from the user and stores it in memory. Eval function tuple.
try: evaluates the input to get the desired output. Print function outputs **Example**:
number = int(user_input) the evaluated result. The loop function executes the loop during the ```python
digit_count = len(str(abs(number))) # execution of the entire program and terminates when our program # Accessing elements
Count digits, using abs for negative ends. This mode is very suitable for beginners in programming as it print(my_tuple[0]) # Output: 1
numbers helps them evaluate their code line by line and understand the print(my_tuple[1]) # Output: apple
print(f"The number of digits in {number} execution of code well. print(my_tuple[-1]) # Output: True (last element)
is: {digit_count}") Example: # Python program to add two numbers ```
except ValueError: a=2 ### Slicing a Tuple
print("Please enter a valid integer.") b=3 You can slice a tuple to access a range of elements
# Adding a and b and storing result in c using the same syntax as lists.
c=a+b **Example**:
# Printing value of c ```python
print(c) # Slicing a tuple
Script Mode sliced_tuple = my_tuple[1:3] # Output: ('apple',
Script etymologically means a system of writing. In the script mode, 3.14)
a python program can be written in a file. This file can then be saved
and executed using the command prompt. We can view the code at
any time by opening the file and editing becomes quite easy as we
can open and view the entire code as many times as we want. Script
mode is very suitable for writing long pieces of code. It is much
preferred over interactive mode by experts in the program. The file
made in the script mode is by default saved in the Python
installation folder and the extension to save a python file is “.py”.
Example: # code
a=2
b=3
c-a+b #adding a and b and storing result in c print(c) #printing value of c
Q9. Explain the usage of break and continue Q10. Explain Mutable and Immutable datatypes with
statements. examples. Q12. Differentiate between local and global variables
Sol. Break and Continue in Loops Sol. ### Mutable Data Types with the help of an example.
**Definition**: Mutable data types are those that allow Sol. Local and global variables in Python differ primarily
break statement:
changes to their content after they are created. This
When a break statement executes inside a loop,means you can modify, add, or remove elements without in their scope and lifetime. Here's a concise explanation
control flow comes out of the loop along with an example:
creating a new object.
immediately: **Examples**: ### Local Variables
Example:to demonstrate break 1. **Lists**: - **Scope**: Accessible only within the function or block
i=0 ```python where they are defined.
while i < 7: my_list = [1, 2, 3] - **Lifetime**: Exists only during the execution of that
my_list[0] = 10 # Modifying an element function.
print(i)
my_list.append(4) # Adding an element ### Global Variables
if i == 4: print(my_list) # Output: [10, 2, 3, 4]
print("Breaking from loop") - **Scope**: Accessible throughout the entire program,
```
break including inside functions.
i += 1 2. **Dictionaries**: - **Lifetime**: Exists for the duration of the program's
The loop conditional will not be evaluated after ```python execution.
the break statement is executed. Note my_dict = {'a': 1, 'b': 2} ### Example
my_dict['a'] = 10 # Modifying a value ```python
that break statements are only allowed inside
my_dict['c'] = 3 # Adding a new key-value pair # Global variable
loops. A break statement inside a print(my_dict) # Output: {'a': 10, 'b': 2, 'c': 3}
function cannot be used to terminate loops global_var = "I am a global variable"
```
that called that function. def example_function():
Executing the following prints every digit until ### Immutable Data Types # Local variable
number 4 when the break statement is met and **Definition**: Immutable data types cannot be changed local_var = "I am a local variable"
after they are created. If you attempt to modify them, a print(local_var) # Accessible
the loop stops:
new object is created instead. print(global_var) # Accessible
Output
**Examples**: example_function()
01234 1. **Tuples**:
Breaking from loop # Trying to access local_var outside its function will raise
```python
Break statements can also be used inside for my_tuple = (1, 2, 3) an error
loops, the other looping construct # my_tuple[0] = 10 # This would raise a TypeError # print(local_var) # Uncommenting this line will cause a
provided by Python: print(my_tuple) # Output: (1, 2, 3) NameError
Example: ``` # Accessing global_var outside the function
2. **Strings**: print(global_var) # Accessible
for i in (0, 1, 2, 3, 4):
```python ```
print(i) my_string = "hello"
if i == 2: # my_string[0] = 'H' # This would raise a TypeError
break new_string = my_string.upper() # This creates a new Q13. Write a program to calculate factorial of a number
Executing this loop now prints: string using recursion.
012 print(new_string) # Output: "HELLO" Sol.
Note that 3 and 4 are not printed since the ``` # Input number for which to calculate the factorial
loop has ended. number = 5 # Change this to calculate the factorial of a
Continue statement different number
A continue statement will skip to the next # Recursive lambda function
iteration of the loop bypassing the factorial = (lambda f: (lambda x: f(f, x)))(
rest of the current block but continuing the lambda f, x: 1 if x == 0 else x * f(f, x - 1)
loop. Continue can only used inside loops: )
Example to demonstrate continue # Calculate factorial
for i in (0, 1, 2, 3, 4, 5): result = factorial(number)
if i == 2 or i == 4: # Print the result
continue print(f"The factorial of {number} is {result}")
print(i) Note that 2 and 4 aren't printed, this is
because continue goes to the next
iteration instead of continuing on to print
(i) when i == 2 or i == 4.
Executing this loop now prints:
0135
Q11. Write a Python script to print the fibonacci series of first 20 elements.
Sol. # Number of elements in the Fibonacci series
n = 20
# Initialize the first two Fibonacci numbers
a, b = 0, 1
# Print the first 20 elements of the Fibonacci series
for _ in range(n):
print(a, end=' ')
a, b = b, a + b # Update values for next iteration