python代码示例

1、打印"Hello, World!"

print("Hello, World!")

2、基本数学运算

a = 10
b = 5
print('加:', a + b)
print('减:', a - b)
print('乘:', a * b)
print('除:', a / b)

3、条件语句

age = 18
if age >= 18:
    print("成年")
else:
    print("未成年")

4、循环语句

# 使用for循环打印0到9
for i in range(10):
    print(i)

# 使用while循环打印0到9
i = 0
while i < 10:
    print(i)
    i += 1

5、列表推导式

# 使用列表推导式创建一个包含0到9所有偶数的列表
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)

6、函数定义和调用

def greet(name):
    return "Hello, " + name + "!"

print(greet("Alice"))

7、文件读写

# 写入文件
with open('example.txt', 'w') as f:
    f.write('Hello, World!')

# 读取文件
with open('example.txt', 'r') as f:
    content = f.read()
    print(content)

8、异常处理

try:
    result = 10 / 0
except ZeroDivisionError:
    print("不能除以零")

9、类和对象

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
    def greet(self):
        return f"Hello, my name is {
     self.name} and I am {
     self.age} years old."

person = Person("Alice", 30)
print(person.greet())

10、网络请求

import requests

response = requests.get('https://api.github.com')
print(response.json())

以上示例由ChatGPT生成

相关推荐

  1. python代码示例

    2023-12-14 14:12:03       39 阅读
  2. Python编程——常用的Python单行实现功能代码示例

    2023-12-14 14:12:03       15 阅读
  3. Boost.Python中的if_详解及示例代码

    2023-12-14 14:12:03       42 阅读
  4. Python中的time_symmetrize介绍及示例代码

    2023-12-14 14:12:03       36 阅读
  5. Python模块Pandas数据切片 -- loc详解及代码示例

    2023-12-14 14:12:03       8 阅读
  6. Lucene 分词 示例代码

    2023-12-14 14:12:03       20 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-14 14:12:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-14 14:12:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-14 14:12:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-14 14:12:03       18 阅读

热门阅读

  1. Golang 领域驱动设计(DDD)最佳实践

    2023-12-14 14:12:03       37 阅读
  2. 数据结构--栈

    2023-12-14 14:12:03       38 阅读
  3. Cmap数据以及L1000介绍

    2023-12-14 14:12:03       47 阅读
  4. ES6之函数新增的扩展

    2023-12-14 14:12:03       35 阅读
  5. Vue3 中的 Proxy--读懂ES6中的Proxy

    2023-12-14 14:12:03       31 阅读
  6. nextTick详解

    2023-12-14 14:12:03       42 阅读
  7. 【Python 千题 —— 基础篇】今年几岁啦

    2023-12-14 14:12:03       44 阅读
  8. 天线的分类

    2023-12-14 14:12:03       40 阅读