> 时尚打扮 > python程序实例

python程序实例

python程序实例

Python是一种广泛使用的编程语言,它有着丰富的库和框架,可以用于各种不同的应用,从简单的任务到复杂的数据分析。下面是一些Python程序实例,涵盖了不同的领域和用途:

1. 打印心形图案

```pythondef print_heart(): print(\'\\n\'.join([\'\'.join([\'*\' if ((x*0.05)2 + (y*0.1)2 - 1)3 - (x*0.05)2*(y*0.1)3 <= 0 else \' \' for x in range(-30, 30)]) for y in range(15, -15, -1)]))print_heart()```

2. 生成随机密码

```pythonimport randomimport stringdef generate_password(length=12): characters = string.ascii_letters + string.digits + string.punctuation password = \'\'.join(random.choice(characters) for i in range(length)) return passwordprint(\"你的随机密码是:\", generate_password())```

3. 文件批量重命名

```pythonimport osdef batch_rename_files(directory, extension, new_extension): for filename in os.listdir(directory): if filename.endswith(extension): new_filename = filename.replace(extension, new_extension) old_path = os.path.join(directory, filename) new_path = os.path.join(directory, new_filename) os.rename(old_path, new_path)# 使用示例batch_rename_files(\'/path/to/directory\', \'.jpg\', \'.png\')```

4. 随机抽奖程序

```pythonimport randomdef draw_winners(participants, num_winners): if num_winners > len(participants): raise ValueError(\"获奖人数不能超过参与者总数\") winners = random.sample(participants, num_winners) return winnersparticipants = [\"Alice\", \"Bob\", \"Charlie\", \"David\", \"Eva\", \"Frank\", \"Grace\", \"Hannah\", \"Ivy\", \"Jack\"]num_winners = 3print(\"获奖者名单:\", draw_winners(participants, num_winners))```

5. 计算1到100的偶数和奇数

```python# 输出1到100的偶数start = 1while start <= 100: print(start * 2) start += 1# 输出1到100的奇数start = 1while start <= 100: if start % 2 == 1: print(start) start += 1```

6. 判断闰年

```pythondef is_leap_year(year): return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)year = 2024if is_leap_year(year): print(f\"{year} 是闰年\")else: print(f\"{year} 不是闰年\")```

7. 使用`geopandas`计算质心

```pythonimport geopandas as gpd# 读取.shp文件original_shp = gpd.read_file(\'path_to_your_file.shp\')# 计算每个县的质心original_shp[\'centroid\'] = original_shp[\'geometry\'].apply(lambda geom: (geom.x.mean(), geom.y.mean()))# 将质心信息写入文本文件with open(\'point.txt\', \'a\') as file: for index, row in original_shp.iterrows(): file.write(f\"{row[\'NAME_1\']}({row[\'centroid\'].x}, {row[\'centroid\'].y})\\n\")```

8. 合并两个字典

```pythondef merge_dicts(dict1, dict2): return {dict1, dict2}dict1 = {\"name\": \"Joy\", \"age\": 25}dict2 = {\"city\": \"New York\"}dict3 = merge_dicts(dict1, dict2)print(dict3)```

9. 使用`selenium`抓取网页数据

其他小伙伴的相似问题:

如何使用Python计算几何图形的面积?

Python中如何实现多线程并行计算?

如何利用Python分析社交媒体数据?