Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Long Python

Uploaded by

doritosra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Long Python

Uploaded by

doritosra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

10/24/24, 11:16 PM 00000

Explain the following terms:-


(i) Pass (ii) Continue (iii) break
Here's a brief explanation of the programming
terms pass, continue, and break:
(i) Pass:
The pass statement in programming is used
when a statement is syntactically required
but no action is needed. It is often used as a
placeholder when you are working on new
code and want to leave a section for later.
example- if condition:
pass # Do nothing for now
(ii) Continue:
The continue statement is used inside loops
to skip the current iteration and move to the
next one. When continue is encountered, the
loop bypasses any remaining code in the
current iteration and starts the next iteration
immediately.
example- for i in range(5):
if i == 3:
continue # Skip iteration when i is 3
print(i)
(iii) Break:
The break statement is used to exit a loop
prematurely. It is often used when a certain
condition is met, and there's no need to
continue looping.
for i in range(5):
if i == 3:
break # Exit the loop when i is 3
print(i)
Summary:
pass: Does nothing, a placeholder.
continue: Skips the rest of the current
loop iteration.
break: Exits the loop completely.

Explain while loop and for loop


with an example. Elaborate
difference between them.
While Loop:
A while loop repeatedly executes a block of
code as long as a specified condition is True.
The condition is evaluated before each
iteration, and if the condition becomes False,
the loop stops.
Example: i = 0
while i < 5:
print(i)
i += 1
Explanation:
The loop continues as long as i is less
than 5.
After each iteration, i increases by 1.
The loop stops when i becomes 5.

For Loop:
A for loop iterates over a sequence (like a
list, string, or range) and executes a block of
code for each element in that sequence.
Example: for i in range(5):
print(i)
Explanation:
The loop runs 5 times, with i taking
values from 0 to 4.
It automatically stops after completing
the range of values.

Key Differences Between while


and for Loops:
Aspect While Loop For Loop
Runs as long as Iterates over a
Condition- a condition is sequence (e.g.,
based True.
list, range,
etc.).
Best for
Used when the iterating
number of through a
Use case iterations is collection or
not known when number
beforehand. of iterations is
known.
No explicit
The condition is condition;
Condition checked before
Evaluation every iterates
iteration. through items
in a sequence.
for i in
Example while i < 5:
range(5):
Controlled by Terminates
after the
Termination the condition
becoming sequence has
False.
been fully
iterated over.

Conclusion:
Use while loop when you need a loop
to continue until a condition changes.
Use for loop when you know the
number of iterations in advance or
want to iterate through a collection.

about:blank 1/9
10/24/24, 11:16 PM 00000
How many operators are
available in python? Explain all
with suitable examples.
In Python, there are 7 categories of
operators that are used to perform different
types of operations on values and variables.
These are:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

1. Arithmetic Operators
These operators are used to perform
mathematical operations like addition,
subtraction, etc.
Operator Description Example
+ 5 + 3 =
Addition 8
5 - 3 =
- Subtraction 2
* Multiplication 515* 3 =
5 / 3 =
/ Division 1.666...
%
Modulus 5 % 3 =
(Remainder) 2
5 ** 3 =
** Exponentiation 125

// Floor Division 5 // 3 =
1
2. Comparison (Relational)
Operators
These operators are used to compare two
values. The result is either True or False.
Operator Description Example
== 5 == 3
Equal to (False)
!= Not equal to 5 != 3
(True)
> Greater than 5 > 3 (True)
5 < 3
< Less than (False)
>=
Greater than or 5 >= 3
equal to (True)
<= Less than or equal to 5(False)
<= 3

3. Assignment Operators
These operators are used to assign values to
variables.
Operator Description Example
= Assigns value x = 5
x += 3 (x = x +
+= Adds and assigns 3)

-=
Subtracts and x -= 3 (x = x -
assigns 3)
*=
Multiplies and x *= 3 (x = x *
assigns 3)
/= Divides and x /= 3 (x = x /
assigns 3)
%= Modulus and x %= 3 (x = x %
assigns 3)
**= Exponent and x **= 3 (x = x
assigns ** 3)
//= Floor divide and x //= 3 (x = x
assigns // 3)

