Python笔记-3-循环、循环练习

while condition:
    block
for element in iteratable:
    block

可迭代对象

元素的值可以相同,但相同元素的地址不同
关键是可迭代对象中的东西是散放的,只能保证一个元素迭代一次
循环控制:continue 中断当前循环的当次执行,继续下一次循环
位运算实现偶数

for i in range(0,10,2):
    print(i)
for i in rang(10):
    if not i&0x01:
        print(i)

循环控制:break 终止当前循环

count = 0
for i in range(0,1000,7):
    print(i)
    count += 1
    if count == 20:
        break
nums = input("不超过5位的正整数,q退出")
while 1:
    if nums.isdigit():
        numn = int(nums)
        if numn <= 0 or numn > 99999:
            print("重新输入")
            nums = input("不超过5位的正整数,q退出")
            continue
        else:
            print("len=",len(nums))
            for i in range(len(nums)):
                print(numn%10)
                numn //= 10
        nums = input("不超过5位的正整数,again,q退出")
        continue
    else:
        if nums == "q" or nums == "Q":
            print("Bye!\n")
            break
        else:
            print("error input!")
            nums = input("不超过5位的正整数,q退出")
            continue
print("len=",len(num))
num = int(num)
for i in range(len(num)):

由万位到个位

nums = input("不超过5位的正整数,q退出")
while 1:
    if nums.isdigit():
        numn = int(nums)
        if numn <= 0 or numn > 99999:
            print("重新输入")
            nums = input("不超过5位的正整数,q退出")
            continue
        else:
            print("len=",len(nums))
            for i in range(len(nums),0,-1):
                print(numn//10**(i-1))
                numn = numn%10**(i-1) #这个地方可以用取模的方式实现
        nums = input("不超过5位的正整数,again,q退出")
        continue
    else:
        if nums == "q" or nums == "Q":
            print("Bye!\n")
            break
        else:
            print("error input!")
            nums = input("不超过5位的正整数,q退出")
            continue
边输出每个位 边确定个数
num = int(input('num='))
n = 5
w = 10**5
flag = False
while w:
    t = num//w
    if flag:
        print(t)
    else:
        if t:
            print(t)
            flag = True
        else:
            n -= 1
    num %= w
    w //= 10
print('len = ',n)

else子句:如果循环正常的执行结束,就执行else子句;如果使用break终止,else子句不会执行

while condition:
    block
else:
    block
for i in iterable:
    block
else:
    block

练习

1--------------------------------------

方法1
n = int(input("边长n="))
for i in range(n):
    if i==0:
        for j in range(n):
            if j==n-1:
                print('*')
            else:
                print('*',end='')
    elif i==n-1:
        for j in range(n):
            if j==n-1:
                print('*')
            else:
                print('*',end='')
    else:
        for j in range(n):
            if j==0:
                print('*',end='')
            elif j==n-1:
                print('*')
            else:
                print(' ',end='')
方法2
n = int(input("边长n="))
for i in range(n):
    if(i==0 or i==n-1):
        print('*'*n)
    else:
        print('*',' '*(n-2),'*',sep='')
n = int(input("边长n="))
for i in range(n):
    if(i==0 or i==n-1):
        print('* '*n)
    else:
        print('* ',' '*(n-2),'*')
方法3
n = int(input("边长n="))
for i in range(n):
    if i==0 or i==n-1:
        print('*\t'*n)
    else:
        print('*\t','\t'*(n-2),'*\t',sep='')
    print('\n')
方法4:将range的范围对称化
n = int(input('>>>>'))
e = -n//2
for i in range(e,n+e):
    if i==e or i==n+e-1:
        print('*'*n)
    else:
        print('*'+' '*(n-2)+'*')

2-----------------------------------

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

3--------阶乘---------------------------

sum = 1
t = 1
for i in range(2,6):
    t *= i
    sum += t
print(sum)

4-----------------------------------

score = int(input('score='))
if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 70:
    grade = 'C'
elif score >= 60:
    grade = 'D'
else:
    grade = 'E'
print('grade=',grade)
折半的思想
score int(input('score='))
if score >= 80:
    if score < 90:
        print('B')
    else:
        print('A')
else:
    if score >= 70:
        print('C')
    elif score >= 60:
        print('D')
    else:
        print('E')

5-----------------------------------

import math
num = int(input('num='))
for i in range(2, int(math.sqrt(num))+1 ):
    if not num%i:
        print(num,"is not prime")
        break
else:
    print(num,"is prime")

素数:偶数肯定不是素数
练习题

###1
#2πr
#πr2
pi = 3.14159
while 1:
    r = input('R=')
    if r.replace('.','').isdigit():
        r = float(r)
        print("周长=",2*pi*r,"\n面积=",pi*r*r)
        continue
    else:
        if r == 'Q' or r == 'q':
            print('Bye!')
            break
        else:
            print('Error,input again:')
            continue

2

while 1:
    num1 = input('number1=')
    num2 = input('number2=')
    t1 = num1.replace('.','')
    t1 = t1.replace('-','')
    t2 = num2.replace('.','')
    t2 = t2.replace('-','')
    if t1.isdigit() and t2.isdigit():
        if float(num1) >= float(num2):
            print(num2,num1)
        else:
            print(num1,num2)
        #三元表达式
        print(num2,num1) if float(num1) >= float(num2) else print(num1,num2)
    else:
        if num1 == 'Q' or num1 == 'q':
            print('Bye!')
            break
        else:
            print('Error,input again:')
            continue

3

输入若干整数,打印最大值

max_n = 0 #这地方有坑引入了非用户输入变量,如果输入的负值就失效了
flag = 1
i = 1

while 1:
    num = input('num%d='%(i))
    t = num.replace('.','')
    t = t.replace('-','')
    if t.isdigit():
        if flag:
            flag = 0 # 但是也有解决的方法
            max_n = float(num)
        elif float(num) > max_n:
            max_n = float(num)
    else:
        if num == 'q' or num == 'Q':
            break
        else:
            print('Error!,input again!')
            continue
    i += 1
print("max=",max_n)

让用户提供个数
用户不提供个数
或者,将用户输入的第一个数保存在max,然后继续循环输入

num = input('num1=')
t = num.replace('.','')
max_n = t.replace('-','')
i = 1
#输入若干个整数,打印出最大值
m=float("-inf")
i=1
Sum=0
while True:
    num=input("===>")
    if num.replace('.','').replace('-','').isdigit():
        num=float(num)
        if m < num:
            m=num
        Sum+=num
        print('平均值 =',Sum/i,'\n')
        #计算算数平均
        i+=1
        continue
    elif num == 'q' or num == 'Q':
        print('max =',m,'\n')
        break
    else:
        print('Input Error!\n')
        continue
先加 最后的和再计算平均数

作业

1------------------------------------------------------------------

for i in range(1,10):
    for j in range(1,i+1):
        print(i,'×',j,'=',i*j,sep='',end='\t')
    print()
for i in range(1,10):
    for j in range(1,i+1):
        if i*j<10 and j>1:
            print(j,'×',i,'=',i*j,sep='',end='   ')
        else:
            print(j,'×',i,'=',i*j,sep='',end='  ')
    print()
for i in range(1,10):
    for j in range(1,10):
        if i>j:
            print('     ',sep='',end='\t')
        else:
            print(i,'×',j,'=',i*j,sep='',end='\t')
    print()
for i in range(1,10):
    s=''
    for j in range(i,10):
        s+='{}*{}={:<{}}'.format(i,j,i*j,2 if j<4 else 3)
    print('{:>66}'.format(s))
print函数可以在里面用*指定字符的个数

2------------------------------------------------------------------

#######

n = int(input('number = '))
if not n&1:
    n += 1
for i in range(1,n//2+2):
    q = i + (i-1)
    s = (n - q)//2
    for j in range(1,n+1):
        if j <= s:
            print(' ',end='')
        elif j <= q+s:
            print('*',end='')
        else:
            print('\n')
            break
print('\n')
for i in range(1,n//2+1):
    s = n-(i*2)
    for j in range(1,n+1):
        if j <= i:
            print(' ',end='')
        elif j <= i+s:
            print('*',end='')
        else:
            print('\n')
            break

对称的思想

n = int(input('number = '))
if not n&1:
    n += 1
e = -n//2
for i in range(e,n+e+1):
    print(' '*abs(i)+'*'*(n-abs(i)*2))
#或者以后形成一个对称数列
#对顶三角形
1 *****
2  *** 
3   *  
4  *** 
5 *****
n = int(input('number'))
if not n&1:
    n+=1
e=n//2 - n + 1
print(range(e,n+e))
for i in range(e,n+e):
    num=abs(i)*2 + 1
    s=(n-num)//2
    print(' '*s,'*'*num)
#是在下输了!
   *
  **
 ***
*******
   ***
   **
   *
```python
n = int(input('number'))
if not n&1:
    n+=1
e=n//2
for i in range(-e,e+1):
    if i<0:
        print(' '*abs(i),'*'*(n//2-abs(i)+1),sep='')
    elif i>0:
        print(' '*(n//2),'*'*(n//2+1-i),sep='')
    else:
        print('*'*n)

3-----------------------------------------------

f1 = 0
f2 = 1
while f2 <= 100: 
    print(f2)
    t = f1+f2
    f1 = f2
    f2 = t
python中的交换:
f1, f2 = f2 , f1+f2
右边的都算完,然后给左边

4-----------------------------------------------

f1 = 0
f2 = 1
count = 1
while count <= 101:
    print(f2)
    t = f1+f2
    f1 = f2
    f2 = t
    count += 1
打印斐波那契数列的第101
f1=0
f2=1
for count in range(100):
    f1,f2=f2,f1+f2
else:
    print(f2)

5-----------------------------------------------

import math
number = 0
for n in range(2,100001):#0001 #[2,range(3,100001,2)]
    for i in range(2,int(math.sqrt(n))+1):
        if not n%i:
            break
    else:
        number+=1
        #print(n)
print("共",number,"个素数\n")
#9592
import datetime
start = datetime.datetime.now()
import math
number = 0
for n in range(3,1000001,2):
    if (n>10 and n%5 == 0) or (n%6!=1 and n%6!=5):
        continue
    for i in range(3,int(math.sqrt(n))+1,2):
        if not n%i: #整除了
            break
    else:
        number+=1
        #print(n)
print("共",number+1,"个素数\n")
(datetime.datetime.now()-start).total_seconds()

x
x/2 -1 = y
y/2 -1 = z
.
.
.
x = 2(y+1)
y = 2
(z+1)
1
z=1

for i in range(1,10):
    z=2*(z+1)
print(z)
x=1534
for i in range(1,10):
    x=(x//2)-1
print(x)

使用函数
range() 返回可迭代的range对象
range(stop) -> range object
range(start, stop[, step]) -> range object
range(5) --> range(0,5) --> [0,5) 前包后不包
通过input输入一个字符串时
n.replace('.','').isdigit()可用来判断输入的是不是实数
是实数就能方便的转化为float
isinstance检查对象是否为某种类型
print()函数的新理解
value逗号分隔,sep指定分隔符
了解format格式输出,‘{占位符},{占位符},{占位符}’.format(1,2,3)
占位符默认从0开始,{: >20} {:<10} 字符串的总位数,以及左打头还是右打头
:是前后不同描述符的分隔符
三元表达式 真值执行 if 条件 else 假值执行
a=1
b=2
print(a) if a

你可能感兴趣的:(Python笔记-3-循环、循环练习)