day02 while loop and formatting

day02 while loop and formatting

Today Executive Summary

  1. while loop
  2. format
  3. Operators
  4. The initial coding

Yesterday Recap

  1. variable

    Variable naming convention:

    1. Numbers, letters and underscores
    2. You can not begin with a number
    3. You can not use Python keywords
    4. Variable names in Python are case sensitive
    5. Named variable to be descriptive with
    6. Variable names should not have Chinese characters and Pinyin
    7. Variable names Recommended wording:
      • Hump ​​body
      • Underline
  2. constant

  3. Basic data types

    • String
    • Integer
    • Boolean value
  4. Note

  5. User interaction

  6. Process Control

Today's detailed content

while loop

The basic structure of the while loop

Cycle is constantly repeated something. whileThat is, while the keyword loop.

The basic structure of the while loop:

while 条件:
缩进 循环体

Typical examples of the while loop:

print(1111)
while True:   # 死循环
    print("坚强")
    print("过火")
    print("鸡你太美")
    print("大碗宽面")
print(333)

In the above example, the first step, first printing 1111. The second step, enter the while statement to determine whilewhether the condition is true. whileAfter the statement is True, true, into the body of the loop. The third step is to print 坚强. The fourth five or six times, respectively, print out 过火, 鸡你太美and 大碗宽面. Content to run in the loop body is completed, the program returns to the while statement. The seventh step, continue to determine whilethe conditions after is true. Then continue into the body of the loop, reprint content. Subsequent return to the while statement. Because after the while statement the condition has always been True, and therefore the cycle, does not stand still, become an infinite loop. The last of 333never printed out.

1567757718914

break statement

Obviously, this cycle of death and can not meet the needs of our daily programming. If there is a way to limit the number of cycles will be very useful. Here, we can introduce the break statement. break can terminate the current cycle. If combined with conditional statements, it can be converted into an endless loop of limited circulation. E.g:

# 循环5次
count = 0
while True:  # 死循环
    count = count + 1  # 先执行 = 右边的内容
    if count == 5:
        print(count)
        break # 有限循环
        
运行的结果为:
5

In this example, we first define a variable countused to count, has become 计数器. In each cycle, countit will increase 1. When countequal 5, the if statement's condition was established, print out the current countvalue, running break, exit the loop. We successfully converted to an infinite loop limited circulation.

1567758395997

continue Statement

In addition break, while the cycle there is a very important statement continue. continueThe statement means that out of this cycle, the next cycle continues. In simple terms, then, continueit is disguised as the last line of code in the loop body. E.g:

count = 0
while True:  # 死循环
    count = count + 1  # 先执行 = 右边的内容
    if count == 5:
        print(111)
        continue  # continue 就是伪装成循环体中最后一行代码
    print(count)

Obviously, this is an endless loop. But when the counter countequal 5time will be printed once 111, and this time count, that is 5, will not be printed.

QQ picture 20190906145135

Conditions control loop

In addition to termination by using keyword break the cycle, we can control the number of cycles through the back while conditions:

count = 0
while count < 2:
    print(count)
    count = count + 1
    
打印出的结果为:
0
1

In the above example, the beginning counter countvalue is 0. Then run while the condition count < 2is true, then into the body of the loop. First, the countcontents of 0the print out, and then countincrease 1, to enter the next cycle. The second cycle is the same, print 1after countbecame 2, then back while the judge sentences. At this point, count < 2does not hold, the loop terminates.

QQ picture 20190906145142

while else statements

while语句也有判断的行为,所以也可以配合else语句使用。while else结构和if else结构很相似。只有当while后判断的条件不成立时,才会执行else中的语句。如果循环中没有break,else语句中的内容将在循环结束后执行;如果循环中有break,else语句中的内容有可能不被执行。观察下面两个例子:

print(222)
count = 0
while count < 3:
    print(count)
    count = count + 1
else:
    print(111)
# 运行结果: 222 0 1 2 111

print(222)
count = 0
while count < 3:
    print(count)
    count = count + 1
    break
else:
    print(111)
# 运行结果: 222 0

在第一个例子中,经过三次循环后,计数器count的值将增加到3。此时,条件count < 3不再满足,跳出循环,执行else语句,打印出111来。而第二个例子中,在第一次循环中就遇到了break,循环被强行终止,并没有再次判断count < 3,于是就不会进入到else中,111便打印不出来。

while循环小结

  • break:终止当前循环
  • continue:跳出本次循环,继续下次循环(就是伪装成循环体中最后一行代码)
  • continuebreak下方的代码都不会执行
  • while 循环可以通过条件控制循环的次数
  • while 语句可以和 else 语句配合使用,当 while后的条件不满足时,将会运行else中的语句。

格式化

有这样一个字符串:

msg = """
------info------
name:meet
age:18
sex:男
hobby:女
-------end------
"""

如果我们想让用户输入名字,年龄,性别和爱好,然后程序按照上面的格式给打印出来。从目前我们所学的知识,我们可以用这样的代码来实现:

