#### 常用语句

# 常用语句

## 条件语句

### if.....else....

while True:
x = int(input("请输入数字:50"))
if x >50:
print("你输入的数大于50")
else:
print("你输入的值小于50")

### if....elif....else...

while True:
x = int(input("请输入数字:"))
if x >90:
print("你输入的数大于90")
elif x >80:
print("你输入的值大于80")
elif x > 70:
print("你输入的值大于70")

## continue

### 条件满足调到while循环语句

i =10
while i >0:
i -= 1
if i==5:
continue
print(i)

9
8
7
6
4
3
2
1
0

## break

### 条件满足跳出循环

i =10
while True:
i -= 1
if i==5:
break
print(i)

9
8
7
6

## return

### 函数返回，可带返回值，返回值可以是元祖，无需加括号，可不带

def func2(b):
return b **2

print(func2(3))

9

## 循环语句

### while...

while True:
x = input("请输入数字:")
if len(x)>0 and x.isdigit():  #判断是否空也可以用bool如下:if not len(x) and x.isdigit():
x1 = int(x)
# if x.isdecimal():
#     x1 = int(x)
# else:
#     print("你输入的不是数字")
if x1 >90:
print("你输入的数大于90")
elif x1 >80:
print("你输入的值大于80")
elif x1 > 70:
print("你输入的值大于70")
elif x1 == 0:
break

else:
print("你输入为空,或者输入的不是数字")

### while...else...

- while条件不满足就执行else

age_old_boy = 40
count = 0
while count < 3:
guess_age = int(input("请输入年龄>>> "))
if guess_age == age_old_boy:
print("猜对了")
break
elif guess_age > age_old_boy:
print("猜大了！")
else:
print("猜小了！")
count += 1
else:
print("次数到了，滚蛋！")
不执行while 就执行else

### for....in...:

x1 = [‘我‘,1,{‘姓名‘:"林明均","年龄":10},(1,"年级")]
for item in x1:
print(item)

1
{‘姓名‘: ‘林明均‘, ‘年龄‘: 10}
(1, ‘年级‘)

### for ...else......

- 循环执行for里面的循环，完了执行else,如果不想执行else,就在for里面用break,就跳过else

"""
从文件里面获取用户密码，并比较后，发回比较结果
:param dic:
:return:
"""
with open("info.txt",mode="r",encoding="utf-8") as f:
for line in f:
flag = 1
break
else:
flag = 0
return dic

## 三目运算符/三元表达式

### 为真时的结果 if 判断条件  else  为假时的结果

# x1 = 20
# result = x1+2 if x1 > 10 else x1**2
# print(result)

# def fn(n):
#     return n+1 if n%2 ==1 else n
# print(fn(3))

## lamda表达式，只是定义了函数，必须调用才执行

func = lambda x: x*x
print(func(3))

9

fib=lambda n,x=0,y=1:x if n>5 else y
print([fib(i)  for i in range(10)])

[1, 1, 1, 1, 1, 1, 0, 0, 0, 0]

## 推导式

### 列表推导式

print([i**2  for i in range(10)])

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

print([i**2  for i in range(10) if i%2 is 0])

[0, 4, 16, 36, 64]

def squared(x):
return x*x
multiples = [squared(i) for i in range(30) if i % 3 is 0]

print(multiples)

[0, 9, 36, 81, 144, 225, 324, 441, 576, 729]

### 字典推导式

mcase = {‘a‘: 10, ‘b‘: 34}
mcase_frequency = {mcase[k]: k for k in mcase}
print(mcase_frequency)

{10: ‘a‘, 34: ‘b‘}

dic = {"k"+str(i):i for i in range(5)}
print(dic)

{‘k0‘: 0, ‘k1‘: 1, ‘k2‘: 2, ‘k3‘: 3, ‘k4‘: 4}

### 集合推导式

squared = {x**2 for x in [1, 2, 3]}
print(squared)

{1, 4, 9}

*XMind - Trial Version*