题目:https://blog.csdn.net/qq_33254766/article/details/133895035
print("Hello, World!")
x = 10
print(x)
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(a + b)
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
lst = [1, 2, 3]
lst.append(4) # 添加
lst.remove(2) # 删除
print(lst)
for item in lst:
print(item)
i = 1
while i <= 10:
print(i)
i += 1
def add(a, b):
return a + b
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
evens = [i for i in range(2, 21, 2)]
print(evens)
dictionary = {"a": 1, "b": 2}
dictionary["c"] = 3 # 增
del dictionary["a"] # 删
print(dictionary.get("b")) # 查
dictionary["b"] = 4 # 改
print(dictionary)
len()
函数计算字符串的长度。s = "Python"
print(len(s))
print(s[1:4])
my_set = {1, 2, 3}
my_set.add(4) # 添加
my_set.remove(2) # 删除
print(my_set)
import
导入一个模块,并使用其中的函数。(这个例子假设我们导入了math
模块)import math
print(math.sqrt(16))
# my_module.py
def func1():
pass
def func2():
pass
f = lambda x: x * 2
print(f(5))
filter()
和lambda
输出一个列表中的所有偶数。nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)
map()
和lambda
将列表中的每个数字乘以2。doubled = list(map(lambda x: x * 2, nums))
print(doubled)
with open("file.txt", "w") as f:
f.write("Hello, World!")
with open("file.txt", "r") as f:
content = f.read()
print(content)
def
关键字定义一个接受不定数量参数的函数。def print_args(*args):
for arg in args:
print(arg)
print_args(1, 2, 3, 4)
data = {
"names": ["Alice", "Bob", "Charlie"],
"ages": (25, 30, 35),
"scores": [85, 90, 95]
}
print(data)
enumerate()
遍历列表的索引和元素。for index, value in enumerate(["a", "b", "c"]):
print(index, value)
zip()
合并两个列表。names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 95]
combined = list(zip(names, scores))
print(combined)
sort()
方法和sorted()
函数排序一个列表。lst = [3, 1, 4, 1, 5, 9, 2, 6, 5]
lst.sort()
print(lst)
lst2 = [3, 1, 4, 1, 5, 9, 2, 6, 5]
sorted_lst2 = sorted(lst2)
print(sorted_lst2)
intersection()
方法找到两个集合的交集。set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(set1.intersection(set2))
get()
方法获取字典中的值,如果键不存在则返回默认值。print(dictionary.get("z", "Default Value"))
append()
和extend()
方法添加元素。lst = [1, 2, 3]
lst.append(4) # [1, 2, 3, 4]
lst.extend([5, 6]) # [1, 2, 3, 4, 5, 6]
print(lst)
split()
方法分割字符串。s = "Hello, World!"
print(s.split(", "))
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")