Variable Declaration: No need for var, let, or const. Just name the variable.
x = 10 name = "Python"
Primitive Types:
Data Structures:
numbers = [1, 2, 3] numbers.append(4)
point = (10, 20)
person = {"name": "Alice", "age": 30} person["name"] # Accessing value
unique_numbers = {1, 2, 3, 2}
Conditionals:
if x > 5: print("Greater") elif x == 5: print("Equal") else: print("Lesser")
Loops:
for num in [1, 2, 3]: print(num)
i = 0 while i < 5: i += 1
Function definition and return syntax:
def greet(name): return f"Hello, {name}"
Lambda Functions (like JS arrow functions):
square = lambda x: x * x
List Comprehensions (efficient way to create lists):
squares = [x * x for x in range(10)]
Generators (yielding values one by one):
def generate_numbers(n): for i in range(n): yield i
Try/Except Blocks:
try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero")
Class Definition:
class Animal: def __init__(self, name): self.name = name def speak(self): return f"{self.name} makes a sound"
Inheritance:
class Dog(Animal): def speak(self): return f"{self.name} barks"
Reading and Writing:
x = 10 name = "Python"
This summary should provide the essentials to begin coding in Python efficiently.
The above is the detailed content of Python Essentials for JS Developers. For more information, please follow other related articles on the PHP Chinese website!