4. Logical Operators
These operators are used to perform logical
operations, returning either True or False.
Operator Description Example
and True if both are (5 > 3) and (5
True < 8) (True)
or True if at least (5 > 3) or (5
one is True > 8) (True)
not Inverts the not(5 > 3)
result (False)

5. Bitwise Operators
These operators work with binary numbers
(bit-level operations).
Operator Description Example
& Bitwise AND 5 & 3 = 1
` ` Bitwise OR
^ Bitwise XOR 5 ^ 3 = 6
~ Bitwise NOT ~5 = -6
<< Left Shift 5 << 1 = 10
>> Right Shift 5 >> 1 = 2

6. Membership Operators
These operators are used to test whether a
value is a member of a sequence like strings,
lists, or tuples.
Operator Description Example
True if value is 'a' in
in found in the 'apple'
sequence (True)
True if value is not 'b' not in
not in found in the 'apple'
sequence (True)

7. Identity Operators
These operators are used to compare objects,
to check if they are the same object in
memory.
Operator Description Example
is
True if both variables x is y
point to the same object
True if both variables x is not
is not point to different
objects y

about:blank 2/9
10/24/24, 11:16 PM 00000
Conclusion:
Python provides a variety of operators to
perform different operations. Understanding
these operators allows developers to
manipulate data and control the flow of logic
in programs effectively.

What is the difference between


interactive mode and script
mode in python?
Difference Between Interactive
Mode and Script Mode in
Python:
Aspect Interactive Script Mode
Mode
Code is
Code is executed
written in a
line by line as
Execution soon as it's file and
executed as a
typed. whole.
Code is
written in a
Typically used in script file
Environment Python shell or (e.g., .py file)
command line and executed
(REPL). from a
terminal or
an editor.
Best for
Best for quick writing and
Use Case testing, running
debugging, and large,
experimenting. complete
programs.
Code is not Code is saved
saved in a file, so it
Persistence automatically; can be re-
once the session executed or
ends, the code is modified
lost. later.
Outputs are Output is
immediate, as shown only
Output each line is after the
executed entire script
instantly. is executed.
Examples:
1. Interactive Mode:
When you open a Python shell
and type:
>>> 2 + 3 5 >>>
print("Hello") Hello
The results are displayed
immediately after each line.
2. Script Mode:
You write a script in a file
named example.py:
a = 2 + 3 print(a)
print("Hello")
You then run this file from the
terminal:
python example.py
The output is displayed after
the entire script is executed.

Key Points:
Interactive mode is more suitable for
small code snippets and learning.
Script mode is used for writing full
programs and storing them for future
use.

Explain membership operator,


identity operator, escape
sequence, slicing with an
example.
1. Membership Operator:
The membership operators (in, not in) are
used to test whether a value is present in a
sequence (like a list, tuple, string, etc.).
Example:
my_list = [1, 2, 3, 4, 5] print(3 in
my_list) # True print(6 not in
my_list) # True

in checks if 3 is in my_list and


returns True.
not in checks if 6 is not in my_list,
which also returns True.

2. Identity Operator:
The identity operators (is, is not) are used
to compare if two variables refer to the same
object in memory, not just if their values are
equal.
Example:
a = [1, 2, 3] b = [1, 2, 3] c = a
print(a is b) # False (a and b have
the same value but are different
objects) print(a is c) # True (a and
c refer to the same object) print(b
is not c) # True (b and c are
different objects)

is checks whether two variables


point to the same object.
is not checks if they point to
different objects.

3. Escape Sequence:
Escape sequences are used to insert special
characters in a string. They are preceded by a
backslash (\) and represent characters that
have special meanings (like newline, tab,
etc.).
Example:
print("Hello\nWorld") # Prints on two
lines print("He said, \"Python is
great!\"") # Prints quotes inside a
string

about:blank 3/9
10/24/24, 11:16 PM 00000
\n is the escape sequence for a new
line.
\" allows double quotes inside a
string.

