猜数字-while循环
import random
num = random.randint(1, 10)
while True:
x = int(input("输入:"))
if x > num:
print("大了")
elif x < num:
print("小了")
else:
print("猜对了")
break
打印九九乘法表-while循环
i = 1
while i <= 9:
j = 1
while j <= i:
# end = ' ' 不换行
print(f"{j} * {i} = {i * j}\t", end='')
j += 1
i += 1
print() # 换行
for 循环
for i in '123456':
print(i, end='\t')
- range(num): [0,num)
- range(num1,num2): [num1,num2)
- range(num1,num2,step): [num1,num2) 步长为step
# 作用域,理论上不可以,实际上能运行。不规范
# 规范写法(for 循环外为i赋初值,初值不重要):i =0
for i in range(5):
print(i)
print(i) # 4
i = 1 # 赋初值
for i in range(5):
print(i)
print(i)
for 循环打印九九乘法表
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j} * {i} = {j * i}\t", end='')
print()
continue 跳过,进入下次循环
break 跳出循环
函数
'''
def 函数名(传参):
函数体
return 返回值
变量 = 函数(参数)
'''
def add(x, y):
"""
函数文档:多行注释+回车
:param x: 形参
:param y: 形参
:return:
"""
result = x + y
return result
x = int(input("x="))
y = int(input("y="))
sum = add(x, y)
print(f"x + y = {sum}")
1. 无return默认返回None,if语句中None等同False
2. 函数内部定义局部变量,外部定义全局变量
3. 关键字global,在函数内部将局部变量定义为全局变量,写法: global 局部变量
ATM实例
money = 50000
name = None
def query(show_header):
if show_header: # 标志位,去标头
print("--------------查询余额--------------")
print(f"{name},你好,余额为{money}元")
def save(num):
global money # 此处将money设为全局变量
money += num
print("--------------存款--------------")
print(f"{name},成功存款{num}元")
query(False) # 标志位置为False,不打印查询余额头信息
def get_money(num):
global money
if num <= money:
money -= num
print("--------------取款--------------")
print(f"{name},成功取款{num}元")
query(False) # 标志位置为False,不打印查询余额头信息
else:
print("余额不足")
def main():
print("--------------主菜单--------------")
print(f"{name}, 您好,欢迎使用ATM,")
print("查询余额\t[输入1]")
print("存款\t\t[输入2]")
print("取款\t\t[输入3]")
print("退出\t\t[输入4]")
return input("请选择操作:")
name = input("请输入姓名:")
while True:
n = int(main()) # input输入接收字符串,int()强制转型
if n == 1:
query(True)
continue
elif n == 2:
num = input("请输入存款金额:")
save(int(num))
continue
elif n == 3:
num = input("请输入取款金额:")
get_money(int(num))
continue
else:
print("程序退出")
break # 跳出循环