pyton基础 1
1. 文件
- python文件名可以任意
- 导入模块时,后缀名是.py
2. 变量
由字母、数字和_组成,不能以数字开头
关键字
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
3. 字符串
单引号或双引号或三个引号包裹的内容
name = 'root'
name = "root"
name = '''root'''
name = """root"""
3.1 加法
n1 = 'hello'
n2 = 'world'
print(n1 + n2)
3.2 乘法
n1 = 'hello '
print(n1 * 10) # 重复出现十次
4. 数字
a1 = 10
a2 = 20
a3 = a1 + a2
a4 = a1 - a2
a5 = a1 * a2
a6 = a1 / a2
a7 = 4**4 # 幂
a8 = 40 % 3
a9 = 40 // 3 # 商
5. 条件语句
5.1 if - else
USER = 'root'
PASSWORD = '123'
user = input('请输入用户名:')
password = input('请输入密码:')
if user == USER:
print('用户名正确')
if password == PASSWORD:
print('密码正确')
print('登录成功')
else:
print('密码错误')
else:
print('用户名错误')
5.2 if elif else
user = input('请输入用户名:')
if user == 'root':
print('正确')
elif user == 'admin':
print('超级用户')
else:
print('用户名错误')
5.3 条件语句中,不执行操作,使用pass
5.4 and
USER = 'root'
PASSWORD = '123'
user = input('请输入用户名:')
password = input('请输入密码:')
if user == USER and password == PASSWORD:
print('登录成功')
6. while
死循环
import time
while True:
print('ok', time.time())
count = 0
while count < 10:
print('ok')
count = 11
print('done')
count = 0
while count < 10:
count += 1
print(count)
练习题
1.使用while 循环输出123456 8 9 10
2.求1-100 的所有数的和
3.输出1-100内所有奇数
4.输出1-100内所有偶数
5.求 1-2+3-4+5 ...99 的所有书的和
6.用户登录(3次机会重试)
1.使用while 循环输出1,2,3,4,5,6,8,9,10
n = 1
while n < 11:
if n != 7:
print(n)
n += 1
2.求1-100 的所有数的和
sum = 0
n = 1
while n < 101:
sum += n
n += 1
print(sum)
3.输出1-100内所有奇数
n = 1
while n < 101:
if n % 2 != 0:
print(n)
n+=1
4.输出1-100内所有偶数
n = 1
while n < 101:
if n % 2 == 0:
print(n)
n+=1
5.求 1-2+3-4+5 …99 的所有书的和
for 循环
sum = 0
for i in range(100):
if i % 2 == 0:
sum = sum - i
else:
sum = sum + i
print(sum)
while 循环
n = 1
sum = 0
while n < 100:
if n % 2 == 0:
sum -= n
else:
sum += n
n += 1
print(sum)
6.用户登录(3次机会重试)
USER = 'root'
PASSWORD = '123'
n = 0
while n <=2:
user = input('请输入用户名(root)):')
password = input('请输入密码:')
if user == USER:
print('用户名存在')
if password == PASSWORD:
print('密码正确')
print('登录成功')
break
else:
n += 1
print('密码错误次数: ', n)
else:
print('用户名不存在')