Python Tutorial (Easy & Modern Features)
Python is known for its readability and simplicity. It's great for web development, data science, automation, and more.
1. "Hello, World!"
Explanation:
#: Lines starting with#are comments, used for explaining code.print(): A built-in Python function to display output to the console."Hello, Python World!": A string literal (text enclosed in quotes).
2. F-Strings (Formatted String Literals) (Python 3.6+):
A fantastic way to embed variables directly into strings. Much cleaner than older methods.
Explanation:
f"...": TheforFbefore the quotes indicates it's an f-string.{variable_name}: Place variable names or expressions inside curly braces{}to insert their values.{pi:.2f}:.2fspecifies formatting as a floating-point number (f) with 2 decimal places.
3. Type Hinting (Python 3.5+):
Specifies the expected types for variables, function arguments, and return values. It doesn't enforce types strictly at runtime but improves code readability and helps static analysis tools catch errors early.
Explanation:
a: int: Specifies that variableais expected to be an integer.-> int: Specifies that theaddfunction is expected to return an integer.-> None: Specifies that thegreetfunction doesn't explicitly return anything (it implicitly returnsNone).
4. Structural Pattern Matching (Python 3.10+):
A powerful way to match values against patterns, similar to switch statements but much more flexible.
Explanation:
match point:: Starts the pattern matching block.case (0, 0):: Matches ifpointis exactly the tuple(0, 0).case (x, 0):: Matches ifpointis a tuple with two elements, where the second is0. The first element is assigned to the variablex.case (x, y):: Matches ifpointis a tuple with two elements, assigning them toxandy.case _:: The wildcard case, matches if none of the previous patterns match.
5. Walrus Operator (:=) (Python 3.8+):
Allows assigning values to variables within an expression. It can sometimes make code cleaner, especially when you need to re-use the result of an operation immediately.
Explanation:
(n := len(data)): Assigns the result oflen(data)tonand returns that result, which is then used in theifcondition.
Running Python Code:
Save the code in a .py file (e.g., my_script.py). Open your terminal or command prompt, navigate to the directory where you saved it, and run: