2019.07.17 study notes (program loop control)

A. Review Review (basic data types)

1. Digital Type

(1) integer

  • x = int(10)
    pow(x, 10)

(2) Float

  • y = float(10)  # 10.0
    print(round(0.1 + 0.2, 1) == 0.3)

2. Operator

  • +-*/ // % **

3. String

  • name = str(10)  # '10'
    name = 'nick'
    name = "nick"
    name = "nick's"# 双引号可以包裹单引号
    name = """
    nick's 
    name 
    is "nick"
    """  # 三双引号里的字符串可以换行

4. The built-in method

  • name.split()  # 指定字符串分割
    name.startswith('n')#从头开始匹配 
    name.endswith('k')# 从尾开始匹配
    print(name.center(50, '*')) # 从中间开始补充字符*,总长度50

The escape character

  • s = "nick's name is \"nick\""
    s = '\t' # 缩进
    print(s)
    s = '\n' # 换行
    print(s)
    s = r'\t\n' # \r原位打印,和end=''成对使用
    print(s)
    
    for i in range(5):
        print('1',end=',')

Two control structure of a program

1. The branched structure

  • Single branch

  • Usually for determining if the scene / selection

  • 90 points or more outstanding

    score=95
    if score>90:
        print('优秀')
  • Dual Branch

  • if ....else

  • More than 90 points outstanding, 90 points or less good

    score=95
    if score>90:
      print('优秀')
    else:
      peint('良好')
  • A triplet of expressions

     score=75
        print('优秀')if score>90 else print('良好')# 单分支没有,多分支也没有
        #结果一 条件 结果二
  • Multi-Branch

  • Elif Elif .... if .... else ......

  • 90 more than excellent, 90-70 good, about 70 fail

    score=95
    if score>90:
      print('优秀')
    elif score>70:
      peint('良好')
    else:
        peint('及格')
  • if......if......if......if

    score=95
    if score>90:
      print('优秀')
    if score>70 and score<90:
      peint('良好')
    if score<60:
        peint('及格')

2. Logical Operators

  • > >= < <= == !=
  • and 两者都必须成立
  • or 其中一个成立即可
  • not 非

III., And combinations conditional

1. Analyzing conditions

Operators Mathematics Symbol description
< < Less than
<= Less than or equal
>= greater or equal to
> > more than the
== = equal
!= not equal to

2. The combination of conditions

Operators, and use description
x and y Two logic conditions are x and y and
x or y Or two logical conditions of x and y
not x X is the logical NOT condition

3. Analyzing conditions and combinations

  • guess = eval(input())
    if guess > 99 or guess < 99:
        print("猜错了")
    else:
        print("猜对了")

IV. Exception Handling

1. The basic exception handling using

  • try:
    <语句块1>
    except:
    <语句块2>
    
    try:
        num = eval(input("请输入一个整数: "))
        print(num**2)
    except:
        print("输入不是整数")
  • # 示例
    try:
        y = int(input('数字:'))  # 10
        y += 10 # y = y + 10
    except Exception as e:
        print(f'error: \033[1;35m {e} \033[0m!')
    finally:  # 无论报不报错,都会执行finally下面的代码
        print(1)
    
    Exception# 异常处理的时候,只要写这个就可以了
    raise  # 自定义报错
    assert 断言()
    assert 1==2

2. The use of high-level exception handling

  • finally4 corresponding to a certain block of statements executed
  • else3 corresponds to a block of statements executed when an abnormality occurs
try:
    <语句块1> 
except:
    <语句块2> 
else:
    <语句块3> 
finally:
    <语句块4>

V. loop structure of the program

1.for circulation

  • for i in range(1,10,2): 
         print(i)# [1,3,5,7,9],输出的就是1-10之间的奇数
    for i in 'nick':
        print(i)# n,i,c,k每个字符换行输出

2.while cycle

  • continue和break的区别
    # continue不执行下面代码,继续运行循环
    count = 0
    while count < 100: # 49
        if count == 49:
            count += 1
            continue  # 不执行下面代码,继续运行循环
        count += 1 # 50   跳过不打印
        print(count) # 50
    
    # break终止循环  结束本次的while循环
    count = 0
    while count < 100: # 49
    
        if count == 49:
            count += 1
            break  # 终止循环    结束本次的while循环
        count += 1 # 50
        print(count) # 50

3.while.....else

  • count = 0
    while count < 100: # 49
        if count == 49:
            count += 1
            break # 终止循环
        count += 1 # 50n
        print(count) # 50
    else:  #正常跳出循环的时候会执行,异常中断不执行
        print('打我')

4.break和continue

  • and end the current break out of the entire cycle, the statement after the execution cycle
  • break out of only the innermost loop current
  • When the end of the cycle continue, continue to perform the subsequent cycles
  • break and continue can be used with the for and while loops
  • When the cycle is not exit the break statement, the else statement block

The string traversal

  • s is a string, each character string traversed, generation cycle

    for c  in  s: 
        <语句块>

