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
相关推荐
G***E31613 小时前
前端在移动端中的React Native Web
前端·react native·react.js
Trouville0113 小时前
Pycharm软件初始化设置,字体和shell路径如何设置到最舒服
ide·python·pycharm
云烟飘渺o13 小时前
JPA 的脏检查:一次“没 save() 却更新了”的排查记录
前端
Neptune113 小时前
深入浅出:理解js的‘万物皆对象’与原型链
前端·javascript
高-老师13 小时前
WRF模式与Python融合技术在多领域中的应用及精美绘图
人工智能·python·wrf模式
王霸天13 小时前
扒一扒 Vue3 大屏适配插件 vfit 的源码:原来这么简单?
前端
王霸天13 小时前
拒绝 rem 计算!Vue3 大屏适配,我是这样做的 (vfit 使用体验)
前端
小白学大数据13 小时前
基于Splash的搜狗图片动态页面渲染爬取实战指南
开发语言·爬虫·python
xlq2232213 小时前
22.多态(下)
开发语言·c++·算法
xinyu_Jina13 小时前
ikTok Watermark Remover:客户端指纹、行为建模与自动化逆向工程
前端·人工智能·程序人生·信息可视化