目录标题

  • 1.for循环语句
  • for循环语句格式:
  • 2.while语句
  • (1)while语句格式:
  • (2)while嵌套语句格式:
  • (3)死循环:
  • 3.字符串
  • (1)字符串输出
  • (2)字符串的特性
  • (3)字符串的常用方法



1.for循环语句

for循环语句格式:

for 变量 in range(x):		#range为0~x-1
	循环需要执行的代码
else:
	全部循环结束后要执行的代码

Python的内置函数:range()

range(stop):0~stop-1
range(start,stop):start~stop-1
range(start,stop,step):start ~ stop-1 ,其中step为步长

示例1:求1~100的和

sum = 0
for i in range(1,101): #或for(i=1;i<=100;i++)
    sum +=i #sum = sum + i
print(sum)

示例2:求1~100的奇数之和

sum = 0
for i in range(1,101,2):
    sum += i
print(sum)

示例3:用户输入一个数字,求该数的阶乘:3!=321

num = int(input('NUM:'))
res = 1
for i in range(1,num+1):
    res *= i
print('%d的阶乘为:%d'%(num,res))

for循环矩阵乘法python for循环求阶乘python_字符串


for循环练习

输入两个数值:
求两个数的最大公约数和最小公倍数.
最小公倍数=(num1*num2)/最大公约数

# 1.接收两个数字
num1 = int(input('Num1:'))
num2 = int(input('Num2:'))
# 2.找出两个数字中最小的值
min_num = min(num1,num2)
# 3.最大公约数的范围在1~min_num
for i in range(1,min_num+1):
    if num1 % i == 0 and num2 % i ==0:
        # 当全部循环结束后,gys中保存的就是最大的公约数
        gys = i
# 4.最小公倍数
lcm = int((num2 * num1)/gys)
print('%d和%d的最大公约数是:%d' %(num1,num2,gys))
print('%d和%d的最小公倍数是:%d' %(num1,num2,lcm))

for循环矩阵乘法python for循环求阶乘python_for循环矩阵乘法python_02

2.while语句

(1)while语句格式:

while 条件1(True):
    语句1
else:
    语句2(循环完成后要执行的语句)

(2)while嵌套语句格式:

while 条件1(True):
    语句1
    while 条件2(True):
    	语句2
    else:
    	语句3(循环完成后要执行的语句)
else:
    语句4(循环完成后要执行的语句)

(3)死循环:

while True:
    print('!!!')
while 2>1:
    print('!!!')

示例1:求1~100的和

sum = 0
i = 1
while i <= 100:
    sum += i
    # 手动给计数器加1
    i += 1
print(sum)

for循环矩阵乘法python for循环求阶乘python_变量名_03


示例2:用户登录3次

for i in range(3): # 0 1 2
    name = input('用户名:')
    passwd = input('密码:')
    if name == 'root' and passwd == 'westos':
        print('登陆成功')
        # 跳出整个循环 不会再执行后面的内容
        break
    else:
        print('登陆失败')
        print('您还剩余%d次机会' %(2-i))
else:
    print('登陆次数超过三次,请等待100s后再试!!!')

for循环矩阵乘法python for循环求阶乘python_for循环矩阵乘法python_04

i = 0
while i < 3: # 0 1 2
    name = input('用户名:')
    passwd = input('密码:')
    if name == 'root' and passwd == 'westos':
        print('登陆成功')
        # 跳出整个循环 不会再执行后面的内容
        break
    else:
        print('登陆失败')
        print('您还剩余%d次机会' %(2-i))
        i +=1
else:
    print('登陆次数超过三次,请等待100s后再试!!!')

for循环矩阵乘法python for循环求阶乘python_变量名_05


示例3:九九乘法表之1:

制表符

# \t:制表符 协助我们在输出文本的时候在垂直方向保持对齐
print('1\t2\t3')
print('10\t20\t30')
print('100\t200\t300')

for循环矩阵乘法python for循环求阶乘python_for循环矩阵乘法python_06


换行符

# \n:换行符
print('hello\npython')

for循环矩阵乘法python for循环求阶乘python_for循环_07

