python basis of branch and loop

A, Python branch (condition) statement 2

The computer was able to automate tasks, because they can do it conditional.

Thinking 1: Existing a demand, for example, enter the user's age, print different content depending on age.

![370AA951-25BC-4374-B07E-4D6BA76BC694](/Users/zhangjiao/Library/Containers/com.tencent.qq/Data/Library/Application Support/QQ/Users/1838887021/QQ/Temp.db/370AA951-25BC-4374-B07E-4D6BA76BC694.png)

if 判断条件:
    执行语句...
else:
    执行语句...

Analyzing the condition of the if statement can be> (greater than), <(less than), == (equal),> = (greater than or equal), <= (less than or equal) to represent the relationship.

Requirement 1: If older than 18, has become in the print, otherwise minor

age = 17
if age> 18:
    print("已成年")
else:
    print("未成年")

Demand 3: If the age is 18 or less, print juvenile, age greater than 18 and less than or equal to 25, print the youth, greater than 25 is less than or equal to 40, print the prime of life, greater than 40, to print your menopause. . .

We need multiple similar to the above judgment, we can use the following ways to solve

if 条件判断1:
    语句1
elif 条件判断2:
    语句2
...
elif 条件判断n:
    语句n
else:
    语句

Note: elif is an abbreviation else if, there can be multiple elif.

Therefore, according to the above requirements, our code can be written

age = 34
if age <= 18:
    print("少年")
elif age <= 25:
    print("青年")
elif age <= 40:
    print("壮年")
else:
    print("更年期到啦")

if the statement has a feature, which is down from the judge, if the judge is on a True, the corresponding statement after the judgment execution, it ignored other elif and else.

if the judge sentences can also shorthand:

if x:
   print("True")

As long as x is a non-zero value, non-empty string, a non-null List, it is determined is True, False otherwise

Nested if statements

Demand: Now enter a number, whether or not he is an even number greater than 10

If you want to solve these needs, we might need two statements to determine whether the first number determines whether the input is greater than 10, and the second is the judgment on the basis of first come up determination whether this number is even.

Simply put, that is, in a nested if statement then the if statement, the effect is as follows:

grammar:

if expression 1:

Statement 1

if Expression 2:

Statement 2

num = 20
if num > 10:
    if num % 2 == 0:
        print(num)

Note: From the perspective of grammar that nested layers is not limited, however, from the readability and maintainability of the code, the best nesting depth should not exceed three.

if the magic usage (operation trinocular)

Analyzing conditions result1 if else result2

If the condition is true then the output result1, otherwise the output result2

>>> x = 10
>>> y = 20
>>> x if x > y else y
20

Second, the while loop

Consideration 1: find the value of 1 + 2 + 3 + ... + 10.

A solution to the problem: the use of adding learned before

>>> num = 1 + 2 + ...+10
>>> print(num)

Consideration 2: seeking value + 2 + ... + 13 + 100

>>> num = 1 + 2 + 3 + ... + 100
>>> print(num)

This method is very cumbersome, in order to allow the computer to calculate repeat calculations thousands of times, we need to loop. In python while statement for executing a program loop, i.e., under certain conditions, implementation of certain program loop, the same processing tasks need to repeat the process, which is substantially in the form:

while 判断条件:
    执行语句...

Execute statement may be a single statement or statement block, the determination condition may be any expression, in any non-zero value, or a non-empty (null) are both true, when the determination condition is false, the loop ends.

![CF7B3BB0-6FFC-4886-AE1D-55AEA44378EE](/Users/zhangjiao/Library/Containers/com.tencent.qq/Data/Library/Application Support/QQ/Users/1838887021/QQ/Temp.db/CF7B3BB0-6FFC-4886-AE1D-55AEA44378EE.png)

2. Solution two: We use the cycle way to solve the above problems

sum = 0
num = 1
while num < 101:
    sum += num
    num += 1
print(sum)

