Python基础
- 编译型与解释型、变量、注释、简单数据类型、用户交互、流程控制语句
-
Python语言的分类:
编译型:编译型是将代码一次性转换为二进制文件,然后再执行
- 优点:执行效率高
- 缺点:开发效率低,不易跨平台
解释型:一边解释一边执行
- 优点:开发效率高,易跨平台
- 缺点:执行效率低
-
变量
变量的作用:代指程序中一些复杂的或者被重复使用的内容,可以使代码变动简洁美观
变量的命名规则:
- 只能由数字字母下划线组成
- 不能由数字开头
- 不能包含Python的关键字
- 变量名称要具有一定含义
- 不建议使用中文
- 不要过长
- 推荐:驼峰体、下划线格式
注意:
- 变量与变量之间不能相互指向,变量只能指向数据,变量名在内存中是唯一的
-
常量
- 用来指代不变的量,默认变量名都为大写的变量为常量。
-
注释
注释的作用:用来说明代码,便于他人理解
注释的使用:
- 井号 用来注释单行
- '''/""" 用来注释多行
-
数据类型
作用:Python通过特定的数据类型,将数据分成不同的类,做对应类型的相应操作
简单的数据类型:
-
int(整型):如1,2,3.......,可以用来做运算
-
str(字符串类型):用引号引起来的在Python中被认为字符串类型,可以做拼接和多次输出等操作。
- '/"用于单行字符串,'''/"""用于多行字符串,有换行的那种
>>> str1 = 'abc' >>> str2 = "123" >>> print(str1+str2) abc123 >>> str3 = ''' ... hello ... world ... python ... ''' >>> print(str3) hello world python >>> print(str3*3) hello world python hello world python hello world python -
bool(布尔):true、false,用于判断
-
-
判断数据类型
type()
>>> type(str3) <class 'str'> -
用户交互
input("提示内容"),input输入的数据格式默认为字符串
user = input("name:") print(user,type(user)) 结果: alex <class 'str'> -
流程控制语句if
if的五种结构:
-
if 条件:#不符合条件就不会执行if后的代码
代码
num = input("please input number:") if int(num) > 10: print("bingo!") 结果: please input number:25 bingo! please input number:6-
if 条件:#符合条件走代码1否则走代码2
代码1
else:
代码2
num = input("please input number:") if int(num) > 10: print("bingo!") else: print("go die!") 结果: please input number:3 go die! please input number:45 bingo!-
if 条件1: #多条件的类型,满足哪个条件就走哪个代码,都不满足就不执行
代码1
elif 条件2:
代码2
...................
num = int(input("please input number:")) if num < 5: print("pig") elif num < 10: print("dog") elif num < 15: print("cat") 结果: please input number:4 pig please input number:8 dog please input number:13 cat please input number:45-
if 条件1:
代码1
elif 条件2:
代码2
..................
else:
代码n
num = int(input("please input number:")) if num < 5: print("pig") elif num < 10: print("dog") elif num < 15: print("cat") else: print("rabbit") 结果: please input number:4 pig please input number:6 dog please input number:11 cat please input number:67 rabbit-
嵌套的if:
if 条件1:
If 条件2:
...................
user_sign = "qazq" sign = input("验证码:") if sign == user_sign: username = input("Name:") password = input("Password:") if username == "lucy" and password == "123456": print("welcome login!") else: print("用户名或者密码错误!") else: print("验证码错误!") 结果: 验证码:uuuu 验证码错误! 验证码:qazq Name:lucy Password:789 用户名或者密码错误! 验证码:qazq Name:lucy Password:123456 welcome login! -
浙公网安备 33010602011771号