0% found this document useful (0 votes)
5 views27 pages

python5thsem2.0 updated

The document provides a comprehensive overview of various Python concepts including slicing, lambda functions, lists vs tuples, Python libraries, random number generation, class creation, and dictionary manipulation. It also discusses the benefits of Python, its interpreted nature, the significance of indentation, and the use of the super() function. Additionally, it covers dictionary comprehension, the range() function, and the immutability of tuples, along with examples and syntax for each topic.

Uploaded by

maitymahadeb530
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)
5 views27 pages

python5thsem2.0 updated

The document provides a comprehensive overview of various Python concepts including slicing, lambda functions, lists vs tuples, Python libraries, random number generation, class creation, and dictionary manipulation. It also discusses the benefits of Python, its interpreted nature, the significance of indentation, and the use of the super() function. Additionally, it covers dictionary comprehension, the range() function, and the immutability of tuples, along with examples and syntax for each topic.

Uploaded by

maitymahadeb530
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/ 27

..

Python ::)
Group A::)
1) What is slicing in Python?
Slicing in Python allows you to access a portion or subset of a
sequence (like a string, list, or tuple) using a range of indices.
It is done using the colon : operator within square brackets.
Syntax: sequence[start:stop:step]
• start: The starting index (inclusive, default is 0).
• stop: The ending index (exclusive).
• step: The interval between indices (default is 1).
For example ::
my_list = [0, 1, 2, 3, 4, 5]
print(my_list[1:5]) # Output: [1, 2, 3, 4]
2) How do you define a lambda function in Python?
A lambda function is an anonymous function defined using
the lambda keyword. It can have multiple arguments but only
a single expression.
Syntax:
python
Copy code
lambda arguments: expression
for example ::
square = lambda x: x**2
print(square(5)) # Output: 25
3) Two differences between List and Tuple:
A list is a data structure in Python that is a mutable, or
changeable, ordered sequence of elements.

List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store
collections of data, the other 3 are Tuple, Set, and Dictionary,
all with different qualities and usage.
Vs :)
For example ::
my_list = [1, 2, 3] # List
my_tuple = (1, 2, 3) # Tuple
4) What are Python libraries? Name a few of them.
Python libraries are pre-written collections of functions and
modules that simplify complex tasks and enhance
functionality. They save time and effort by providing reusable
code for various applications.
Popular Python Libraries:
• NumPy: For numerical computing.
• Pandas: For data manipulation and analysis.
• Matplotlib: For data visualization.
• Scikit-learn: For machine learning.
• TensorFlow: For deep learning.

5) How to generate a random number in Python?


To generate random numbers, Python provides the random
module.
Example:
import random
# Generate a random number between 1 and 10
rand_num = random.randint(1, 10)
print(rand_num)
6) Four differences between mutable and immutable objects
in Python:

Group B::
9) How do you create a class in Python?
A class in Python is created using the class keyword. It acts as
a blueprint for creating objects with attributes (data) and
methods (functions).
Example:
class Person:
def __init__(self, name, age): # Constructor
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age}
years old.")
# Create an object
person1 = Person("Alice", 25)
person1.greet()
releted question --
Object of Python Class
In Python programming an Object is an instance of a Class. A
class is like a blueprint while an instance is a copy of the class
with actual values.
Class
A class is a user-defined blueprint or prototype from which
objects are created. Classes provide a means of bundling data
and functionality together.

10) How can you create and manipulate tuples in Python?


Creating Tuples: Tuples are created using parentheses () or
the tuple() function.
my_tuple = (1, 2, 3)
empty_tuple = ()
single_element_tuple = (5,) # Note the trailing comma
• Iteration:
python
Copy code
for item in my_tuple:
print(item)
Tuples are immutable, so their contents cannot be modified
after creation.
11) Differences between break, continue, and pass
statements:

