|
| 1 | + |
| 2 | +## 1. Walrus Operator (:=) |
| 3 | +Introduced in Python 3.8, the walrus operator allows assignment expressions, enabling assignment and return of a value in a single expression. This is particularly useful in loops and comprehensions. |
| 4 | +```python |
| 5 | +# Not Allowed |
| 6 | +print(is_alive=False) |
| 7 | +# Allowed |
| 8 | +print(is_active:=True) |
| 9 | +``` |
| 10 | + |
| 11 | +## 2. Matrix Multiplication Operator (@) |
| 12 | +Introduced in Python 3.5, the '@' operator is used for matrix multiplication, which is especially useful in numerical computing and machine learning applications. |
| 13 | +```python |
| 14 | +import numpy as np |
| 15 | + |
| 16 | +a = np.array([[1, 2], [3, 4]]) |
| 17 | +b = np.array([[5, 6], [7, 8]]) |
| 18 | + |
| 19 | +# Matrix multiplication |
| 20 | +c = a @ b |
| 21 | +print(c) |
| 22 | +``` |
| 23 | + |
| 24 | +## 3. New String Formatting (f-strings) |
| 25 | +Introduced in Python 3.6, f-strings provide a way to embed expressions inside string literals, using curly braces '{}'. |
| 26 | +```python |
| 27 | +name = "Abhinay" |
| 28 | +age = 21 |
| 29 | +print(f"My name is {name} and I am {age} years old.") |
| 30 | +``` |
| 31 | +## 4. Enhanced Unpacking |
| 32 | +Python 3.5 introduced extended unpacking with the '*' operator to allow more flexible unpacking operations. |
| 33 | +```python |
| 34 | +a, *b, c = [1, 2, 3, 4, 5] |
| 35 | +print(a) # 1 |
| 36 | +print(b) # [2, 3, 4] |
| 37 | +print(c) # 5 |
| 38 | +``` |
| 39 | +## 5. Positional-Only Parameters |
| 40 | +Introduced in Python 3.8, positional-only parameters are defined by adding a '/' in the function signature. These parameters can only be passed positionally, not as keyword arguments. |
| 41 | +```python |
| 42 | +def greet(name, /, greeting="Hello"): |
| 43 | + return f"{greeting}, {name}!" |
| 44 | + |
| 45 | +print(greet("Abhinay")) # Works |
| 46 | +# print(greet(name="Abhinay")) # Raises TypeError |
| 47 | +``` |
| 48 | + |
| 49 | +## 6. Keyword-Only Parameters |
| 50 | +Defined by adding '*' in the function signature, parameters following '*' can only be passed as keyword arguments. |
| 51 | +```python |
| 52 | +def greet(*, name, greeting="Hello"): |
| 53 | + return f"{greeting}, {name}!" |
| 54 | + |
| 55 | +print(greet(name="Abhinay")) # Works |
| 56 | +# print(greet("Abhinay")) # Raises TypeError |
| 57 | +``` |
| 58 | +These new operators and enhancements make Python more expressive and capable of handling various programming paradigms more efficiently. |
0 commit comments