目录
和C++有些不同,故作记录。
一、运算符
-
算数运算符
print("1 + 1 = ", 1 + 1) # 加 +
print("2 - 1 = ", 2 - 1) # 减 -
print("3 * 2 = ", 3 * 2) # 乘 *
print("11 / 2 = ", 11 / 2) # 除 /
print("11 // 2 = ", 11 // 2) # 整除 //
print("9 % 2 = ", 9 % 2) # 取余 %
print("3 ** 2 = ", 3 ** 2) # 指数 **
运行结果:
-
赋值运算符
# 赋值运算符
num = 1 + 2 * 3
# 复合赋值运算符
num += 1
print("num+=1:", num)
num -= 1
print("num-=1:", num)
num *= 4
print("num*=4:", num)
num /= 2
print("num/=2:", num)
num = 3
num %= 2
print("num%=2:", num)
num **= 2
print("num**=2:", num)
num = 9
num //= 2
print("num//=2:", num)
运行结果:
二、判断语句
-
if 判断句
if 条件:
执行语句//前面缩进4个空格,表示归属于if
-
if-else 判断句
if 条件:
执行语句1
执行语句2
...
else:
执行语句1
执行语句2
...
print("enter your age:")
age = int(input())
if age >= 18:
print("not free")
else:
print("free")
-
if-elif-else 组合句
if 条件1:
执行语句1
执行语句2
...
elif 条件2:
执行语句1
执行语句2
...
else:
执行语句1
执行语句2
...
height = int(input("enter your height:")) #多条件判断下,条件之间互斥 if height < 120: print("shorter than 120cm,free") elif height >= 120 and height < 140: print("half ticket") else: print("not free,buy tickets plz")
简洁写法:
- 条件是依次输入的
if int(input("enter your height:")) < 120:
print("shorter than 120cm,free")
elif int(input("enter the date:")) == 1:
print("free day")
else:
print("not free,buy tickets plz")
注意点:
- .elif可以写多个
- 判断是互斥且有序的,上一个满足后面的就不会判断了
- 可以在条件判断中,直接写input语句,节省代码量
-
判断语句的嵌套
if 条件1:
执行语句1.1
if 条件2:
执行语句2.1
else:
执行语句2.2
else:
执行语句1.2
age = int(input("enter your age:"))
if age > 18 and age < 30:
print("age correct")
work_year = int(input("enter your work year:"))
level = int(input("enter your level:"))
if work_year > 2:
print("qualified!")
elif level > 3:
print("qualified!")
else:
print("unqualified")
else:
print("unqualified")
三、循环语句
-
while循环
while 条件:
操作
i = 1
sum = 0;
while i < 101:
sum += i
i += 1
print(sum)//sum=5050
eg.猜数字
import random
num = random.randint(1, 10)
guess_num = int(input("enter the number:"))
count = 0
flag = True
while flag:
if guess_num == num:
print("correct")
flag = False
else:
if guess_num > num:
print("bigger")
elif guess_num < num:
print("smaller")
guess_num = int(input("enter the number:"))
count += 1
print(f"{count} time")
嵌套循环
while 条件1
操作1
while 条件2
操作2
注意:
- 基于空格缩进决定层次关系
- 注意条件设置避免出现死循环
i = 1
while i < 10:
print(f"date {i}")
j = 1
while j < 4:
print(f"melon top {j}")
j += 1
i += 1
eg.九九乘法表
i = 1
while i <= 9:
j = 1
while j <= i:
print(f" {j} * {i} = {j*i}\t", end='')
j += 1
print()
i += 1
运行结果:
-
for循环
for 临时变量 in 待处理数据集:
循环满足条件时执行的代码
注意:
- 无法定义循环条件,只能被动取出数据处理
- 循环内的语句需要有空格缩进
range语句
- 语法1:
range(num1)
获取一个从0开始,到num结束的数字序列(不含num本身)
如range(5)取得的数据是:[0,1,2,3,4]
- 语法2:
range(num1,num2)
获得一个从num1开始,到num2结束的数字序列(不含num2本身)
如range(5,10)取得的数据是[5,6,7,8,9]
- 语法3:
range(num1,num2,step)
获得一个从num1开始,到num2结束的数字序列(不含num2本身)
数字之间的步长,以step为准(step默认为1)
如range(5,10,2)取得的数据是:[5,7,9]
可以用range快速确定for循环的次数:
for x in range(3):
print("killing voice")
运行结果:
eg.计算1~100的偶数
count = 0
for x in range(1, 101):
if x % 2 == 0:
count += 1
print(count) # count = 50
临时变量作用域
临时变量在编程规范上作用域只限定在for循环内部。(并非强制限定)
嵌套循环
i = 0
for i in range(1, 11):
print(f"day {i}")
for j in range(1,3):
print(f"melon top {j}")
print(f"day{i+1},not in")
注意空格决定了缩进关系。
for和while可以相互嵌套使用。
eg.九九乘法表
for i in range(1, 10):
for j in range(1,i):
print(f"{j}*{i}={i*j}\t", end='')
print("\t")
运行结果:
-
break和continue
continue
- 中断本次循环,直接进入下一次循环
- 可以用于for和while
- 只用于它所在的循环临时中断
for i in range(1, 5):
print("test 1")
for j in range(1,3):
print("test 2")
continue
print("test 3")# this code is unreachable
print("test 4")
运行结果:
break
- 直接结束循环
- 可以用于for和while
- 只用于它所在的循环
for i in range(1, 5):
print("test 1")
for j in range(1,101):
print("test 2")
break
print("test 3")
print("test 4")
运行结果:
四、函数
-
函数定义
def 函数名(传入参数1,传入参数2...):
函数体
return 返回值
注:可以不用传入参数和返回值
# 定义函数
def add(num1,num2):
result = num1 + num2
print(f"{num1}+{num2}={num1+num2}")
return result
#调用函数
sum = add(3, 5)
# 3+5=8
形式参数(形参):num1,num2.表示函数声明将要使用2个参数
实际参数(实参):3,5.表示函数执行时真正使用的参数值
返回值:函数在执行完成后,返回给调用者的结果。函数体在return后就结束了,所以写在return后的代码不会执行。
None:
- 函数返回值
无返回值函数,返回的内容是None,返回的内容类型是NoneType类型字面量。
- 可用于if判断
def check_age(age):
if age > 18:
return "success"
else:
return None
result = check_age(16)
if not result:
# 进入if表示result是None值,也就是False
print("not allowed to enter")
else:
print("plz come in")
运行结果:
- 用于声明无初始内容的变量上
name = None
-
嵌套调用
def func_a():
print("test 1")
def func_b():
print("a")
func_a();
print("b")
func_b()
函数A中执行到调用函数B的语句,会将函数B全部执行完成后,继续执行函数A 的剩余内容。
-
变量的作用域
局部变量:定义在函数体内部的变量,即只在函数体内部生效。其作用是在函数体内部临时保存数据,当函数调用完成后,则销毁局部变量。
全局变量:在函数体内外都能生效的变量。在函数外定义的变量。
global关键字:将函数内定义的变量声明为全局变量。
# 在函数内修改全局变量
num = 200
def test_a():
print("test a:", num)
def test_b():
global num # 设置内部定义的变量为全局变量
num = 500
print("test b:", num)
test_a()
test_b()
print(num)
运行结果:
五、综合案例
eg.银行取钱
money = 5000000
name = None
name = input("enter your name:")
def check_balance():
print(f"{name},The balance is {money}")
def deposit(num):
global money
money += num
print(f"Deposit {num}")
check_balance()
def withdraw(num):
global money
money -= num
print(f"Withdraw {num}")
check_balance()
def display():
print("---main menu---")
print("1.check balance")
print("2.deposit money")
print("3.withdraw money")
print("4.exit")
return input("enter your choice:")
while True:
choice = int(display())
if choice == 1:
check_balance()
continue
elif choice == 2:
deposit(int(input("enter your deposit amount:")))
continue
elif choice == 3:
withdraw(int(input("enter your withdraw amount:")))
continue
elif choice == 4:
print("exit the service")
break
运行结果: