0% found this document useful (0 votes)
37 views

Neha Answers

Uploaded by

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

Neha Answers

Uploaded by

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

NAME: Neha Erusavadla

Phone No: 9014994756


1. What is Python? What are the benefits of using Python?
2. What is an Interpreted language?
3. What are lists and tuples? What is the key difference between the two?
4. What is pass in Python?
5. What is Lambda Functions in Python? Give an example?
6. What is a Negative Index in Python?
7. How the string can be converted to a number?
8. What is the use of self in Python?
9. What is __init__?Give an example code?
10. What is the difference between break, continue and pass in Python?
11. What is slicing in Python?
12. What is List comprehensions and give example?
13. What is the output of the following statement "Hello World"[::-1]?
14. Let list1 = ['s', 'r', 'a', 's'] and list2 = ['a', 'a', 'n', 'h'], what is the output of ["".join([i, j]) for i, j
in zip(list1, list2)]?
15. what is inheritance in python?
16. What is polymorphism?
17. Write a python function that takes an integer as input and returns "Even" if the number is
even, and "odd" if it's odd?
18. Write a python class student with attributes such as name,age,and grade and print the
student's information?
19. Count Consonants in a Given Word?
20. Write a Python function that finds the common elements of two lists?
21. Write a Python function to find the second largest number in a list?
22. Write a Python function to find the missing number in a list of integers from 1 to n?
23. Write a Python function to check if a string can be a palindrome after deleting one
character?
24. Write a Python function to find the most repeated element in a list?
25. Write a Python function to calculate the sum of the series 1 + 1/2 + 1/3 + ... + 1/n?

Answers:
1.Ans)
Python programming language is a general-purpose, interpreted, and high-level language
that mainly offers code readability. It is largely used by professional programmers and
developers across a variety of fields, including Web Development and Machine Learning.
Like all other programming languages that you must have heard or read about, or you might
have used for various reasons,
Benefits of Python :
1) Easy-to-learn and Easy-to-use
2) Improves Productivity
3) Free and open-source:
4) Portable
5) Easy-to-integrate with Other Programming Languages
6) Massive Libraries
2.Ans)
An interpreted language is a type of programming language in which the source code is
executed line by line by an interpreter during runtime, rather than being translated into
machine code beforehand. In contrast to compiled languages, where a compiler translates
the entire source code into machine code before execution, interpreted languages allow for
a more dynamic and flexible approach to code execution. In an interpreted language, the
interpreter reads the source code, interprets each line, and executes the corresponding
instructions. This process happens on-the-fly, making it possible to see the results of code
immediately without the need for a separate compilation step. This approach provides
advantages in terms of ease of development, debugging, and platform independence.
3.Ans)
Lists and Tuples in Python are two classes of Python Data Structures. The list structure is
dynamic, and readily changed whereas the tuple structure is static and cannot be
changed. This means that the tuple is generally faster than the list. Lists are denoted by
square brackets and tuples are denoted with parenthesis.
Difference between List and Tuple:

Feature List Tuple


Mutability Mutable Immutable
Syntax Defined using square brackets [] Defined using parentheses ()
Use Cases Collections of items that may change Collections of fixed items
Performance Slower for read-only operations Faster for read-only
operations
Methods Many methods (e.g., append(), Few methods (e.g., count(),
remove(), sort()) index())
Memory Generally more memory Generally less memory
Consumption consumption consumption
Example my_list = [1, 2, 3] my_tuple = (1, 2, 3)

4. Ans):

pass is a null statement. It is used as a placeholder in situations where a statement is


syntactically required but you do not want any code to execute. This can be useful during
development when you are outlining functions, loops, or classes but have not yet
implemented the functionality.
Example:
1. def my_function():
pass
2. class MyClass:
def method1(self):
pass
def method2(self):
passs

5,Ans)

Lambda functions in Python, also known as anonymous functions, are small, unnamed
functions defined using the lambda keyword. They are primarily used for short, throwaway
functions that are not going to be reused elsewhere in your code.

