Python Basics: Revision Guide
1. What is Python?
Python is a high-level programming language known for its simplicity, readability, and versatility.
It is used in various fields such as web development, data science, automation, artificial intelligence,
and more.
2. List vs Tuple
- Lists are mutable (changeable) and can contain duplicate elements.
- Tuples are immutable (unchangeable) and cannot contain duplicate elements.
Example of List: l = [1, 2, 3]
Example of Tuple: t = (1, 2, 3)
3. How do you define a function in Python?
A function in Python is defined using the `def` keyword.
Example:
def greet(name):
return f"Hello, {name}!"
You can call this function with a value: greet("John")
4. What is the difference between `append()` and `extend()`?
- `append()` adds a single element to the end of the list.
- `extend()` adds each element of an iterable (like a list) to the end of the list.
Example:
l = [1, 2]
l.append(3) # l = [1, 2, 3]
l.extend([4, 5]) # l = [1, 2, 3, 4, 5]
5. What is an iterable?
An iterable is an object that can be looped over (iterated).
Examples include lists, tuples, strings, and dictionaries.
You can use a `for` loop to iterate over an iterable:
for item in [1, 2, 3]:
print(item)
6. What are Python's built-in data types?
Python has several built-in data types:
- `int`: Integer numbers (e.g., 5)
- `float`: Decimal numbers (e.g., 3.14)
- `str`: Strings (e.g., 'Hello')
- `list`: Ordered collection of elements (e.g., [1, 2, 3])
- `tuple`: Immutable ordered collection (e.g., (1, 2, 3))
- `set`: Unordered collection of unique elements (e.g., {1, 2, 3})
- `dict`: Collection of key-value pairs (e.g., {"name": "John", "age": 30})
7. What is the difference between `is` and `==`?
- `==` is used to compare the values of two objects.
- `is` checks if two objects refer to the same memory location (identity).
Example:
a = [1, 2]
b=a
print(a == b) # True
print(a is b) # True (since both refer to the same object)
8. How do you handle exceptions in Python?
In Python, exceptions are handled using `try`, `except` blocks.
Example:
try:
x=1/0
except ZeroDivisionError:
print("Cannot divide by zero!")
This prevents your program from crashing due to errors.
9. How do you create a function with multiple arguments?
You can create a function that accepts multiple arguments by defining them inside the parentheses:
Example:
def greet(name, language):
return f"{name} is learning {language}!"
Calling the function:
greet("Sandesh", "Python")