# ##典型的循环语句应用题:1+2+3+...100=?#####
## C语言或者Java##;
sum = 0
for(int i=1; i<100; i++):
sum = sum + i
0+1+2+3+...100
##python##
*** range()函数 python2
range(stop): 0~stop-1
range(start, stop): start~stop-1
range(start, stop, step): start~stop-1, step为步长
>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,10,2)
[1, 3, 5, 7, 9]
>>> # 拿出1~10之间所有的偶数
... range(2,11,2)
[2, 4, 6, 8, 10]
>>> # 拿出1~10之间所有的奇数
... range(1,11,2)
[1, 3, 5, 7, 9]
# for循环使用的语法:
for 变量 in range(10):
循环需要执行的代码
for 变量 in range(10):
循环需要执行的代码
else:
循环执行结束执行的代码
"""
用户登陆程序需求:
1. 输入用户名和密码;
2. 判断用户名和密码是否正确? (name='root', passwd='westos')
3. 为了防止暴力破解, 登陆仅有三次机会, 如果超过三次机会, 报错提示;
"""
#!/usr/local/python3/bin/python3
# 为了让登陆代码循环三次
for i in range(3):
name = input("用户名:")
passwd = input("密码:")
if name == 'root' and passwd == 'westos':
print("登陆成功")
break
else:
print("登陆失败")
print("您还剩余%d次机会" %(2-i))
else:
print("登陆次数超过三次")
"""
求和:
#!/usr/local/python3/bin/python3
sum = 0
for i in range(1,101): # i=1,2,3....100
sum = sum + iprint(sum)
需求1: 求1~100之间所有奇数的和;
#!/usr/local/python3/bin/python3
sum=0
for i in range(1,101,2):
sum=sum+i
print(sum)
需求2: 求1~100之间所有偶数的和;
#!/usr/local/python3/bin/python3
sum=0
for i in range(2,101,2):
sum=sum+i
print(sum)
需求3: 用户输入一个整形数, 求该数的阶乘; 3!=3*2*1=6
#!/usr/local/python3/bin/python3
num = int(input('Num:')) # num = 3 1*2*3 3*2*1
res = 1
for i in range(1, num+1): # num:3 range(1, 4) === 1,2,3
res = res * i
print("%d阶乘的结果为:%d" %(num, res))
***跳出循环的方法**
"""
break: 跳出整个循环, 不会再循环里面的内容;
continue:跳出本次循环, continue后面的代码不再执行, 但是还会继续循环;
exit: 结束程序的运行
"""
#实现命令提示符雏形
#!/usr/local/python3/bin/python3
#倒入os模块
import os
# 死循环
while True:
cmd = input("[root@test ]# ")
if cmd:
if cmd == 'exit':
print('logout')
break
print("hello") # 不会执行
else:
print("run %s" %(cmd))
# 运行shell命令
os.system(cmd)
else:
continue
print("hello") # 不会执行的
***range与xrange**
# python2:
- range(5): 即刻生成数据, 消耗时间并占用内存;
- xrange(5): 先生成一个xrange对象, 使用值时才生成数据, 占用内存;
# python3:
- range(5) 相当与python2里面的xrange;
#while条件语句:
''''''
while 条件语句:
满足条件执行的语句
else:
不满足条件执行的语句
"""
"""
while死循环
while True:
pass
while 1: # bool(1)
pass
while 2>1:
pass
"""
# 1. 1+2+3+.....+100
#!/usr/local/python3/bin/python3
# i+=1 i=i+1
sum = 0
i = 1
while i <=100:
sum += i
i += 1
print(sum)
# 2. 把用户登陆的代码for循环部分改写为while循环;
#!/usr/local/python3/bin/python3
i=0
while i < 3:
name=input("用户名:")
passwd=input("密码:")
i+=1
if name=='root' and passwd == 'westos':
print("登陆成功")
break
else:
print("登陆失败")
print("您还剩余%d次机会" %(3-i))
else:
print("登陆次数超过三次")
#########字符串############
#字符串的定义:
*第一种方式:
str1='hello'
*第二种:
str2="hello"
*第三种:
str3="""hello"""
#转义符号:
一个反斜线加一个单一字符可以表示一个特殊字符,通常是不可打印的字符
\n: 代表换行符 \": 代表双引号本身
\t: 代表tab符 \': 代表单引号本身
#字符串的特性:
*索引
```>>> s = "hello"
正向索引:
>>> s[1]
'e'
>>> s[0]
'h'
>>> s[4]
'o'
反向索引:
>>> s = "hello world"
>>> s[-1]
'd'
>>> s[-2]
'l'
>>> s[-3]
'r'
```
*切片
s[start:end:step] # 从start开始到end-1结束, 步长为step;
- 如果start省略, 则从头开始切片;
- 如果end省略, 一直切片到字符串最后;
s[1:]
s[:-1]
s[::-1] # 对于字符串进行反转
s[:] # 对于字符串拷贝
# 成员操作符
```
>>> s = "hello"
>>> 'h' in s
True
>>> 'hel' in s
True
>>> 'oo' in s
False
>>> 'h' not in s
False
>>> 'oo' not in s
True
```
# 字符串连接
```
>>> a = "hello"
>>> b = "python"
>>> print("%s %s" %(a, b))
hello python
>>> a + b
'hellopython'
>>> a + " " +b
'hello python'
```
# 字符串的重复
```
>>> print("*"*10 + "学生管理系统" + "*"*10)
**********学生管理系统**********
#字符串的常用方法:
str.isalnum() //判断是否都是字母或数字
str.isalpha() //判断是否都是字母
str.isdigit() //判断是否都是数字
str.islower() //判断是否都是小写
str.isspace() //判断是否都是英文空格
str.istitle() //判断是不是都是标题(有大小写)
str.isupper() //判断是不是都为大写字母
>>> "Hello".istitle()
True
>>> "hello".istitle()
False
>>> "HelloWorld".istitle()
False
>>> help("HelloWorld".istitle)>>> "hello".upper()
'HELLO'
>>> "heLlo".lower()
'hello'
>>> "heLlo".title()
'Hello'
>>> "heLlo".swapcase()
'HElLO'
endswith(suffix[, start[, end]])
- 判断字符串是否以suffix结束,如果start和end指
定,则返回str中指定范围内str子串是否以suffix结尾,如果
是,返回True;否则返回False
startswith(prefix[, start[, end]])
>>> s="I an cooffee"
>>> s.endswith("ee")
True
>>> s.endswith("ee",1,5)
False
>>> s.endswith("ee",5,12)
True
strip([chars])
- 返回一字符串,将str中首尾包含指定的chars字符
删除的字符串,未指定时,删除首尾的空格。
lstrip
rstrip
# 注意: 去除左右两边的空格, 空格为广义的空格, 包括: \n, \t, \r
>>> s = " hello "
>>> s.strip()
'hello'
>>> s.lstrip()
'hello '
>>> s.rstrip()
' hello'
>>> s = "\nhello "
>>> s.strip()
'hello'
>>> s = "\thello "
>>> s.strip()
'hello'
>>> s = "helloh"
>>> s.strip('h')
'ello'
>>> s.strip('he')
'llo'
>>> s.lstrip('he')
'lloh'
find(sub[,start[,end]])
- 判断sub是否在str中,存在返回索引值,不存在返
回-1.
replace(old,new[,count])
- 将str中的old字符串替换为new字符串,并将替换
后的新字符串返回,如果count指定,则只替换前count个
字符串
count(sub[, start[, end]]) -> int
- 返回sub在str中出现的次数,如果start与end指定,
则返回指定范围内的sub出现次数。
>>> s = "hello python , learn python"
>>> s.find('python')
6
>>> s.rfind('python')
21
>>> s.replace('python', 'linux')
'hello linux , learn linux'
>>> s
'hello python , learn python'
>>> s1 = s.replace('python', 'linux')
>>> s1
'hello linux , learn linux'
>>> s
'hello python , learn python'
>>> s.count("p")
2
center(width[,fillchar])
- 返回一个长为width的新字符串,在新字符串
中原字符居中,其他部分用fillchar指定的符号填充,
未指定时通过空格填充
ljust,
rjust
>>> print("学生管理系统".center(50, '*'))
****************学生管理系统****************
>>> print("学生管理系统".ljust(50, '*'))
学生管理系统********************************
>>> print("学生管理系统".rjust(50, '*'))
********************************学生管理系统
split([sep[,maxsplit]])
- 以sep字符串作为分割符对str进行切割,默认为空
格;
- maxsplit代表切割的此处
str.join(seq)
- 以str作为分隔符,将序列seq中的所有元素合并为
一个新的字符串。
>>> ip1 = "172.25.254.19">>>ip= ip1.split('.')
>>> ip
['172', '25', '254', '19']
>>> date = "2018-2-30"
>>> ":".join(ip)
'172:25:254:19'
#python在字符串常用的内置方法:
# 枚举: 返回索引值和对应的value值;
>>> for i,v in enumerate('hello'):
... print(str(i) +" -----> " + v)
...
0 -----> h
1 -----> e
2 -----> l
3 -----> l
4 -----> o
# zip
>>> s1 = 'abc'
>>> s2 = "123"
>>> for i in zip(s1,s2):
... print(i)
...
('a', '1')
('b', '2')
('c', '3')
>>> for i in zip(s1,s2):
... print("".join(i))
...
a1
b2
c3
"""
1.设计一个程序,帮助小学生练习10以内的加法
详情: x=random.randint(0,10)
- 随机生成加法题目;
- 学生查看题目并输入答案;
- 判别学生答题是否正确?
- 退出时, 统计学生答题总数,正确数量及正确率(保留两位小数点);
#!/usr/local/python3/bin/python3
import random
print("温馨小提示:退出请输入exit")
sum1=0
right=0
while 1:
a=random.randint(0,9)
b=random.randint(0,9)
print("%d+%d=?" %(a,b))
c=input("请输入您的答案:")
sum1+=1
if c!= 'exit':
d=int(c)
if d==(a+b):
print("恭喜您答对了")
right+=1
else:
print("答错了哦!")
else:
break
sum2=sum1-1
lve=(right/sum2)*100
print("您总共答了%d道题,答对了%d道题,正确率为%.2f%%" %(sum2,right,lve))
2.
"""
输入两个数值:
求两个数的最大公约数和最小公倍数.
最小公倍数=(num1*num2)/最大公约数
"""
#!/usr/local/python3/bin/python3
num1 = int(input('Num1:'))
num2 = int(input('Num2:'))
min_num = num1 if num1<num2 else num2
for i in range(1,min_num+1):
if num1%i == 0 and num2%i ==0:
gys=i
lcm = int((num1*num2)/gys)
print("%s和%s的最大公约数为%s" %(num1,num2,gys))
print("%s和%s的最小公倍数为%s" %(num1,num2,lcm))