a = "------info------"
b = "name:"
c = "age:"
d = "sex:"
e = "hobby:"
f = "-------end------"
name = input("name")
age = input("age")
sex = input("sex")
hobby = input("hobby")
print(a)
print(b + name)
print(c + age)
print(d + sex)
print(e + hobby)
print(f)

代码运行后就是这样的:
namealex
age18
sex男
hobby女
------info------
name:alex
age:18
sex:男
hobby:女
-------end------

%格式化

不过虽然我们实现了需求,但是太过繁琐。这里就可以用到格式化的方法。格式化,就是在字符串中需要自定义的位置放入占位符,然后通过给占位符提供数据,从而构建新的字符串。提供的数据需要和占位符一一对应,否则将会报错。

Python中常用的占位符有:

  • %s 字符串 :%s可以填充字符串也可以填充数字
  • %d|%i整型 : 必须填充数字
  • %% 转义:变成普通的%

有了格式化的方法,上面的例子我们就可以简化成这个样子:

name = input("name")
age = input("age")
sex = input("sex")
hobby = input("hobby")
a = "哈哈啊"
msg = """
------info------
name:%s
age:%s
sex:%s
hobby:%s
-------end------
"""
print(msg%(name,int(age),sex,hobby))

f-strings格式化

在Python 3.6及以后的版本中引入了一个新的f-strings方法格式字符串,把上面的格式化方法进一步简化,具体做法为:

msg = f"""
------info------
name:{input("name")}
age:{input("age")}
sex:{input("sex")}
hobby:{input("hobby")}
-------end------
"""
print(msg)

用大括号将需要格式化的位置标记出来,在大括号里面填入变量或者数据,构建成新的字符串。

其中,可以通过两个大括号{{}}来转义,表示普通的大括号。

运算符

比较运算符

比较运算符主要有六个:

  1. >:大于
  2. <:小于
  3. >=:大于等于
  4. <=:小于等于
  5. ==:等于
  6. !=:不等于

比较运算返回的值为TrueFalse

算术运算符

Python中的算术运算符有七个:

  1. +:加和
  2. -:相减
  3. *:相乘
  4. /:相除
  5. //:整除|地板除(向下取整)
  6. **:幂运算
  7. %:取余(模)

算术运算主要用于数字的计算。字符串也可以用+*进行拼接。

赋值运算符

赋值运算符为=。在Python中,为了输入简便,还从其中算术运算符中衍生出了七种赋值运算符:+=-=*=/=//=**=%=。它们的用法和含义如下:

a = 10
b = 2
b += 1  # b = b + 1
a -= 1  # a = a - 1
a *= 2  # a = a * 2
a /= 2  # a = a / 2
a //= 2 # a = a // 2
a **= 2 # a = a ** 2
a %= 2  # a = a % 2

逻辑运算符

逻辑运算符有三个:与(and,并且)、或(or)、非(not,不是)。

逻辑运算的优先级是() > not > and > or,查找顺序为从左向右。例如:

3>2 and 4>2 or True and not False and True
# 先运算比较
True and True or True and not False and True
# 再运算not
True and True or True and True and True
# 运算and
True or True
# 最后运算or
True

当数字之间进行逻辑运算时,有这样一套规则:

and数字进行逻辑运算时:
    两边都不为0和False时,选择and后边的内容
    两边都为假时,选择and前的内容
    一真一假选择假

or 数字进行逻辑运算时:
    两边都不为0和False时,选择or前边的内容
    两边都为假时,选择or后边的内容
    一真一假选择真

官方给出的运算规则是这个样子的:

操作 结果
x or y 如果x为假,选择y,否则选择x
x and y 如果x为假,选择x,否则选择y
not x 如果x为假,返回True,否则返回False

可以通过下面的示例来找到这些规律:

print(1 and 3)
print(0 and 8)
print(9 and 4)
print(False and 5)

成员运算符

在Python中,成员运算符有两个:

  • a in b: for determining whether a b,
  • a not in b: for determining whether or not a b,

Use specific examples:

name = "alex"
msg = input(">>>")
if name in msg:
    print(111)
else:
    print(222)
    
输出结果为:
>>>alexad
111
>>>alecxaa
222

Coding acquaintance

Common code sets:

  1. ascii:
    • Does not support Chinese
    • A character occupies 8
  2. gbk (contains ascii) GB Code:
    • English character occupies 8 bits (1 byte)
    • A Chinese character takes 16 bits (2 bytes)
  3. Unicode:
    • English: 4 bytes, 32-bit
    • Chinese: 4 bytes, 32-bit
  4. utf-8 (the most popular code sets):
    • English: 1 byte, 8 bits
    • Europe: 2 bytes, 16
    • Asia: 3 bytes, 24

Unit conversion:

  • 1 byte = 8 bits
  • 1Byte = 8 bits
  • 1024bytes = 1KB
  • 1024KB = 1MB
  • 1024MB = 1GB
  • 1024GB = 1TB # enough
  • 1024TB = 1PB

Guess you like

Origin www.cnblogs.com/shuoliuchina/p/11494919.html