row  = 1
while row <= 9:
    col = 1
    while col <= row:
        print('%d * %d = %d\t' %(row,col,row*col),end='')
        col += 1
    # 手动换行
    print('')
    row +=1

for循环矩阵乘法python for循环求阶乘python_变量名_08


示例4:九九乘法表之2:

row  = 1
while row <= 9:
    col = 9
    while col >= row:
        print('%d * %d = %d\t' %(row,col,row*col),end='')
        col -= 1
    # 手动换行
    print('')
    row +=1

for循环矩阵乘法python for循环求阶乘python_变量名_09


示例5:九九乘法表之3:

row = 1
while row <= 9:
    col = 1
    while col < row:
        print('\t\t\t',end='')
        col += 1
    while col >= row and col <= 9:
        print('%d * %d = %d\t'%(row,col,row*col),end='')
        col += 1
    print('')
    row += 1

for循环矩阵乘法python for循环求阶乘python_字符串_10


示例6:九九乘法表之4:

row = 9
while row >= 1:
    col = 1
    while col < row:
        print('\t\t\t',end='')
        col += 1
    while col >= row and col <= 9:
        print('%d * %d = %d\t'%(row,col,row*col),end='')
        col += 1
    print('')
    row -= 1

for循环矩阵乘法python for循环求阶乘python_变量名_11

3.字符串

(1)字符串输出

d = """
    用户管理系统
    1.添加用户
    2.擅长用户
    3.显示用户
    .....
    """
print(d)

for循环矩阵乘法python for循环求阶乘python_for循环_12

(2)字符串的特性

s = 'hello'
# 索引:0 1 2 3 4 索引从0开始
print(s[0])
print(s[4])
print(s[-1]) # 拿出最后一个字符

for循环矩阵乘法python for循环求阶乘python_变量名_13

# 切片 s[start:stop:step] 从start开始到stop-1结束 step:步长
s = 'hello'
print(s[0:3])
print(s[0:4:2])
print(s[:]) #显示全部的字符
print(s[:3])# 显示前3个字符
print(s[::-1]) # 字符串的反转
print(s[2:]) #除了前2个字符之外的其他字符

for循环矩阵乘法python for循环求阶乘python_for循环_14

# 重复
print(s * 10)

for循环矩阵乘法python for循环求阶乘python_变量名_15

# 连接
print('hello ' + 'python')

for循环矩阵乘法python for循环求阶乘python_for循环矩阵乘法python_16

# 成员操作符
print('he' in s)
print('aa' in s)
print('he' not in s)

for循环矩阵乘法python for循环求阶乘python_for循环_17

# for循环遍历
for i in s:
    print(i,end='')

for循环矩阵乘法python for循环求阶乘python_变量名_18

#枚举:返回索引值与对应的value值
for i,v in enumerate('hello'):
    print(str(i) + '---' + v)

for循环矩阵乘法python for循环求阶乘python_变量名_19

## zip压缩
s1 = 'sheena'
s2 = '110900'
for i in zip(s1,s2):
    print(i)

for循环矩阵乘法python for循环求阶乘python_for循环矩阵乘法python_20

练习:

  • 示例 1:
    输入: 121
    输出: true
a = input('输入121:')
print('121' in a)

for循环矩阵乘法python for循环求阶乘python_变量名_21

  • 示例 2:
    输入: -121
    输出: false
    解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。
    因此它不是一个回文数。
a = '121'
print('-121' in a)
b = '-121'
print('-121的倒叙为:', b[::-1])
print('-121不是回文数')

for循环矩阵乘法python for循环求阶乘python_for循环矩阵乘法python_22

  • 示例 3:
    输入: 10
    输出: false
    解释: 从右向左读, 为 01 。因此它不是一个回文数
c = input('输入10:')
print(c in a)
print(c[::-1])
print('10不是回文数')

for循环矩阵乘法python for循环求阶乘python_for循环_23

(3)字符串的常用方法