Long question :
15) Python Code to Check if a Number is an Armstrong
Number
An Armstrong number (or narcissistic number) is a number
that is equal to the sum of its digits each raised to the power
of the number of digits.
Example Explanation (153):
• 153 has three digits: 13+53+33=1+125+27=1531^3 + 5^3
+ 3^3 = 1 + 125 + 27 = 15313+53+33=1+125+27=153, so
it is an Armstrong number.
Code:
16) Answers:
a. Explain how to create a dictionary in Python:
A dictionary is a collection of key-value pairs, where each key
is unique. Dictionaries are created using curly braces {} or the
dict() function.
Example:
# Creating a dictionary
my_dict = {"name": "Alice", "age": 25, "city": "New York"}

# Accessing a value
print(my_dict["name"]) # Output: Alice

b. Explain what is range() function and how it is used in lists:


The range() function generates a sequence of numbers. It is
commonly used in loops and to create lists.
Syntax: range(start, stop, step)
• start: Starting value (default is 0).
• stop: Stopping value (exclusive).
• step: Increment (default is 1).
Example:
# Create a list using range
my_list = list(range(1, 10, 2)) # [1, 3, 5, 7, 9]
print(my_list)
c. What is the output of print(tuple[::2]) if tuple = ('abcd',
786, 2.23, 'john', 70.2)?
Slicing with [::2] selects every second element from the tuple.
Tuple: ('abcd', 786, 2.23, 'john', 70.2)
Output: ('abcd', 2.23, 70.2)

Extra question:

2. What are the benefits of using Python language as a tool


in the present scenario?
The following are the benefits of using Python language:
• Object-Oriented Language
• High-Level Language
• Dynamically Typed language
• Extensive support for Machine Learning Libraries
• Presence of third-party modules
• Open source and community development
• Portable and Interactive
• Portable across Operating systems

3. Is Python a compiled language or an interpreted


language?
Actually, Python is a partially compiled language and partially
interpreted language. The compilation part is done first when
we execute our code and this will generate byte code
internally this byte code gets converted by the Python virtual
machine(p.v.m) according to the underlying
platform(machine+operating system).

4. What does the ‘#’ symbol do in Python?


‘#’ is used to comment on everything that comes after on the
line.
5. What is the difference between a Mutable datatype and
an Immutable data type?
Mutable data types can be edited i.e., they can change at
runtime. Eg – List, Dictionary, etc.
Immutable data types can not be edited i.e., they can not
change at runtime. Eg – String, Tuple, etc.
17. Is Indentation Required in Python?
Yes, indentation is required in Python. A Python interpreter
can be informed that a group of statements belongs to a
specific block of code by using Python indentation.
Indentations make the code easy to read for developers in all
programming languages but in Python, it is very important to
indent the code in a specific order.

18. What is Scope in Python?


The location where we can find a variable and also access it if
required is called the scope of a variable.
• Python Local variable: Local variables are those that are
initialized within a function and are unique to that
function. It cannot be accessed outside of the function.
• Python Global variables: Global variables are the ones
that are defined and declared outside any function and
are not specified to any function.
• Module-level scope: It refers to the global objects of the
current module accessible in the program.
• Outermost scope: It refers to any built-in names that the
program can call. The name referenced is located last
among the objects in this scope.

Pass means performing no operation or in other words, it is a


placeholder in the compound statement, where there should
be a blank left and nothing has to be written there.
25. What is Dictionary Comprehension? Give an Example
Dictionary Comprehension is a syntax construction to ease
the creation of a dictionary based on the existing iterable.
For Example: my_dict = {i:i+7 for i in range(1, 10)}
30. What are Decorators?
Decorators are a very powerful and useful tool in Python as
they are the specific change that we make in Python syntax to
alter functions easily.

40. What is slicing in Python?


Python Slicing is a string operation for extracting a part of the
string, or some part of a list. With this operator, one can
specify where to start the slicing, where to end, and specify
the step. List slicing returns a new list from the existing list.
Syntax: Lst[ Initial : End : IndexJump ]