In the above cycle, num <101 determines statements, when the result is True when it continues the loop body block, otherwise loop out.

The death while cycling

Infinite loop of opportunity: if the expression is always true when there will be an infinite loop

while 1:
    print("I am very good !")
The while loop else

In python, while ... else else block executed in the loop condition is false

count = 0
while count < 5:
    print("%d is less than 5"%count)
    count += 1
else:
    print("%d  is not less than 5"%count)
while the simple statement set

If your while loop in only one statement, you can write the statement and while on the same line

grammar:

while conditions: statement

while True: print("you are a good man")

Third, the end of the loop

Use 1.break statement

In the cycle, you can use the break statement to exit the loop early.

For example: Originally circulation print the numbers 1 to 100, but now I want to end early, when the number is greater than 10, the end of the print cycle.

n = 1
while n <= 100:
    if n > 10:
    #当n = 11时,条件满足,执行break语句
        break
    print(n)
    n += 1
print("循环结束")
Use 2.continue statement

During the cycle, you can continue statement skips the current cycle, the next cycle started directly.

n =  0
while n < 10:
    n += 1
    print(n)

1 to 10 can be printed out by the above procedure, but if we only want to print the odd-numbered, can be used to skip the continue statement cycle:

Reflection three: Print odd within 1 to 100

num = 1
while num <= 100:
    if num%2 == 0:
        continue
    print(n)
Use 3. pass sentence

The pass statement is an empty statement, in order to maintain the integrity of the program structure

pass without doing anything, generally used as a placeholder sentence

if True:
    pass
else:
    print("hello")

Fourth, the for loop

python cycle, there are two, one is we are talking about before the while loop, the other is for ... in loop, followed by the iterative out in the elements list or tuple or string.

name = ['lili','Bob','Tracy']
for name in names:
    print(name)

The implementation of this code, in turn print out every element of names

lili
Bob
Tracy

So for x in ... the cycle is to bring each element of the variable x, then execute the indented block statement.

Calculating integers of 1 to 10 and can be made variable by a cumulative sum:

sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
    sum = sum + x
print(sum)

To compute the sum and 1 to 100, from a 100 bit difficult to provide in python a range () function, can generate a sequence of integers, and then through the list () function can be converted to List, such as the range (5) generated sequence is an integer of from 5 to less than zero.

sum = 0
for x in range(100):
    sum += x
print(sum)

for recycling else statement

And while ... else similar, else will be performed with the loop after executing the normal

for i in range(10):
    print(i)
else:
    print("********")
range function

The range function creates an iterator object is generally used in a for loop

Function syntax:

range([start,] stop[, step])

Parameter Description:

