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
相关推荐
柯南二号11 分钟前
【Java后端】MyBatis-Plus 原理解析
java·开发语言·mybatis
ankleless13 分钟前
C语言(12)——进阶函数
前端·html
一条上岸小咸鱼16 分钟前
Kotlin 基本数据类型(四):String
android·前端·kotlin
0wioiw029 分钟前
Python基础(Flask①)
后端·python·flask
我是哈哈hh31 分钟前
【Node.js】ECMAScript标准 以及 npm安装
开发语言·前端·javascript·node.js
飞翔的佩奇1 小时前
【完整源码+数据集+部署教程】食品分类与实例分割系统源码和数据集:改进yolo11-AggregatedAttention
python·yolo·计算机视觉·数据集·yolo11·食品分类与实例分割
张元清1 小时前
电商 Feeds 流缓存策略:Temu vs 拼多多的技术选择
前端·javascript·面试
一枚前端小能手1 小时前
🎨 CSS布局从入门到放弃?Grid让你重新爱上布局
前端·css
晴空雨1 小时前
React 合成事件原理:从事件委托到 React 17 的重大改进
前端·react.js
魏嗣宗1 小时前
Node.js 网络编程全解析:从 Socket 到 HTTP,再到流式协议
前端·全栈