42. What is PIP?


PIP is an acronym for Python Installer Package which provides
a seamless interface to install various Python modules. It is a
command-line tool that can search for packages over the
internet and install them without any user interaction.
43. What is a zip function?
Python zip() function returns a zip object, which maps a
similar index of multiple containers. It takes an iterable,
converts it into an iterator and aggregates the elements
based on iterables passed. It returns an iterator of tuples.

INTERNAL QUESTIONS :

1. array in python ?
In Python, arrays can be handled using the list data type or
the array module. Assuming you're referring to lists, here
are three commonly used built-in methods for arrays (lists):
1. append()
• Purpose: Adds an item to the end of the list.
• Example:
python
Copy code
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
2. extend()
• Purpose: Adds all elements of an iterable (like another
list) to the end of the list.
• Example:
python
Copy code
my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list) # Output: [1, 2, 3, 4, 5]
3. pop()
• Purpose: Removes and returns an element from the
list. By default, it removes the last element, but you
can specify the index.
• Example
my_list = [1, 2, 3, 4]
removed_item = my_list.pop()
print(my_list) # Output: [1, 2, 3]
print(removed_item) # Output: 4

2. what is range() function with example?


The range() function in Python is used to generate a
sequence of numbers. It's commonly used in loops to iterate
over a sequence of numbers.
Syntax
range(start, stop, step)
start (optional): The number to start from (default is 0).
• stop: The number to stop at (not inclusive).
• step (optional): The difference between each number
in the sequence (default is 1).
Examples
1. Basic Usage
for i in range(5): # Generates numbers from 0 to 4
print(i)
# Output:
#0
#1
#2
#3
#4

2. Using start and stop


for i in range(2, 6): # Generates numbers from 2 to 5
print(i)
# Output:
#2
#3
#4
#5
Using step
for i in range(0, 10, 2): # Generates numbers from 0 to
8, incrementing by 2
print(i)
# Output:
#0
#2
#4
#6
#8

4. Using Negative step


python
for i in range(5, 0, -1): # Generates numbers from 5 to
1, decrementing by 1
print(i)
# Output:
#5
#4
#3
#2
#1
3. how to change values in a dictionary?

Updating a Value
You can update a value by assigning a new value to
an existing key.

Example:
my_dict = {"name": "Alice", "age": 25, "city": "New
York"}
my_dict["age"] = 26 # Change the value of the "age"
key
print(my_dict)
# Output: {'name': 'Alice', 'age': 26, 'city': 'New York'}

Adding a New Key-Value Pair


If the key does not exist, a new key-value pair is added.
Example:
my_dict = {"name": "Alice", "age": 25}
my_dict["profession"] = "Engineer" # Add a new key-
value pair
print(my_dict)
# Output: {'name': 'Alice', 'age': 25, 'profession':
'Engineer'}

Using the update() Method