(1)
s.istitle() :是否为标题(首字母大写为标题),返回布尔值,只要有一个元素不满足,就返回False
s.isupper():是否为大写字母,返回布尔值,只要有一个元素不满足,就返回False
s.islower():是否为小写字母,返回布尔值,只要有一个元素不满足,就返回False
s.isdigit():是否为数字,返回布尔值,只要有一个元素不满足,就返回False
s.isalpha():是否为字母,返回布尔值,只要有一个元素不满足,就返回False
s.isalnum():是否为字母与数字的结合,返回布尔值,只要有一个元素不满足,就返回False
s.startswith(xxx):以xxx开始
s.endswith(xxx):以xxx结尾

>>> 'Hello'.istitle()
True
>>> 'hello'.istitle()
False
>>> 'hello'.isupper()
False
>>> 'hello'.islower()
True
filename = 'hello.loggggg'
if filename.endswith('.log'):
    print(filename)
else:
    print('error.file')

for循环矩阵乘法python for循环求阶乘python_for循环_24

url = 'https://172.25.254.250/index.html'
if url.startswith('http://'):
    print('爬取网页')
else:
    print('不能爬取')

for循环矩阵乘法python for循环求阶乘python_for循环_25


(2)

s.lower():将字符串改为小写

s.upper():将字符串改为大写

s.title():将字符串改为标题

>>> 'HELLO'.lower()
'hello'
>>> a = 'HELLO'.lower()
>>> a
'hello'
>>> 'Herwr'.upper()
'HERWR'
>>> 'HELLO'.title()
'Hello'

练习:

变量名定义是否合法:
1.变量名可以由字母 数字 下划线组成
2.变量名只能以字母和或者下划线开头

while True:
    s = input('变量名:')
    if s == 'exit':
        print('exit')
        break
    if s[0].isalpha() or s[0] == '_':
        for i in s[1:]:
            if not (i.isalnum() or i == '_'):
                print('%s变量名不合法' % (s))
                break
        else:
            print('%s变量名合法' % (s))
    else:
        print('%s变量名不合法' % (s))

for循环矩阵乘法python for循环求阶乘python_字符串_26


(3)字符串的脏数据去除

s.rstrip():去除右边的空格

s.lstrip():去除左边的空格

s.strip():去除空格

注意:s.strip()去除左右两边的空格,空格为广义的空格 包括:\t \n
s.strip('x'):去除字符串中的所有字符x
s.lstrip('x'):去除字符串中最左边的字符x

>>> s = '     hello     '
>>> s.lstrip()
'hello     '
>>> s.rstrip()
'     hello'

>>> s = '     hello     \t\t'
>>> s.lstrip()
'hello     \t\t'
>>> s.rstrip()
'     hello'

>>> s = 'helloh'
>>>> s.strip('h')
'ello'
>>> s.lstrip('h')
'elloh'
>>> s.strip('he')
'llo'

(4)字符串的对齐
s.center(num):字符串s位于30个单元格的中间
s.center(num,'*'):字符串s位于30个单元格的中间,其他单元格用补齐
s.ljust(num,'*'):字符串s位于30个单元格的左边,其他单元格用**补齐
s.rjust(num,'*'):字符串s位于30个单元格的右边,其他单元格用补齐

print('学生管理系统'.center(30))
print('学生管理系统'.center(30,'*'))
print('学生管理系统'.ljust(30,'*'))
print('学生管理系统'.rjust(30,'*'))

for循环矩阵乘法python for循环求阶乘python_字符串_27


(5)字符串的查找与替换

s.find('xxx'):找到子字符串xxx,并返回子字符串最小的索引

s.rfind('xxx'):找到字符串s最右边出现的子字符串xxx,并返回子字符串最小的索引

s.replace():替换字符串中的sheena为sehun

s = 'hello world hello'
print(s.find('world'))
print(s.rfind('hello'))
print(s.replace('hello','westos'))

for循环矩阵乘法python for循环求阶乘python_for循环_28


(6)字符串的统计

s.count('xxx'):统计字符串s中子字符串xxx出现的次数

len(s):统计字符串s的长度

print('hello'.count('l'))
print('hello'.count('ll'))

print(len('westossssss'))

for循环矩阵乘法python for循环求阶乘python_字符串_29