4. Slicing:
Slicing is used to extract a portion of a
sequence (like a list, tuple, or string) by
specifying a range of indices. It is done using
the colon (:) operator.
Example:
my_list = [10, 20, 30, 40, 50]
print(my_list[1:4]) # Output: [20,
30, 40] print(my_list[:3]) # Output:
[10, 20, 30] print(my_list[2:]) #
Output: [30, 40, 50]

my_list[1:4] slices the list from


index 1 to 3 (excluding 4).
[:3] gets elements from the start up
to index 2.
[2:] gets elements from index 2 to
the end.

Summary:
Membership Operator checks for
presence (in, not in).
Identity Operator checks if variables
point to the same object (is, is not).
Escape Sequence allows special
characters in strings (e.g., \n for new
line).
Slicing extracts specific parts of
sequences like lists or strings (e.g.,
list[start:end]).

. Explain the following


functions with examples. 1.
lstrip() 2. swapcase() 3.
isspace()
1. lstrip():
The lstrip() function removes any leading
(left-side) whitespace characters from a
string. It does not remove spaces from the
middle or the right side.
Example:
text = " Hello, World! " result =
text.lstrip() print(result) # "Hello,
World! "

Explanation: In the example above,


lstrip() removes the leading spaces
from the left side of the string.

2. swapcase():
The swapcase() function returns a new string
where all the uppercase characters are
converted to lowercase and all lowercase
characters are converted to uppercase.
Example:
text = "Hello, World!" result =
text.swapcase() print(result) #
"hELLO, wORLD!"

Explanation: In the example,


uppercase H becomes h, and lowercase
e becomes E. This swapping is done for
the entire string.

3. isspace():
The isspace() function checks whether all
the characters in a string are whitespace
characters. If all characters are whitespaces
(spaces, tabs, newlines), it returns True;
otherwise, it returns False.
Example:
text1 = " " text2 = "Hello"
print(text1.isspace()) # True
print(text2.isspace()) # False

Explanation: In the first case,


isspace() returns True because
text1 contains only spaces. In the
second case, it returns False because
text2 contains non-space characters.

Summary:
lstrip() removes leading spaces
from a string.
swapcase() swaps the case of all
letters (lowercase to uppercase and
vice versa).
isspace() checks if a string contains
only whitespace characters.

about:blank 4/9
10/24/24, 11:16 PM 00000

What is a Dictionary? What are


the different ways to create a
Dictionary?
A dictionary is a built-in data structure in
Python that stores data as key-value pairs.
Each key must be unique, and it allows quick
lookup of values by their keys. Dictionaries
are unordered, mutable, and can hold
heterogeneous data types.
Example:
my_dict = {"name": "Alice", "age":
25, "city": "New York"}
print(my_dict["name"]) # Output:
Alice

Here, "name", "age", and "city" are


keys, and "Alice", 25, and "New
York" are their respective values.

Different Ways to Create a


Dictionary:
1. Using Curly Braces ( {}): The most
common way to create a dictionary is
by placing key-value pairs inside curly
braces.
Example:

my_dict = {"name": "Alice",


"age": 25} print(my_dict)
2. Using the dict() Constructor: You can
also create a dictionary using the
dict() constructor by passing key-
value pairs as arguments.
Example:

my_dict = dict(name="Alice",
age=25) print(my_dict)
Note that keys do not need
quotes when using this
method.
3. Creating an Empty Dictionary: You can
create an empty dictionary and add
key-value pairs later.
Example:

my_dict = {} my_dict["name"] =
"Alice" my_dict["age"] = 25
print(my_dict)
4. Using dict() with a List of Tuples:
You can create a dictionary from a list
of tuples, where each tuple represents
a key-value pair.
Example:

my_dict = dict([("name",
"Alice"), ("age", 25)])
print(my_dict)
5. Using Dictionary Comprehension:
Dictionary comprehension allows you
to create a dictionary in a compact
way, often from an iterable like a list
or range.
Example:

my_dict = {x: x**2 for x in


range(1, 4)} print(my_dict) #
Output: {1: 1, 2: 4, 3: 9}