1.start:计数从start开始,默认从0开始,例如:range(5)等价于range(0, 5)
2.stop:计数到stop结束,但不包括stop。例如:range(05)的取值为[053.step:步长,默认为1,例如range(05) 等价于range(0, 5, 1)

The function returns an iterator object, you can get a list of integers in this iterables

#使用list函数,可以从可迭代对象中获取整数列表
>>> list(range(5))
[0, 1, 2, 3, 4]

Nested loop

We can loop in nested loop

Requirements: print multiplication table

'''                          行    列
1x1=1                        1     1
1x2=2   2x2=4                2     2
1x3=3   2x3=6   3x3=9        3     3
...

总结:列数随着行数的变化而变化,列数的最大值和行数相等。
'''
i = 1
while i <= 9:
    j = 1
    while j <= i:
        sum = j*i
        print("%dx%d=%d"%(j,i,sum),end="    ")
        j += 1
    print("")
    i += 1
'''
打印结果:
1x1=1    
1x2=2    2x2=4    
1x3=3    2x3=6    3x3=9    
1x4=4    2x4=8    3x4=12    4x4=16    
1x5=5    2x5=10    3x5=15    4x5=20    5x5=25    
1x6=6    2x6=12    3x6=18    4x6=24    5x6=30    6x6=36    
1x7=7    2x7=14    3x7=21    4x7=28    5x7=35    6x7=42    7x7=49    
1x8=8    2x8=16    3x8=24    4x8=32    5x8=40    6x8=48    7x8=56    8x8=64    
1x9=9    2x9=18    3x9=27    4x9=36    5x9=45    6x9=54    7x9=63    8x9=72    9x9=81    
'''

expand:

By default, use print ( "") will automatically print line breaks, line breaks if you need to change you need to add end property that is print () in print ( "", end = ""), so put line breaks changed to spaces

Five, String string

1. What is the string

String is in single quotes, or any text in double quotes, a character string composed of several arbitrary characters

2. Create a string
str1 = "hello world"
str2 = 'you are good'
3. String operations
3.1 String link

3.1.1 Use the plus link

#字符串的链接,通过“+”进行链接
s1 = 'welcome'
s2 = 'to guangzhou'
print(s1 + s2)

Note: string + number, this being given, not adding different types of

3.1.2 "," [link] tuple type

s1 = 'hello'
s2 = 'world'
print(s1, s2)
#使用“,”链接的时候,在“,”的位置会产生一个空格

3.1.3 Using% formatted link

s1 = 'hello'
s2 = 'world'
print("%s %s"%(s1, s2))

3.1.4 use the join function link

s1 = ['hello', 'world']
print("".join(s1))

Note:. "" Join () internal function only need to pass a parameter.

3.2 repeatedly output string
#重复输出字符串,通过乘法的方式实现
s3 = 'good'
print(s3 * 3)
3.3 Gets a string of characters
#通过索引的方式实现
#索引:给一个字符串中的字符从0开始编号,也成为下标
#索引的取值范围:[0,str.length-1]
#访问方式: 变量名称[索引]
str3 = 'good'
print(str3[0])
#索引值还可以从-1开始,-1代表倒数第一个字符
print(str3[-1])
3.3 interception string
# 通过下标截取字符串
str1 = "hello world"
print(str1[3:6])
#注意:截取字符串的范围是str[start : end] 它是一个前闭后开的区间[start,end)
#如果n的值超过了字符串的最大长度,则仍然截取原下标的长度

#从开头截取到指定索引之前[0,5)
print(str1[:5])

#从指定截取到结尾[4,str1.length)
print(str1[4:])

#注意在使用str[start : end]来截取字符串的时候,若start不写默认从第一个字符开始
#若end不写,则默认到最后一个字符结束
3.5 determine whether to include the specified character
#判断字符串中是否包含某指定字符串
str4 = "you are a good boy"
print("good" in str4)
#若包含有则返回True否则为False
3.6 formatted output
#通过%来改变后面的字母或者是符号的含义,%被称为占位符
# %s:格式化字符串
# %d:格式化整数
# %f:格式化浮点数,可指定小数点后的精度
age = 18
name = "丽丽"
weight = 45.5
print("my name is %s , I am %d year old and my weight is %.2f kg"%(name, age, weight))
#注意:%.nf表示精确到小数点后n位,会四舍五入
4. The common function on the string
4.1 eval(str)

Function: string str as valid and returns an expression to evaluate the results.

Can list, tuple, dict, set and string interconversion

>>>num1 = eval('123')
>>>print(num1)
123

>>>num2 = eval("[1, 2, 3]")
>>>print(num2)
[1, 2, 3]

>>> num3 = eval("12-3")
>>> print(num3)
9
4.2 len (str)

Function: Returns the (number of characters) of the current string length

>>> len("you are good")
12
4.3 str.lower()

Function: Returns a string of uppercase letters lowercase string

>>> str = "Hello World"
>>> print(str.lower())
hello world

Note: This method does not change the original character

4.4 str.upper()

Function: Returns a string in lowercase to uppercase character string

>>> str = "Hello World"
>>> print(str.upper())
HELLO WORLD
4.5 str.swapcase ()

Function: Returns a string of uppercase letters lowercase letters, lowercase letters to uppercase string

>>> str = "Hello World"
>>> print(str.swapcase())
hELLO wORLD
4.6 str.capitalize()

A return to the first letter capitalized, other lowercase string

>>> str = "Hello World"
>>> print(str.capitalize())
Hello world
4.7 str.title()

A return of each word capitalized string

>>> str = "Hello World"
>>> print(str.title())
Hello World
4.8 str.center(width[, fillchar])

Function: Returns a string that specifies the width of the center, as a string filled FillChar default spaces

>>> str = "Hello World"
>>> print(str.center(50,"*"))
*******************Hello World********************
4.9 str.ljust (width [, fillchar])

Function: Returns a string that specifies the width of the left-justified, fillchar filled characters. The default padded with spaces

>>> str = "Hello World"
>>> print(str.ljust(50,"*"))
Hello World***************************************
4.10 str.rjust(width[, fillchar])

Function: Returns a string that specifies the width of the right-aligned, FillChar filled characters, default padded with spaces

>>> str = "Hello World"
>>> print(str.rjust(50,"*"))
***************************************Hello World
4.11 str.zfill(width)

Function: Returns a string of length to width, the original string right alignment, leading zero

>>> str = "Hello World"
>>> print(str.zfill(50))
000000000000000000000000000000000000000Hello World
4.12 str.count(str 【,start】【, end】)

Function: Returns the number of string str occurs, you can specify a range, if not specified, the default start to finish, when the match is case-sensitive.

>>> str = "Hello World"
>>> print(str.count("hello", 0 , 10))
0
4.13 str.find(str1【, start】【, end】)

Function: detecting left to right str1 string is contained in the string, the range can be specified, the default start to finish.

The return is the first time the index started, if no inquiry to -1

>>> str = "Hello World"
>>> str1 = "llo"
>>> print(str.find(str1, 0 , 10))
2
4.14 str.rfind(str1【, start】【, end】)

Function: Similar to str.find (), but from the beginning to find the right

>>> str = "Hello World"
>>> str1 = "llo"
>>> print(str.rfind(str1, 0 , 10))
2
4.15 str.index(str1[, start = 0] ,[ end = len(str)])

Function: Similar to find (), and find () is different, if str1 that does not exist when it will report an exception

>>> str2 = "Hello World"
>>> str1 = "hello"
>>> print(str2.index(str1, 0 , 10))
ValueError: substring not found
4.16 str.lstrip()

Function: string left truncated string specified, the default deletion whitespace (including '\ n', '\ r', '\ t', '')

>>> str = '**** you are very good'
>>> print(str.lstrip())
>>> print(str.lstrip())
**** you are very good
>>> print(str.lstrip("*"))
 you are very good
4.17 str.rstrip ()

Function: truncated string specified string right, the default deletion whitespace (including '\ n', '\ r', '\ t', '')

>>> str = '**** you are good****'
>>> print(str.rstrip())
**** you are good****
>>> print(str.rstrip("*"))
**** you are good
4.18 str.strip()

Function: truncated string left and right sides of the specified string, the default deletion whitespace (including '\ n', '\ r', '\ t', '')

>>> str1 = "      hello world     "
>>> str1.strip()
'hello world'
4.18 string.split(str=”“, num=string.count(str))

Function: a delimiter str slice string, if there is the specified value num, num only separated substrings

str - separator, default for all null characters, including spaces, linefeed (\ n-), tab (\ t) and the like. num - the number of divisions

>>> str1 = "hello you are good"
>>> str1.split()
['hello', 'you', 'are', 'good']
>>> str1.split(" ",2)
['hello', 'you', 'are good ']
Published 31 original articles · won praise 4 · Views 3522

Guess you like

Origin blog.csdn.net/qq_29074261/article/details/80016657