6. The list loop through

  • ls is a list, each element traversing, generation cycle

    for item  in  ls:
        <语句块>

Six .random module

1.random generate random numbers

random library using the Python standard library of random numbers

  • Pseudorandom number: using (pseudo) random sequence of Mersenne Twister generated element
  • random serves mainly for generating a random number
  • Use random library:import random

  • import random
    random.seed(10) # 种子 # 如果不自定义种子,则种子按照当前的时间来
    print(random.random())# 取0和1之间的小数
    print(random.choice([1,1,2,3,4]))

2. The basic function of the random number

function description
seed(a=None) Initialized with the given random number seed, the default is the current system time
random() Generating a random decimal between [0.0, 1.0)
function description
Randine (a, b) Generating an integer between [a, b]
randrange (m, n [k]) Generating a [m, n) in between steps k is a random integer
getrandbits (k) getrandbits (k)
uniform(a, b) Generating a random decimal between [a, b]
choice(seq) Select a random element from a sequence seq
shuffle(seq) Seq sequence elements in a random arrangement, the sequence returns to disrupt
import random

random.seed(10)  # 产生种子10对应的序列
random.random()

3.time () custom function

  • # 自己造的一个随机数
    import time
    time=time.time()
    print(str(time).split('.')[-1][-1])

Computing VII. Pi

  • # Π
     pi = 0
     k = 0
     while True:
     pi +=  (1/(16**k))* \
               (4/(8*k+1) - 2/(8*k+4) - 1/(8*k+5) - 1/(8*k+6))# 数学求Π的公式
      print(pi)
      k += 1
    
    
    # 蒙特卡洛方法求Π
    import random
    
    count = 0
    for i in range(100000):
        x, y = random.random(), random.random()
        dist = pow(x ** 2 + y ** 2, 0.5)
        if dist < 1:
            count += 1
    print(count / 100000 * 4)

operation:

1. 使用while循环输出1 2 3 4 5 6     8 9 10
2. 求1-100的所有数的和
3. 输出 1-100 内的所有奇数
4. 输出 1-100 内的所有偶数
5. 求1-2+3-4+5 ... 99的所有数的和
6. 用户登陆(三次机会重试)
7:猜年龄游戏
要求:
    允许用户最多尝试3次,3次都没猜对的话,就直接退出,如果猜对了,打印恭喜信息并退出
    
8:猜年龄游戏升级版(选做) 
要求:
    允许用户最多尝试3次
    每尝试3次后,如果还没猜对,就问用户是否还想继续玩,如果回答Y或y, 就继续让其猜3次,以此往复,如果回答N或n,就退出程序
    如何猜对了,就直接退出 
    
    
9.for循环打印99乘法表

10.for循环打印金字塔:如下
    *
   ***
  *****
 *******
*********
1.使用while循环输出1 2 3 4 5 6     8 9 10
count = 0
while count < 10:
if count == 6:
    count += 1
    continue
count += 1
print(count,end=' ')

2.求1-100的所有数的和
sum=0
count=0
while count<100:
    count +=1
    sum+=count
print(sum)

3.输出 1-100 内的所有奇数
count=1
while count<100:
    if count % 2==1:
     print(count,end=' ')
    count+=1
    
    
4.输出 1-100 内的所有偶数 
count=1
while count<=100:
    if count % 2==0:
     print(count,end=' ')
    count+=1
    
5.求1-2+3-4+5 ... 99的所有数的和
sum=0
for i in range(1,100):
    if i%2==0:
        sum -=i
    else:
        sum+=i
print(sum)


6.用户登陆(三次机会重试)
id='1608210104'
pw='123456'
for i in range(3):
    id1 = input('Please your enter id:')
    pw1 = input('Please your enter password(您只有三次机会):')
    if id1==id and pw1==pw:
        print('you enter is True(你已登录成功)')
    else:
        print('you enter is False')
print('三次机会已用完')


7.猜年龄游戏
age='18'
for i in range(3):
    age1 = input('Please your enter age:')
    if age1==age:
        print("your answer is very True")
        break
    else:
      continue

8.猜年龄游戏升级版(选做)
要求允许用户最多尝试3次# 每尝试3次后,如果还没猜对,就问用户是否还想继续玩,如果回答Y或y, 就继续让其猜3次,以此往复,如果回答N或n,就退出程序# 如何猜对了,就直接退出
i=0
age=18
while i!=3 :
    age = input("Please your enter age:")
    if age== 18:
        print("your answer is True")
        break
    i += 1  # 计数器就加1

    if i == 3:  # 次数
        ret = input("是否还想玩(Y/N):")
        if ret == "Y" or ret =="y":

9.for循环打印99乘法表
for i in range(1,10):
    for j in range(1,i+1):
        print(f'{i}*{j}={i*j}',end='  ')
    print()
    
10.for循环打印金字塔:如下
for i in range(1,6):
        print(f"{'*'*(i+i-1): ^9}")    

Guess you like

Origin www.cnblogs.com/xichenHome/p/11203360.html