You can use the update() method to change one or
more values at once.
Example:
my_dict = {"name": "Alice", "age": 25, "city": "New
York"}
my_dict.update({"age": 30, "city": "San Francisco"})
print(my_dict)
# Output: {'name': 'Alice', 'age': 30, 'city': 'San
Francisco'}
Conditional Update (Check Before Updating)
You can check if a key exists before changing its value.
Example:
my_dict = {"name": "Alice", "age": 25}
if "age" in my_dict:
my_dict["age"] = 26
print(my_dict)
# Output: {'name': 'Alice', 'age': 26}

Modifying Nested Values


For nested dictionaries, you can directly access and
update the nested keys.
Example:
my_dict = {"person": {"name": "Alice", "age": 25}}
my_dict["person"]["age"] = 26
print(my_dict)
# Output: {'person': {'name': 'Alice', 'age': 26}}

1.how dictionaries can not have (duplicate) two items with


the same key in python ? with example?
In Python, dictionaries are a collection of key-value pairs
where each key must be unique. If you try to insert a
duplicate key, the dictionary will overwrite the previous
value associated with that key.
This behavior ensures that each key in the dictionary maps
to a single value. Let's look at an example:

Code :
# Create a dictionary
my_dict = {
"a": 1,
"b": 2,
"c": 3
}

# Add a new key-value pair


my_dict["d"] = 4

# Try to add a duplicate key with a different value


my_dict["a"] = 100 # Overwrites the existing value for key
"a"

# Print the dictionary


print(my_dict)
output:

{'a': 100, 'b': 2, 'c': 3, 'd': 4}


Explanation:
• When the key "a" is reassigned to 100, the dictionary
does not keep the previous value (1). Instead, it
replaces it because keys in dictionaries must be unique.
If you need to store multiple values for a single key, you can
use a list or another container as the value:
python
Copy code
# Using a list to store multiple values for a key
multi_value_dict = {
"a": [1, 100],
"b": [2],
"c": [3]
}

print(multi_value_dict)
output:

{'a': [1, 100], 'b': [2], 'c': [3]}

what is use super() function in python ?


The super() function in Python is used to call a method from a
parent (or superclass) in a child (or subclass). It is commonly used in
inheritance to:
1. Access overridden methods in a parent class.
2. Simplify method resolution in multiple inheritance scenarios.
class Parent:
def greet(self):
print("Hello from Parent!")

class Child(Parent):
def greet(self):
super().greet() # Call the parent class method
print("Hello from Child!")

obj = Child()
obj.greet()
output :
Hello from Parent!
Hello from Child!

Program ::
write a program to display the fibbonachi sequence up to n
th term ? write output also?
def fibonacci(n):
# Initialize the first two terms of the Fibonacci sequence
a, b = 0, 1
# Loop through the sequence until the n-th term
for _ in range(n):
print(a, end=" ")
a, b = b, a + b # Update values for the next term
# Get input from the user for the number of terms
n = int(input("Enter the number of terms in the Fibonacci sequence:
"))
fibonacci(n)
output :
0 1 1 2 3 5 8 13 21 34

write a program to simple calculator by using function ?


Python Program (Simple Calculator):
python
Copy code
# Function for addition
def add(x, y):
return x + y

# Function for subtraction


def subtract(x, y):
return x - y

# Function for multiplication


def multiply(x, y):
return x * y
# Function for division
def divide(x, y):
if y != 0:
return x / y
else:
return "Error! Division by zero."

# Function to display the calculator menu


def calculator():
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

# Get user input


choice = input("Enter choice (1/2/3/4): ")

# Check if the choice is valid


if choice in ['1', '2', '3', '4']:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
print(f"{num1} + {num2} = {add(num1, num2)}")
elif choice == '2':
print(f"{num1} - {num2} = {subtract(num1, num2)}")
elif choice == '3':
print(f"{num1} * {num2} = {multiply(num1, num2)}")
elif choice == '4':
print(f"{num1} / {num2} = {divide(num1, num2)}")
else:
print("Invalid Input! Please select a valid option.")

# Call the calculator function


calculator()
output ::
Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 1
Enter first number: 5
Enter second number: 3
5.0 + 3.0 = 8.0
Write a program to count the number of each vowels?
# Function to count the vowels in a string
def count_vowels(input_string):
# Initialize a dictionary to store the counts of each vowel
vowels = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}
# Convert the string to lowercase to handle case insensitivity
input_string = input_string.lower()
# Iterate through the string and count each vowel
for char in input_string:
if char in vowels:
vowels[char] += 1

return vowels

# Input from the user


input_string = input("Enter a string: ")

# Call the function and store the result


vowel_counts = count_vowels(input_string)

# Print the count of each vowel


print("\nVowel counts:")
for vowel, count in vowel_counts.items():
print(f"'{vowel}': {count}")

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy