Python 快速入门——基础语法

python 的语法逻辑完全靠缩进,建议缩进 4 个空格。 如果是顶级代码,那么必须顶格书写,哪怕只有一个空格也会有语法错误。

下面示例中,满足 if 条件要输出两行内容,这两行内容必须都缩进,而且具有相同的缩进级别。

python 复制代码
if 3 > 0:
    print('OK')
    print('yes')

print 函数

python 复制代码
print('hello world!')
print('hello', 'world!')  # 逗号自动添加默认的分隔符:空格 hello world!
print('hello' + 'world!')  # 加号表示字符拼接 helloworld!
print('hello', 'world', sep='***')  # 单词间用***分隔 hello***world
print('#' * 50)  # *号表示重复 50 遍
print('how are you?', end='')  # 默认 print 会打印回车,end=''表示不要回车

input

python 复制代码
number = input("请输入数字:")  # input 用于获取键盘输入
print(number)
print(type(number))  # input 获得的数据是字符型

print(number + 10)  # 报错,不能把字符和数字做运算
print(int(number) + 10)  # int 可将字符串 10 转换成数字 10
print(number + str(10))  # str 将 10 转换为字符串后实现字符串拼接

python 中,单双引号没有区别,表示一样的含义

字符串

python 复制代码
py_str = 'python'
len(py_str)  # 取长度
py_str[0]  # 第一个字符
'python'[0]
py_str[-1]  # ⭐⭐最后一个字符
# py_str[6]  # 错误,下标超出范围
py_str[2:4]  # 切片,起始下标包含,结束下标不包含
py_str[2:]  # 从下标为 2 的字符取到结尾
py_str[:2]  # 从开头取到下标是 2 之前的字符
py_str[:]  # 取全部
py_str[::2]  # 步长值为 2,默认是 1
py_str[1::2]  # 取出 yhn
py_str[::-1]  # 步长为负,表示自右向左取

py_str + ' is good'  # 简单的拼接到一起
py_str * 3  # 把字符串重复 3 遍

't' in py_str  # True
'th' in py_str  # True
'to' in py_str  # False
'to' not in py_str  # True
相关推荐
AlanAshley6 分钟前
无 SIM 卡也能打 110?手机紧急呼叫能力的软硬件技术探究
开发语言·智能手机·php
modelmd11 分钟前
Go 切片、映射常见使用场景
开发语言·后端·golang
陈随易28 分钟前
一个网吧网管,做了个网页,卖了 5000 万
前端·后端·程序员
dialect_8 小时前
KMP算法
开发语言·c++·算法
jktantan9 小时前
Vue keep-alive 切标签后滚动位置回顶?因为 onDeactivated 里读到的 scrollTop 是 0
前端·javascript·vue.js
总要学点什么9 小时前
第89篇:三维特效-螺旋圆效果——让螺旋臂卷起一圈圈外扩的涟漪
开发语言·javascript·ecmascript·webgl·cesium·空间分析·1024程序员节
前端精髓9 小时前
结构化输出with_structured_output(抽卡)
python·langchain
2601_9628857210 小时前
quotes 字段全解:涨跌幅、振幅、换手率的口径与单位
java·前端·spring
excel10 小时前
encodeURI 和 encodeURIComponent 有什么区别?
前端
前端精髓10 小时前
调用openrouter的免费API模型
java·前端·javascript