Python基础语法讲解及案例 Python基础语法概述Python是一种解释型、高级编程语言以其简洁易读的语法著称。以下是核心语法元素变量与数据类型变量无需声明类型直接赋值即可name Alice age 25 height 1.68 is_student True常见数据类型整数int、浮点数float、字符串str、布尔值bool、列表list、元组tuple、字典dict运算符算术运算符,-,*,/,//整除,%取模,**幂比较运算符,!,,,,逻辑运算符and,or,not控制结构条件语句if age 18: print(成年人) elif age 13: print(青少年) else: print(儿童)循环结构for循环for i in range(5): # 输出0到4 print(i)while循环count 0 while count 3: print(count) count 1函数定义def greet(name): return fHello, {name}! print(greet(Bob)) # 输出Hello, Bob!参数可设置默认值def power(base, exponent2): return base ** exponent数据结构操作列表Listfruits [apple, banana, cherry] fruits.append(orange) # 添加元素 print(fruits[1]) # 访问索引1banana字典Dictionaryperson {name: Alice, age: 25} print(person[name]) # 输出Alice person[city] New York # 添加键值对文件操作# 写入文件 with open(example.txt, w) as file: file.write(Hello, World!) # 读取文件 with open(example.txt, r) as file: content file.read() print(content)案例计算斐波那契数列def fibonacci(n): a, b 0, 1 for _ in range(n): print(a, end ) a, b b, a b fibonacci(10) # 输出前10项0 1 1 2 3 5 8 13 21 34案例单词统计text hello world hello python words text.split() word_count {} for word in words: word_count[word] word_count.get(word, 0) 1 print(word_count) # 输出{hello: 2, world: 1, python: 1}异常处理try: result 10 / 0 except ZeroDivisionError: print(不能除以零) finally: print(执行结束)以下是10个基础代码案例涵盖常见编程任务使用Python语言实现。变量交换a 5 b 10 a, b b, a print(fa{a}, b{b}) # 输出: a10, b5斐波那契数列def fibonacci(n): a, b 0, 1 for _ in range(n): print(a, end ) a, b b, a b fibonacci(10) # 输出: 0 1 1 2 3 5 8 13 21 34判断素数def is_prime(num): if num 2: return False for i in range(2, int(num**0.5) 1): if num % i 0: return False return True print(is_prime(17)) # 输出: True列表去重my_list [1, 2, 2, 3, 4, 4, 5] unique_list list(set(my_list)) print(unique_list) # 输出: [1, 2, 3, 4, 5]字符串反转text Hello, World! reversed_text text[::-1] print(reversed_text) # 输出: !dlroW ,olleH文件读写# 写入文件 with open(example.txt, w) as file: file.write(Hello, File!) # 读取文件 with open(example.txt, r) as file: content file.read() print(content) # 输出: Hello, File!计算阶乘def factorial(n): return 1 if n 0 else n * factorial(n - 1) print(factorial(5)) # 输出: 120冒泡排序def bubble_sort(arr): n len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] arr[j1]: arr[j], arr[j1] arr[j1], arr[j] data [64, 34, 25, 12, 22] bubble_sort(data) print(data) # 输出: [12, 22, 25, 34, 64]计算圆的面积import math def circle_area(radius): return math.pi * radius ** 2 print(circle_area(5)) # 输出: 78.53981633974483生成随机数import random random_number random.randint(1, 100) print(f随机数: {random_number}) # 输出: 1到100之间的随机整数