1.变量
box_width = 3
box_height = 4
s = box_width * box_height
print(s)
2.if-else
age = 18
if age > 16:
print('可以进入!')
else:
print('年级太小,不能进入!')
3.if-elif-else
score = 80
if score >= 90:
print('A')
elif score >= 80:
print('B')
elif score >= 70:
print('C')
elif score >= 60:
print('D')
else:
print('E')
4.for循环
for i in range(1,5):
print(i)
for i in range(5):
print(i)
for i in range(1,15,2):
print(i)
5.while循环
n = 1
while n < 10:
print(n)
n = n + 1
else:
print("循环结束!")
6.for循环嵌套
for i in range(1,10):
for j in range(1,i + 1):
print(f'{i} * {j} = {i * j}',end=' ')
print()
7.while循环嵌套
n = 1
while n <= 9:
m = 1
while m <= n:
print(f'{n}*{m}={n*m}',end=' ')
m += 1
n += 1
print()
8.for-while嵌套
n = 1
while(n <= 9):
for m in range(1,n + 1):
print(f'{n}*{m}={n*m}',end=' ')
n = n + 1
print()
9.循环控制-break
while True:
s = input('输入:(0)退出:')
if s == '0':
break
print('你输入的是:',s)
10.循环控制-continue
for s in [1, 2, 3, 4, 5, 6]:
if s == 3:
continue
print(s)
11.实战—猜数字
import random
m = random.randint(1,100)
total = 5
count = 0
while True:
n = int(input('输入1-100之间的整数:'))
if n < m:
print('猜小了!')
elif n > m:
print('猜大了!')
else:
print('恭喜你,猜对了!')
break
count = count + 1
if count >= total:
print('很遗憾,游戏结束!')
break
12.字符串
print('''pyt
sdfs
hon''')
print("""python
java
js
c++""")
print('这里\n\n\n有一个换行')
13.字符串切片
s = '床前明月光'
print(s[1:4])
print(s[0:5:2])
print(s[2:])
print(s[:3])
print(s[:])
14.字符串格式化输出
user_1 = '韩梅梅'
user_2 = '李雷'
print('{}对{}说:"hello"'.format(user_1,user_2))
print(f'{user_1}对{user_2}说:"hello!"')
15.字符串的索引
s = '床前明月光'
print(s[0])
print(s[1])
print(s[2])
print(s[3])
print(s[4])
print(s[-1])
print(s[-2])
print(s[-3])
print(s[-4])
print(s[-5])
16.列表
my_list = [1, 2, 'a', 1.3]
print(my_list[2])
my_list.append(111)
print(my_list)
my_list.insert(1, 'python')
print(my_list)
my_list.extend('s')
print(my_list)
my_list.extend('python')
print(my_list)
my_list.extend([22, 33, 44])
print(my_list)
my_list2 = [1, 2, 'a', 1.3]
my_list2.pop()
print(my_list2)
my_list2.remove(1)
print(my_list2)
my_list3 = [1, 2, 'a', 1.3]
my_list3[2] = 33
print(my_list3)
17.元组
my_list = (1, 2, 'a', 1.3)
print(my_list[2])
print(my_list[-1])
print(my_list[1:4])
18.字典
user = {
'name': 'Tom',
'age': 18,
'sex': 'male'
}
print(user)
print(user['age'])
user['age'] = 28
print(user)
user['fav'] = '打篮球'
print(user)
19.函数
n = 1
sum = 0
while n <= 100:
sum += n
n += 1
print(sum)
def qiu_he(n, m):
sum = 0
while n <= m:
sum += n
n += 1
return sum
print(qiu_he(1,100))
20.文件操作
f = open('liyuhuan.txt', encoding='utf-8')
s = f.read()
print(s)
f.close()
f = open("liyuhuan.txt", mode='w', encoding='utf-8')
f.write('djskhc\n')
f.write('jdhfcn\n')
f.close()
21.第三方库
import random
print(random.randint(1,10))