Summary:
A dictionary stores key-value pairs,
allowing fast lookups by key.
Ways to create a dictionary include:
Using curly braces {}.
Using the dict() constructor.
Starting with an empty
dictionary and adding pairs.
Using a list of tuples.
Using dictionary
comprehension.

Explain the following methods


of Lists with examples. 1.
reverse() 2. insert() 3. remove()
4. pop()
List Methods in Python:
1. reverse():
The reverse() method reverses the
elements of the list in place. It doesn't return
any value, but it modifies the original list.
Example:
my_list = [1, 2, 3, 4, 5]
my_list.reverse() print(my_list) #
Output: [5, 4, 3, 2, 1]

Explanation: The elements of my_list


are reversed, and the modified list is
printed.

2. insert():
The insert() method inserts an element at
a specified position in the list. It takes two
arguments: the index at which to insert the
element and the element itself.
Example:
my_list = [1, 2, 3, 4]
my_list.insert(2, "new")
print(my_list) # Output: [1, 2,
'new', 3, 4]

Explanation: The element "new" is


inserted at index 2, pushing the rest of
the elements to the right.

3. remove():

about:blank 5/9
10/24/24, 11:16 PM 00000
The remove() method removes the first
occurrence of the specified element from the
list. If the element is not found, it raises a
ValueError.
Example:
my_list = [1, 2, 3, 4, 3]
my_list.remove(3) print(my_list) #
Output: [1, 2, 4, 3]

Explanation: The first occurrence of 3


is removed from the list.

4. pop():
The pop() method removes and returns the
element at the specified index. If no index is
provided, it removes and returns the last
element of the list.
Example:
my_list = [1, 2, 3, 4] element =
my_list.pop(2) print(my_list) #
Output: [1, 2, 4] print(element) #
Output: 3

Explanation: The element at index 2


(which is 3) is removed from my_list
and stored in the variable element.
The modified list and the removed
element are both printed.

Summary:
reverse(): Reverses the list in place.
insert(): Inserts an element at a
specified index.
remove(): Removes the first
occurrence of the specified element.
pop(): Removes and returns the
element at a specified index, or the
last element if no index is provided.

Differentiate between mutable


and immutable objects with
examples.
Difference Between Mutable
and Immutable Objects in
Python:
In Python, objects can be classified as
mutable or immutable based on whether
their values can be changed after creation.

1. Mutable Objects:
Definition: Mutable objects can have
their values changed after they are
created. You can modify the content of
a mutable object in place.
Examples: Lists, dictionaries, sets, and
byte arrays are mutable.
Example of Mutable Object:
my_list = [1, 2, 3] my_list[0] = 10 #
Modifying the first element
print(my_list) # Output: [10, 2, 3]

Explanation: The list my_list is


mutable, so its elements can be
changed. In this case, the value at
index 0 is changed from 1 to 10.

2. Immutable Objects:
Definition: Immutable objects cannot
have their values changed after they
are created. If you try to modify an
immutable object, Python creates a
new object instead.
Examples: Strings, tuples, integers,
floats, and frozensets are immutable.
Example of Immutable Object:
my_tuple = (1, 2, 3) # my_tuple[0] =
10 # This would raise an error since
tuples are immutable new_tuple = (10,
2, 3) # Create a new tuple with the
modified value print(new_tuple) #
Output: (10, 2, 3)

Explanation: Tuples are immutable, so


we cannot modify them directly.
Instead, a new tuple is created if we
want different values.

Key Differences:
Aspect Mutable Immutable
Objects Objects
Can be Cannot be
Modification modified after modified once
creation. created.
Lists, Strings,
Example dictionaries, tuples,
Types sets. integers,
floats.
Modifications New memory
Memory happen in place is allocated
Allocation (same memory for any
address). changes.
Generally Faster for
slower for read-only
Performance frequent
updates due to operations, as
in-place no changes
changes. are allowed.
Strings:
my_string =
my_list[0] = "Hello" +
Example of 10 (modifies list
Mutation in place). "World"
(creates a
new string).

Conclusion:
Mutable objects like lists and
dictionaries can be modified in place
without changing their identity.

