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
相关推荐
莹雨潇潇9 分钟前
Docker 快速入门(Ubuntu版)
java·前端·docker·容器
陈苏同学11 分钟前
4. 将pycharm本地项目同步到(Linux)服务器上——深度学习·科研实践·从0到1
linux·服务器·ide·人工智能·python·深度学习·pycharm
唐家小妹15 分钟前
介绍一款开源的 Modern GUI PySide6 / PyQt6的使用
python·pyqt
Jiaberrr17 分钟前
Element UI教程:如何将Radio单选框的圆框改为方框
前端·javascript·vue.js·ui·elementui
XKSYA(小巢校长)1 小时前
NatGo我的世界联机篇
开发语言·php
羊小猪~~1 小时前
深度学习项目----用LSTM模型预测股价(包含LSTM网络简介,代码数据均可下载)
pytorch·python·rnn·深度学习·机器学习·数据分析·lstm
Cons.W1 小时前
Codeforces Round 975 (Div. 1) C. Tree Pruning
c语言·开发语言·剪枝
憧憬成为原神糕手1 小时前
c++_ 多态
开发语言·c++
VBA63371 小时前
VBA信息获取与处理第三个专题第三节:工作薄在空闲后自动关闭
开发语言
Tiffany_Ho1 小时前
【TypeScript】知识点梳理(三)
前端·typescript