Python 常用命令及示例 - 入门指南

本文介绍了 Python 中 10 个常用命令和示例,涵盖打印输出、用户输入、长度获取、循环、条件判断、函数定义、模块导入、文件操作等基本功能,帮助初学者快速入门 Python 编程。

1. print():打印输出信息

print("Hello, World!")

2. input():接收用户输入

name = input("请输入您的名字:")
print("Hello, " + name)

3. len():返回对象的长度

str = "Hello, World!"
print(len(str))

4. range():生成一个指定范围的整数序列

for i in range(1, 5):
    print(i)

5. if 语句:条件判断语句

num = 10
if num > 0:
    print("正数")
elif num < 0:
    print("负数")
else:
    print("零")

6. for 循环:遍历列表或其他可迭代对象

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

7. while 循环:根据条件重复执行代码块

num = 1
while num <= 5:
    print(num)
    num += 1

8. def 语句:定义函数

def greet(name):
    print("Hello, " + name + "!")
    
greet("Alice")

9. import 语句:导入模块

import math

print(math.sqrt(16))

10. with 语句:管理文件的打开和关闭

with open("file.txt", "r") as file:
    content = file.read()
    print(content)

原文地址: https://www.cveoy.top/t/topic/pVZj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录