Q: What are Python's key features?
A:
- Easy to read and write
- Interpreted and dynamically typed
- Extensive standard libraries
- Supports object-oriented and functional programming
- Open-source and community-driven
- Portable across platforms
----------------------------------------
Q: Difference between `is` and `==` in Python?
A:
- `==` checks for **value equality** (same data)
- `is` checks for **object identity** (same memory location)
Example:
```python
a = [1, 2]
b = a
c = [1, 2]
print(a == c) # True (same content)
print(a is c) # False (different objects)
print(a is b) # True (same object)
```
----------------------------------------
Q: What is the use of `self` in a class?
A:
- `self` represents the instance of the class.
- It's used to access variables and methods associated with the current object.
```python
class Dog:
def __init__(self, name):
[Link] = name
```
----------------------------------------
Q: What are Python decorators? Give an example.
A:
- Decorators allow modification of a function’s behavior without changing its code.
```python
def decorator_func(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@decorator_func
def say_hello():
print("Hello!")
say_hello()
```
----------------------------------------
Q: Check if a number is palindrome.
A:
```python
def is_palindrome(n):
return str(n) == str(n)[::-1]
print(is_palindrome(121)) # True
print(is_palindrome(123)) # False
```
----------------------------------------
Q: Find second largest number in a list.
A:
```python
def second_largest(nums):
first = second = float('-inf')
for n in nums:
if n > first:
second = first
first = n
elif first > n > second:
second = n
return second
print(second_largest([10, 20, 4, 45, 99])) # 45
```
----------------------------------------
Q: Check if two strings are anagrams.
A:
```python
from collections import Counter
def is_anagram(s1, s2):
return Counter(s1) == Counter(s2)
print(is_anagram("listen", "silent")) # True
print(is_anagram("hello", "world")) # False
```
----------------------------------------
Q: Print Fibonacci series up to n terms.
A:
```python
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
fibonacci(7) # 0 1 1 2 3 5 8
```
----------------------------------------
Q: Remove vowels from a string.
A:
```python
def remove_vowels(s):
return ''.join([ch for ch in s if [Link]() not in 'aeiou'])
print(remove_vowels("Hello World")) # Hll Wrld
```
----------------------------------------
Q: First non-repeating character in a string.
A:
```python
from collections import Counter
def first_unique(s):
freq = Counter(s)
for ch in s:
if freq[ch] == 1:
return ch
return None
print(first_unique("aabbcdde")) # c
```
----------------------------------------