首页 > 编程语言 >Python编程入门常用代码

Python编程入门常用代码

时间:2023-06-02 15:07:54浏览次数:33  
标签:入门 Python age 编程 numbers file print Hello name


这些代码片段涵盖了Python编程的一些常用方面,包括日期和时间操作、列表排序、字符串格式化、文件读写以及包和模块的使用。继续探索和学习这些概念,以及其他相关的Python特性,将使你的编程能力不断提升。


1.输出语句:


print("Hello, World!")  # 打印字符串


2.变量和赋值:


x = 5  # 整数
y = 3.14  # 浮点数
name = "Alice"  # 字符串
is_true = True  # 布尔值


3.输入语句:


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

4.条件语句:


x = 10
if x > 5:
print("x大于5")
elif x == 5:
print("x等于5")
else:
print("x小于5")


5.循环语句:

for循环:


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

while循环:


i = 0
while i < 5:
print(i)
i += 1


6.列表:


fruits = ["apple", "banana", "orange"]
print(fruits[0])  # 输出第一个元素
fruits.append("grape")  # 添加元素
fruits.remove("banana")  # 移除元素


7.字典:


person = {"name": "Alice", "age": 25, "city": "New York"}
print(person["name"])  # 输出键为"name"的值
person["age"] = 26  # 修改键为"age"的值
del person["city"]  # 删除键为"city"的键值对

8.函数:


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


greet("Alice")  # 调用函数并传递参数



9.数字运算:


x = 5
y = 3
print(x + y)  # 加法
print(x - y)  # 减法
print(x * y)  # 乘法
print(x / y)  # 除法
print(x % y)  # 取模运算
print(x ** y)  # 幂运算


10.字符串操作:


text = "Hello, World!"
print(len(text))  # 字符串长度
print(text.upper())  # 转换为大写
print(text.lower())  # 转换为小写
print(text.replace("Hello", "Hi"))  # 替换字符串
print(text.split(","))  # 拆分字符串为列表


11.文件操作:


# 写入文件
file = open("myfile.txt", "w")
file.write("Hello, World!")
file.close()

# 读取文件
file = open("myfile.txt", "r")
content = file.read()
print(content)
file.close()

12.异常处理:


try:
x = 5 / 0
except ZeroDivisionError:
print("除数不能为零")


13.导入模块:


import math

print(math.sqrt(16))  # 平方根
print(math.pi)  # 圆周率

14.列表推导式:


numbers = [1, 2, 3, 4, 5]
squared_numbers = [x**2 for x in numbers]
print(squared_numbers)

15.面向对象编程:


class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def greet(self):
print("Hello, my name is " + self.name)

person = Person("Alice", 25)
person.greet()

16.日期和时间操作:


import datetime

current_time = datetime.datetime.now()
print(current_time)
print(current_time.year)
print(current_time.month)
print(current_time.day)


17.列表排序:


numbers = [3, 1, 4, 2, 5]
numbers.sort()  # 升序排序
print(numbers)

numbers.sort(reverse=True)  # 降序排序
print(numbers)


18.字符串格式化:


name = "Alice"
age = 25
print("My name is %s and I'm %d years old." % (name, age))

# 使用f-string(Python 3.6+)
print(f"My name is {name} and I'm {age} years old.")

19.文件读写:


# 写入文件
with open("myfile.txt", "w") as file:
file.write("Hello, World!")

# 读取文件
with open("myfile.txt", "r") as file:
content = file.read()
print(content)

20.包和模块:

创建模块(例如,my_module.py):


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

在另一个脚本中使用模块:


import my_module

my_module.greet("Alice")

Python编程入门常用代码_字符串

标签:入门,Python,age,编程,numbers,file,print,Hello,name
From: https://blog.51cto.com/u_16077447/6402516

相关文章

  • Python编程入门常用代码
    这些代码片段涵盖了Python编程的一些常用方面,包括日期和时间操作、列表排序、字符串格式化、文件读写以及包和模块的使用。继续探索和学习这些概念,以及其他相关的Python特性,将使你的编程能力不断提升。1.输出语句:print("Hello,World!")#打印字符串2.变量和赋值:x=5#整数y......
  • Python编程入门常用代码
    这些代码片段涵盖了Python编程的一些常用方面,包括日期和时间操作、列表排序、字符串格式化、文件读写以及包和模块的使用。继续探索和学习这些概念,以及其他相关的Python特性,将使你的编程能力不断提升。1.输出语句:print("Hello,World!")#打印字符串2.变量和赋值:x=5#整......
  • 如何4天快速入门性能测试
    在现代软件开发中,性能测试是至关重要的步骤之一。它可以帮助我们确定系统的负载极限和稳定性,以确保应用程序和网站在高流量期间仍然能够正常运行。但是,性能测试通常需要大量的时间和资源,对于初学者而言可能会感到有些棘手。以下是4天快速入门性能测试的步骤,帮助您开始追踪应用程序......
  • Python function argument All In One
    PythonfunctionargumentAllInOnePython函数参数https://docs.python.org/3/library/typing.htmlhttps://docs.python.org/3/library/typing.html#typing.ParamSpec.argsfunctionargumenttypesdefaultargumentskeywordargumentspositionalargumentsarbitrary......
  • # yyds干货盘点 # #经验分享# #网络爬虫# #数据分析# #Python# #每日打卡# #进阶学习#
    大家好,我是皮皮。一、前言前几天在Python群【洋洋】问了一个Python基础的问题,这里拿出来给大家分享下。二、实现过程这里【kim】给出了代码,如下所示:的确满足了粉丝的需求。很多人应该和我一样,想到的是zip吧。zip完全可以,可是他说要for,所以上面演示的是for循环。那么如果通过zip函数......
  • Adafruit CircuitPython NeoPixel All In One
    AdafruitCircuitPythonNeoPixelAllInOneRaspberryPi&Python&WS2812BRGBLEDStripneopixel#installforcurrentuser$pip3installadafruit-circuitpython-neopixel#installsystem-wide$sudopip3installadafruit-circuitpython-neopixe......
  • ubuntu16 python2 安装M2Crypto报错
    正文pip2installM2Crypto#报错:#unabletoexecute'swig':Nosuchfileordirectory#error:command'swig'failedwithexitstatus1#解决:sudoaptinstallswig#继续pip2installM2Crypto,又报错:#src/SWIG/_m2crypto_wrap.c:149:21:fat......
  • 《深度剖析CPython解释器》16. Python函数机制的深度解析(第三部分): 闭包的底层实现
    https://www.cnblogs.com/traditional/p/13580694.html楔子上一篇我们看了函数是如何调用的,这一次我们看一下函数中局部变量的访问、以及闭包相关的知识。函数中局部变量的访问我们说过函数的参数和函数内部定义的变量都属于局部变量,所以它也一样是通过静态的方式进行访问。......
  • python把指定文件夹内所有文件和子文件夹大写全部改为小写
    来源:http://www.shanhubei.com/archives/2622.html接手老项目,里面的文档大小心不同意,而在linux中对大小写又敏感。所以那就统一下把所有文件和文件夹全部转为小写#!/usr/bin/pythonimportsys,ostotal=0defrename(directory):globaltotalifdirectory!=dir......
  • python安装pyaudio
    python安装pyaudio1.环境python>=3.72.安装直接用pip安装会报错error:command'C:\\ProgramFiles(x86)\\MicrosoftVisualStudio14.0\\VC\\BIN\\x86_amd64\\cl.exe'failedwithexitcode2---到https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyaudio......