Python study notes (2)

Action list

1. for loop: iterates over the entire list, doing the same thing for each element.

magicians.py

magicians=['alice','davida','caroliona']
for magician in magicians:
    print(magician)
for magician in magicians: Python takes a name from magicians, stores it in magician, and executes print(magician) for each name until the last element;

In the for loop, as many lines of code are included, each indented line of code is part of the indentation, and is executed once for each value of the list. The : sign after the for indicates that the next line is a looped line. Python judges the relationship between the code and the previous code according to the indentation;

After the for loop, the unindented lines of code are executed only once and not repeated.

magicians=['alice','davida','caroliona']
for magician in magicians:
    print(magician.title() + " , that was a grat trick!")
    print("I can not wait to see you next trick," + magician + "!")
The result of running is

Alice , that was a grat trick!
I can not wait to see you next trick,alice!
Davida , that was a grat trick!
I can not wait to see you next trick,davida!
Caroliona , that was a grat trick!
I can not wait to see you next trick,caroliona!
2. Create a list of values

a. The function range() generates a series of numbers

One difference: Python starts at the first value specified and stops before the second value;

numbers.py

for value in range(1,6):
    print(value)

operation result

1
2
3
4
5

b. The functions range() and list() create lists of values

The function range() can also specify the step size;

even_numbers=list(range(2,11,2))
print(even_numbers)
operation result

[2, 4, 6, 8, 10]
c.squares.py

squares=[]
for value in range(1,11):
    squares.append(value**2)
print(squares)
operation result

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

You can also use list comprehension, which is more concise;

squares=[value**2 for value in range(1,11)]
print(squares)
3. Use part of a list

a. Slice: part of the list; like range, stop before reaching the specified second element

If the starting index is not specified, the list is extracted from the beginning; if the ending index is omitted, the list is finally at the end;

players.py

players=['guoqing','xianghao','jiangnan','huangsong']
print(players[1:3])
print(players[:2])
print(players[:]

operation result

['xianghao', 'jiangnan']
['guoqing', 'xianghao']
['guoqing', 'xianghao', 'jiangnan', 'huangsong']
b. Traverse slices: use slices in for loops

players=['guoqing','xianghao','jiangnan','huangsong']
for player in players[1:3]:
    print(player)
print("They are the first two players on my team!")
operation result

xianghao
jiangnan
They are the first two players on my team!
c. Copy the list: Create a slice that contains the entire list, that is, omit the start index and end index at the same time;

You can't get two lists by simply assigning, because this syntax essentially tells Python to associate the new variable with the variable containing the list, both referring to the same value

foods.py

foods=['pizza','falafel','carot cake']
friend_foods=foods[:]
foods.append('carnoli')
friend_foods.append('ice_cream')
print("My favorite foods are:")
print(foods)
print("My friend favorite foods are:")
print(friend_foods)
operation result

My favorite foods are:
['pizza', 'falafel', 'carot cake', 'carnoli']
My friend favorite foods are:
['pizza', 'falafel', 'carot cake', 'ice_cream']
If it is just simple foods=friend_foods, the result will be different, you can try

4. Tuples

  Lists are great for datasets that may change during runtime, lists are modifiable, and tuples are great for creating a sequence of unmodifiable elements.

a. Tuples: Python calls values ​​that cannot be modified as immutable, and immutable lists are called tuples;

Tuples use parentheses instead of square brackets, and a for loop can be used to iterate over the values ​​in the tuple;

Attempts to modify tuple values ​​are prohibited.

dimensions.py

dimensions=(200,50)
for dimension in dimensions:
    print(dimension)
operation result

200
5
b. Modify tuple variables: Although you cannot modify the elements of the tuple, you can assign values ​​to the variables of the tuple, that is, redefine the entire tuple.

dimensions=(200,50)
for dimension in dimensions:
    print(dimension)
dimensions=(400,100)
for dimension in dimensions:
    print(dimension)
operation result

200
50
400
100
5. Set the code format

a. Indentation: PEP8 recommends four spaces per level of indentation

b. Blank lines: separate different parts of the program, blank lines can be used; blank lines will not affect code operation, but will affect readability


IF statement

Allows you to check the current state of the program and take appropriate action

1. Conditional test: The core of each if statement is an expression with a value of True or false, which is called a conditional test;

   If the conditional test value is True, python executes the statement immediately following the if, and ignores it if it is False.

 a. Python will be case-sensitive when checking. If the case is not important, it can be converted to lowercase.

>>> car = 'Audi'

>>> car.lower() == 'audi'

>>> car
'Audi'

 b. Use! = check for inequality

toppings.py

requested_topping = 'mushrooms'
if  requested_topping != 'anchovies' :
    print('Hold the anchovies')

operation result

Hold the anchovies

 c. Less than, less than or equal to, greater than, greater than or equal to compare numbers

>>> age = 19
>>> age < 21
True
>>> age <= 21
True
>>> age > 21
False
>>> age >= 21
False

d. Check for multiple conditions

  The keyword and both conditions are True, the result is True, and at least one of the keyword or is satisfied, the result is True.

>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 and age_1 >= 21
False
>>> age_1 = 21
>>> ( age_1 >= 21) and (age_0 >= 21)
True

To improve readability, each test may be enclosed in a pair of parentheses, but this is not required

e. Check if a specific value is in the list

requested_toppings = ['mushrooms','onions','pineapples']
>>> 'mushrooms' in requested_toppings
True

banned_users.py

banned_users = ['andrew','carolina','david']
user = 'marie'
if user not in banned_users:
    print(user.title() + ",  you can post a response if you wish.")

operation result:

Marie,  you can post a response if you wish

f. Boolean expressions

   Boolean expressions are often used to record conditions, either True or False.

game_active = True

2. if statement

 a. Simple if statement: there is only one test and one operation, if the test result is True, python executes the code behind the if statement

    In the if statement, the indentation function is the same as the for loop, the test passes, and all indented lines of code after the if are executed.

voting.py

age =19
if age > 18 :
    print("you are old enough to vote")
    print("Have you regeisted to vate yet")

operation result:

you are old enough to vote
Have you regeisted to vate yet

 b. if-else statement: The conditional test passes to perform one action, but fails to perform another action.

age = 17
if age >= 18 :
    print("You are enough to vote!")
    print("Have you registed to vote yet?")
else :
    print("You are too young to vote!")
    print("Please registed to vote as soon as you turn 18!")

operation result:

You are too young to vote!
Please registed to vote as soon as you turn 18!
c. if-elif-else structure: check more than two, it checks each test in turn, after the test passes


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325562482&siteId=291194637