Example:

def add(x, y):


return x + y
add_lambda = lambda x, y: x + y
print(add(3, 5))
print(add_lambda(3, 5))

Output:
8
8

6.Ans)

Negative indexing in Python is a way to access elements of a sequence (such as a list, tuple,
or string) from the end of the sequence rather than from the beginning. Negative indices
start from -1, which corresponds to the last element of the sequence, -2 to the second-to-
last element, and so on.

7.Ans):
In Python, strings can be converted to numbers using built-in functions like int(), float(), and
complex(). These functions convert a string representation of a number into an actual
number of the appropriate type.

8.Ans):
In Python, self is a conventional name used for the first parameter of methods in a class. It
represents the instance of the class and allows access to the attributes and methods of the
class in object-oriented programming.
9.Ans):

The __init__ method in Python is a special method, also known as a constructor. It is


automatically called when an instance of a class is created. The purpose of __init__ is to
initialize the attributes of the class.
Example:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

person = Person("Neha", 22)


print(person.name)
OUTPUT:

Neha

10.Ans):

Break Continue Pass


Feature
Usage Terminates the Skips the rest of the code Placeholder for future
loop prematurely for the current iteration code, does nothing
Effect Exits the loop Skips the remaining code for Does nothing when
immediately the current iteration and executed, allows code
moves to the next iteration to pass through
Example ```python ```python ```python
for i in range(5): for i in range(5): for i in range(5):
if i == 3: if i == 3: if i == 3:
break continue pass
print(i) print(i) print(i)
``` ``` ```
Output 012 0124 01234

11.Ans)

Slicing in Python refers to extracting a subset of elements from a sequence (such as a list,
tuple, or string) based on specified start, stop, and step indices. It allows you to create a
new sequence containing a portion of the original sequence.

12.Ans):

List comprehensions are a concise way to create lists in Python by applying an expression to
each item in an existing iterable (like a list, tuple, or string) and optionally including a
condition to filter items. They provide a more compact and readable alternative to
traditional loops for generating lists.
Example:

squares = [x**2 for x in range(10)]


print(squares)

Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

13.Ans):

The statement "Hello World"[::-1] reverses the string "Hello World" using slicing with a step
of -1.

Output:

'dlroW olleH'

14.Ans):

The given expression ["".join([i, j]) for i, j in zip(list1, list2)] creates a new list by
concatenating corresponding elements from list1 and list2 using the zip() function and list
comprehension.

 zip(list1, list2) pairs up elements from list1 and list2 element-wise. It creates an iterator of
tuples where each tuple contains corresponding elements from list1 and list2.
 "".join([i, j]) concatenates the elements i and j from each tuple into a single string.

 The list comprehension [...] iterates over each tuple of paired elements generated by zip()
and applies the concatenation operation.

Output:

['sa', 'ra', 'an', 'sh']

15.Ans):

Inheritance in Python is a mechanism that allows a class (subclass or derived class) to inherit
properties and behaviors (attributes and methods) from another class (superclass or base
class). This promotes code reusability and helps create a hierarchical structure among
classes.

Key Concepts

1. Base Class (Superclass): The class whose properties and behaviors are inherited by
another class. It's also referred to as the superclass or parent class.
2. Derived Class (Subclass): The class that inherits properties and behaviors from
another class. It's also referred to as the subclass or child class.
3. Syntax:

python
Copy code
class BaseClass:
# Base class definition

class DerivedClass(BaseClass):
# Derived class definition

4. Inheriting Attributes and Methods: The subclass automatically gains access to all
attributes and methods of the superclass.
5. Overriding Methods: The subclass can override methods of the superclass by
providing its own implementation.
6. Adding New Features: The subclass can add new attributes and methods or modify
existing ones.