about:blank 6/9
10/24/24, 11:16 PM 00000
Immutable objects like strings and
tuples cannot be changed once
created; any "modification" results in a
new object being created.

What is Tuple? How to define


and access the elements of
Tuple? Explain it with a code
A tuple is a collection of ordered, immutable
elements. Once a tuple is created, its values
cannot be changed, unlike lists. Tuples can
hold mixed data types (e.g., integers, strings,
etc.), and they are typically used to store
related data that should not be altered.
How to Define a Tuple:
Tuples are defined using parentheses () with
elements separated by commas. A tuple can
also be created without parentheses by
simply separating the values with commas.
Syntax:
my_tuple = (element1, element2,
element3, ...)
or
my_tuple = element1, element2,
element3, ...
How to Access Elements in a
Tuple:
You can access elements of a tuple by using
indexing and slicing. Indexing starts from 0 for
the first element, and negative indexing can
be used to access elements from the end.
Example of Defining and Accessing
Tuple Elements:
# Defining a tuple my_tuple =
("apple", 42, 3.14, "banana") #
Accessing elements using positive
indexing print(my_tuple[0]) # Output:
apple (first element)
print(my_tuple[2]) # Output: 3.14
(third element) # Accessing elements
using negative indexing
print(my_tuple[-1]) # Output: banana
(last element) # Slicing a tuple
print(my_tuple[1:3]) # Output: (42,
3.14) (from index 1 to 2)
Explanation:
1. Defining a tuple:
my_tuple = ("apple", 42,
3.14, "banana") creates a
tuple with four elements: a
string "apple", an integer 42,
a float 3.14, and another
string "banana".
2. Accessing elements:
my_tuple[0] retrieves the
first element, "apple".
my_tuple[2] retrieves the
third element, 3.14.
my_tuple[-1] uses negative
indexing to retrieve the last
element, "banana".
3. Slicing the tuple:
my_tuple[1:3] retrieves
elements from index 1 to index
2 (not including index 3),
resulting in (42, 3.14).

Key Points:
Tuples are immutable, meaning their
elements cannot be changed after
creation.
Elements can be accessed using
indexing and slicing.
Tuples are often used when you want
to store a collection of items that
should not change.

Explain dictionary methods-


