0
点赞
收藏
分享

微信扫一扫

Python-入门

古月无语 2023-08-02 阅读 53

介绍

  • Python (python.org)
  • Learn X in Y minutes (learnxinyminutes.com)
  • Regex in python (jaywcjlove.github.io)

hello word

>>> print("Hello, World!")
Hello, World!

Python 中著名的“Hello World”程序

变量

age = 18      # 年龄是 int 类型
name = "John" # name 现在是 str 类型
print(name)

Python 不能在没有赋值的情况下声明变量

数据类型

str

Text

intfloatcomplex

Numeric

listtuplerange

Sequence

dict

Mapping

setfrozenset

Set

bool

Boolean

bytesbytearraymemoryview

Binary

Slicing String

>>> msg = "Hello, World!"
>>> print(msg[2:5])
llo

查看: Strings

Lists

mylist = []
mylist.append(1)
mylist.append(2)
for item in mylist:
    print(item) # 打印输出 1,2

查看: Lists

If Else

num = 200
if num > 0:
    print("num is greater than 0")
else:
    print("num is not greater than 0")

查看: 流程控制

循环

for item in range(6):
    if item == 3: break
    print(item)
else:
    print("Finally finished!")

查看: Loops

函数

>>> def my_function():
...     print("来自函数的你好")
...
>>> my_function()
来自函数的你好

查看: Functions

文件处理

with open("myfile.txt", "r", encoding='utf8') as file:
    for line in file:
        print(line)

查看: 文件处理

算术

result = 10 + 30 # => 40
result = 40 - 10 # => 30
result = 50 * 5  # => 250
result = 16 / 4  # => 4.0 (Float Division)
result = 16 // 4 # => 4 (Integer Division)
result = 25 % 2  # => 1
result = 5 ** 3  # => 125

/ 表示 x 和 y 的商,// 表示 x 和 y 的底商,另见 StackOverflow

加等于

counter = 0

counter += 10 # => 10

counter = 0

counter = counter + 10 # => 10

message = "Part 1."# => Part 1.Part 2.

message += "Part 2."

f-字符串(Python 3.6+)

>>> website = 'Quick Reference'
>>> f"Hello, {website}"
"Hello, Quick Reference"
>>> num = 10
>>> f'{num} + 10 = {num + 10}'
'10 + 10 = 20'

查看: [Python F-Strings](#f-字符串(Python 3.6+))


举报

相关推荐

学python-入门介绍

Python-字典

python-报错

Python-类

Python-继承

python-元组

Python-列表

Python-序列

0 条评论