score = int(input("请输入期末成绩"))
if score >= 90:
print("优秀!")
elif score >= 75:
print("良好")
elif score >= 60:
print("及格")
else:
print("不及格")
score = int(input("请输入期末成绩"))
print( "不及格" if int(score)<60 else "及格")
i = 1
num = 0
while i <= 100:
num += i
i += 1
print(num)
#遍历字符串中的所有字符
for i in "alvin":
print(i , end=" ")
print()
#=================#遍历字典=============================
# 遍历所有的key
dic = {1:"张三",2:"小明",3:"小海"}
for x in dic:
print(x,end=" ")
print()
#遍历所有Key的第二种
for x in dic.keys():
print(x,end=" ")
print()
#遍历所有的value
for x in dic.values():
print(x,end=" ")
print()
#遍历所有的键值对
for x in dic.items():
print(x,end=" ")
for i in range(10):
print(i,end=" ")
print()
for i in range (5,13):
print(i,end=" ")
print()
for i in range (1,20,2):
print(i,end=" ")
for i in range(1,10):
for j in range(1,i + 1):
print("{0} * {1} = {2}".format(i,j,(i * j)),end=" ")
print()
names = ("小明","小刚","小海")
ages = (19,18,20)
for name,age in zip(names,ages):
print("{0} {1}".format(name,age))
#列表推导式
a = [i for i in range(1,15)]
print(a)
#字典推导式
st = "alvin is great"
dic = {i : "a" for i in st}#字符个数
print(dic)
#集合推导式
ar = {x for x in range(1,100) if x % 5 == 0}
print(ar)
def function(max):
if max <= 100 and max >= 0:
return max +function(int(max) - 1)
else:
return 0
print(function(100))
字典、列表、集合、自定义的对象等
数字、字符串、元组、function 等
*param(一个星号),将多个参数收集到一个“元组”对象中。
**param(两个星号),将多个参数收集到一个“字典”对象中。
def function(*a):
print(a)
function(1,2,3,4,5,6,7)
def functionS(**a):
print(a)
functionS(one = 'alvin',two = 'bob')
f = lambda a,b,c:a+b+c
print(f(5,3,9))
结果是: 17
功能:将字符串 str当成有效的表达式计算结果。
语法: eval(source[, globals[, locals]]) -> value
参数:
source:一个 Python 表达式或函数 compile()返回的代码对象
globals:可选。必项是 dictionary
locals:可选。任意映射对象
str = "print('hello world')"
eval(str)
score = "print(10 + 80)"
eval(score)
def function():
def func():
def local():
print("hello world")
local()
func()
function()
nonlocal 用来声明外层的局部变量。
global 用来声明全局变量。
def function():
def local():
global a #全局变量
a = 100
local()
function()
print(a)
def function():
a = 20
def local():
nonlocal a #外部函数变量
a = 100
local()
print(a)
function()
Python在查找“名称”时,是按照LEGB规则查找的:
Local-->Enclosed-->Global-->Built in
Local 指的就是函数或者类的方法内部
Enclosed 指的是嵌套函数(一个函数包裹另一个函数,闭包)
Global 指的是模块中的全局变量
Built in 指的是 Python为自己保留的特殊名称。