变量声明:不需要 var、let 或 const。只需命名变量即可。
x = 10 name = "Python"
原始类型:
数据结构:
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}
条件:
if x > 5: print("Greater") elif x == 5: print("Equal") else: print("Lesser")
循环:
for num in [1, 2, 3]: print(num)
i = 0 while i < 5: i += 1
函数定义和返回语法:
def greet(name): return f"Hello, {name}"
Lambda 函数(如 JS 箭头函数):
square = lambda x: x * x
列表推导式(创建列表的有效方法):
squares = [x * x for x in range(10)]
生成器(一一产生值):
def generate_numbers(n): for i in range(n): yield i
尝试/排除块:
try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero")
类定义:
class Animal: def __init__(self, name): self.name = name def speak(self): return f"{self.name} makes a sound"
继承:
class Dog(Animal): def speak(self): return f"{self.name} barks"
阅读和写作:
x = 10 name = "Python"
此摘要应提供有效开始使用 Python 编码的要点。
以上是JS 开发人员的 Python 基础知识的详细内容。更多信息请关注PHP中文网其他相关文章!