keys, values, items, clear, copy,
update, get. Give an example.
Dictionary Methods in Python
Dictionaries in Python come with several
built-in methods that allow you to perform
various operations. Here are explanations of
some commonly used dictionary methods
along with examples:
1. keys()
The keys() method returns a view object
that displays a list of all the keys in the
dictionary.
Example:
my_dict = {"name": "Alice", "age":
25, "city": "New York"} keys =
my_dict.keys() print(keys) # Output:
dict_keys(['name', 'age', 'city'])
2. values()
The values() method returns a view object
that displays a list of all the values in the
dictionary.
Example:
values = my_dict.values()
print(values) # Output:
dict_values(['Alice', 25, 'New
York'])
3. items()
The items() method returns a view object
that displays a list of tuples, where each
tuple is a key-value pair from the dictionary.
Example:
items = my_dict.items() print(items)
# Output: dict_items([('name',
'Alice'), ('age', 25), ('city', 'New
York')])
4. clear()
about:blank 7/9
10/24/24, 11:16 PM 00000
The clear() method removes all items from
the dictionary, leaving it empty.
Example:
my_dict.clear() print(my_dict) #
Output: {}
5. copy()
The copy() method returns a shallow copy of
the dictionary. This means that a new
dictionary is created with the same key-value
pairs.
Example:
original_dict = {"name": "Alice",
"age": 25} copied_dict =
original_dict.copy()
print(copied_dict) # Output: {'name':
'Alice', 'age': 25}

6. update()
The update() method updates the dictionary
with elements from another dictionary or
from an iterable of key-value pairs. Existing
keys will have their values updated, while
new keys will be added.
Example:
my_dict = {"name": "Alice", "age":
25} my_dict.update({"age": 26,
"city": "New York"}) print(my_dict) #
Output: {'name': 'Alice', 'age': 26,
'city': 'New York'}
7. get()
The get() method returns the value for a
specified key if it exists in the dictionary. If the
key does not exist, it returns None or a
specified default value.
Example:
value = my_dict.get("name")
print(value) # Output: Alice #
Example with a non-existent key
value_not_exist =
my_dict.get("country", "Not Found")
print(value_not_exist) # Output: Not
Found
Summary of Dictionary
Methods:
Method Description Example
Returns a
keys()
view of all my_dict.keys()
keys in the
dictionary.
Returns a
view of all
values() values in my_dict.values()
the
dictionary.
Returns a
items()
view of all my_dict.items()
key-value
pairs.
Removes
clear()
all items my_dict.clear()
from the
dictionary.
Returns a
shallow
copy() copy of the my_dict.copy()
dictionary.
Updates
the
update()
dictionary my_dict.update({"key":
with key- "value"})
value
pairs.
Returns
the value my_dict.get("key",
get() for a
specified default_value)
key.
These methods provide essential
functionalities for managing and interacting
with dictionaries in Python, making them a
powerful tool for handling key-value data.

Make a list of first 10 letters of


the alphabet, then use the
slicing to do the following
operations: 1. Print the first 3
letters of the list 2. Print any 3
letters from the middle 3. Print
the letter from any particular
index to the end of the list
# Create a list of the first 10 letters of the
alphabet alphabet_list = ['A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J']
alphabet_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J']
first_three = alphabet_list[:3] print("First 3
letters:", first_three)
middle_letters = alphabet_list[4:7] # Slicing
from index 4 to 6 print("Middle letters:",
middle_letters)
from_index_to_end = alphabet_list[5:]
print("Letters from index 5 to end:",
from_index_to_end)
Output:-
First 3 letters: ['A', 'B', 'C']
Middle letters: ['E', 'F', 'G']
Letters from index 5 to end: ['F', 'G', 'H', 'I', 'J']
This code demonstrates how to slice a list in
Python to retrieve specific elements based on
your requirements.

A list contains 10 numbers. Write a program


to eliminate duplicates from the list.
Program to Eliminate Duplicates from a List
numbers = [10, 20, 30, 10, 40, 50, 20, 60, 70,
80]
print("Original list:", numbers)
unique_numbers = list(set(numbers))

about:blank 8/9
10/24/24, 11:16 PM 00000
print("List after removing
duplicates:", unique_numbers)

Explanation:
1. Create a List: We first define a list
called numbers that contains 10
numbers, including duplicates.
2. Print Original List: We display the
original list to show its contents
before removing duplicates.
3. Remove Duplicates:
We convert the list to a set
using set(numbers), which
removes any duplicate values
because sets only store unique
items.
We then convert the set back
to a list using list().
4. Print Unique List: Finally, we print the
new list, which contains only unique
numbers.

Sample Output:
Original list: [10, 20, 30, 10, 40,
50, 20, 60, 70, 80] List after
removing duplicates: [40, 10, 50, 20,
70, 80, 30, 60]

Write a program to print odd/even number


from a list.
Program to Print Odd and Even Numbers from
a List
code-
numbers = [10, 15, 22, 33, 40, 55, 68, 79, 84,
91]
even_numbers = [] odd_numbers = []
for num in numbers: if num % 2 == 0:
even_numbers.append(num)
else: odd_numbers.append(num)
print("Even numbers:", even_numbers)
print("Odd numbers:", odd_numbers)
Explanation:
1. Create a List: We start by defining a
list called numbers, which contains a
mix of odd and even integers.
2. Initialize Lists: We create two empty
lists, even_numbers and
odd_numbers, to store the
categorized numbers.
3. Loop Through the List:
We iterate through each
number in the numbers list.
Using the modulus operator %,
we check if a number is even (if
num % 2 == 0) or odd
(otherwise).
We append the number to the
corresponding list based on its
category.
4. Print Results: Finally, we print the
lists of even and odd numbers.
Sample Output:
Even numbers: [10, 22, 40, 68, 84] Odd
numbers: [15, 33, 55, 79, 91]
This program effectively categorizes numbers
from the list into odd and even and prints
them accordingly.

about:blank 9/9

You might also like