16.Ans):
Polymorphism, in the context of object-oriented programming, refers to the ability of
different objects to respond to the same message or method call in different ways. It allows
objects of different classes to be treated as objects of a common superclass, providing
flexibility and extensibility in code design.

Key Concepts

1. Method Overriding: Subclasses can provide their own implementation of methods


defined in the superclass, allowing objects of different classes to respond differently
to the same method call.
2. Dynamic Binding: The decision of which method implementation to execute is made
at runtime based on the actual type of the object, rather than the declared type of
the variable.

Types of Polymorphism

1. Compile-time Polymorphism: Also known as static polymorphism, it refers to


method overloading and operator overloading, where the decision on which method
or operator to call is made at compile time based on the arguments passed.
2. Runtime Polymorphism: Also known as dynamic polymorphism, it refers to method
overriding and virtual functions, where the decision on which method
implementation to execute is made at runtime based on the actual type of the
object.

17.Ans) :
def check_even_odd(number):
if number % 2 == 0:
return "Even”
else:

return "Odd"
print(check_even_odd(5))
print(check_even_odd(10))

OUTPUT:

Odd
Even

18.Ans):

class Student:

def __init__(self, name, age, grade):

self.name = name

self.age = age

self.grade = grade

def print_info(self)
print(f"Name: {self.name}")

print(f"Age: {self.age}")

print(f"Grade: {self.grade}")

student1 = Student("Naha", 22 , "A")

student1.print_info()

OUTPUT:

Name: Naha
Age: 22
Grade: A

19.Ans):
def count_consonants(word):

consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'

count = 0

for char in word:

if char in consonants:

count += 1

return count

word = "Hello"

print("Number of consonants in '{}' is: {}".format(word, count_consonants(word)))

OUTPUT:

Number of consonants in 'Hello' is: 3

20.Ans):

def find_common_elements(list1, list2):

common_elements = []

for item in list1:

if item in list2:

common_elements.append(item)

return common_elements

list1 = [1, 2, 3, 4, 5]

list2 = [4, 5, 6, 7, 8]

print("Common elements:", find_common_elements(list1, list2))

OUTPUT:

Common elements: [4, 5]

21.Ans):
def second_largest_number(numbers):

sorted_numbers = sorted(numbers, reverse=True)

return sorted_numbers[1] if len(sorted_numbers) > 1 else None

numbers = [10, 5, 20, 8, 15]

print("Second largest number:", second_largest_number(numbers))

OUTPUT:

Second largest number: 15

22.Ans):

def find_missing_number(numbers, n):

expected_sum = n * (n + 1) // 2

actual_sum = sum(numbers)

return expected_sum - actual_sum

numbers = [1, 2, 4, 5, 6]

n=6

print("Missing number:", find_missing_number(numbers, n))

OUTPUT:

Missing number: 3

23.Ans):

def is_palindrome_after_deletion(s):

def is_palindrome(string):

return string == string[::-1]

if is_palindrome(s):

return True
for i in range(len(s)):

modified_string = s[:i] + s[i + 1:]

if is_palindrome(modified_string):

return True

return False

string = "radar"

print("Can be palindrome after deletion:", is_palindrome_after_deletion(string))

OUTPUT:

Can be palindrome after deletion: True

24.Ans):

def most_repeated_element(lst):

# Create a dictionary to store the count of each element

count_dict = {}

for element in lst:

if element in count_dict:

count_dict[element] += 1

else:

count_dict[element] = 1

max_count = max(count_dict.values())

most_repeated_elements = [key for key, value in count_dict.items() if value ==


max_count]
return most_repeated_elements

lst = [1, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5]

print("Most repeated element(s):", most_repeated_element(lst))

OUTPUT:

Most repeated element(s): [4]

25.Ans):

def sum_of_series(n):

total = 0

for i in range(1, n + 1):

total += 1 / i

return total

# Test the function

n=5

print("Sum of the series:", sum_of_series(n))

OUTPUT:

Sum of the series: 2.283333333333333

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