(7)字符串的分离和连接

s.split('xxx'):以xxx作为分隔符分离字符串s,存放在列表中

'xxx'.join(s):通过指定的连接符号,连接列表中的每个字符,形成新的字符串

s = '172.25.254.250'
s1 = s.split('.')
print(s1)

date = '2019-12-08'
date1 = date.split('-')
print(date1)

print(''.join(date1))
print('/'.join(date1))
print('~~~'.join('hello'))

for循环矩阵乘法python for循环求阶乘python_变量名_30


练习1:

给定一个句子(只包含字母和空格), 将句子中的单词位置反转,单词用空格分割, 单词之间只有一个空格,前>后没有空格。
1.“hello xiao mi”-> “mi xiao hello”
输入描述:
输入数据有多组,每组占一行,包含一个句子(句子长度小于1000个字符)
输出描述:
对于每个测试示例,要求输出句子中单词反转后形成的句子
2.示例1:

  • 输入
    hello xiao mi
  • 输出
    mi xiao hello
a=input('输入英文句子:')
a1=a.split(' ')
a2=a1[::-1]
a3=' '.join(a2)
print('输出:%s' %a3)

for循环矩阵乘法python for循环求阶乘python_字符串_31


练习2:

设计一个程序,帮助小学生练习10以内的加法
详情:

  • 随机生成加法题目;
  • 学生查看题目并输入答案;
  • 判别学生答题是否正确?
  • 退出时, 统计学生答题总数,正确数量及正确率(保留两位小数点);
import random			#导入随机数的函数库
AllCount = 0			#统计答题总数
RightCount = 0			#统计答题正确数
while True:			#循环,设置该考试为10道题
    StudentAction = int(input('请选择你要执行的动作:(1)答题(2)退出: '))			#输入动作
    if StudentAction == 1:			#若选择答题
        num1 = random.randint(1, 10)			#生成第一个1~10之间的随机数
        num2 = random.randint(1, 10)			#生成第二个1~10之间的随机数
        sum = num1 + num2			#求和
        print('%d+%d=?' % (num1, num2))			#显示题目
        StudentAnswer = int(input("请输入答案:"))			#输入答案
        if StudentAnswer == sum:			#若回答正确
            RightCount += 1			#正确数+1
            AllCount += 1			#答题总数+1
        else:			#若回答错误
            AllCount += 1			#答题总数+1
    else:			#若选择退出
        print('bye~')			
        break			#直接跳出循环,不再进入循环答题
RightCountPercent = (RightCount / AllCount) * 100			#计算答题的正确率
print('该同学共答了%d道题目,正确的数量为%d道,正确率为%.2f%%' % (AllCount, RightCount, RightCountPercent))			
#显示输出

for循环矩阵乘法python for循环求阶乘python_变量名_32


练习3:

小学生算术能力测试系统:
详情:

  • 设计一个程序,用来实现帮助小学生进行百以内的算术练习,
  • 它具有以下功能:提供10道加、减、乘或除四种基本算术运算的题目;
  • 练习者根据显示的题目输入自己的答案,
  • 程序自动判断输入的答案是否正确并显示出相应的信息。
import random	
i=0
while i <= 10:
    a = ['+','-','*','/']
    a1 = random.choice(a)
    num1 = random.randint(0, 100)
    num2 = random.randint(0, 100)
    print('%d %s %d= ' % (num1, a1, num2))
    num3 = int(input('输入你的答案:'))
    if a1=='+':
        sum_num=num1+num2
        if sum_num==num3:
            print('输入的答案正确')
        else:
            print('输入的答案错误')
    if a1=='-':
        sum_num=num1-num2
        if sum_num==num3:
            print('输入的答案正确')
        else:
            print('输入的答案错误')
    if a1=='*':
        sum_num=num1*num2
        if sum_num==num3:
            print('输入的答案正确')
        else:
            print('输入的答案错误')
    if a1=='/':
        sum_num=num1/num2
        if sum_num==num3:
            print('输入的答案正确')
        else:
            print('输入的答案错误')
    i+=1

for循环矩阵乘法python for循环求阶乘python_变量名_33