2--09 Python basic knowledge points 4.13

#!/usr/bin/env python

-- coding: utf-8 --

The first line of comment is to tell the Linux/OS X system that this is a Python executable program, and the Windows system will ignore this comment; the
second line of comment is to tell the Python interpreter to read the source code in UTF8 encoding, otherwise, you The Chinese output written in the source code may have garbled formatting:

We often output something like'Hello dear xxx! Your xx monthly bill is xx, and the balance is
a string like xx'

The content of xxx changes according to variables, so a simple way to format strings is needed. ```

For example:
print('Hello, %s'%'world')

print(‘Hi, %s, you have $%d.’ % (‘Michael’, 1000000))

What is said

Summary: %,%s,%d
% -----------------placeholder.
%s ---------------- represents a placeholder for a string.
%d-----------------Placeholder for integer

Common placeholder: %d %f %s

print(’%2d-%02d’ % (3, 1))
print(’%.2f’ % 3.1415926)

Summary:
%2d ----- means two placeholders, if the number is not enough, use spaces to stand
%02d----- also means two placeholders, if the number is not enough, use 0 to stand
% .2f ------Reserve two decimal places.

If you are not sure what placeholder should be used,
%s will always work, it will convert any data type to a string

print(‘Age: %s. Gender: %s’ % (25, True))

print(‘Age: %s. Gender: %s,score: %.5s’ % (25, True,89.786))

eg: 89.786
%.3s ------ means 3 positions, including decimal point, space, etc.
89.

%.3f ------ means three digits after the decimal point.
89.786

Sometimes, what should I do if the% in the string is a normal character?

At this time, you need to escape, use %% to represent a%
print('growth rate: %d %%'% 7)

7%

format()
Another way to format a string is to use the format() method of a string, which will replace the placeholders {0}, {1}... in the string with the passed parameters in turn, but this This way of writing is much more troublesome than %:
print('Hello, {0}, the result is improved by {1:.1f}%'.format('小明', 17.125)

Practicing
Xiaoming’s score has increased from 72 points last year to 85 points this year. Please calculate the percentage point of Xiao Ming’s performance improvement and display'xx.x%' in string format, with only one decimal place remaining: the display category is: hello, XXX, grades increased by xx.x%

s1 = 72
s2 = 85
r =
print(’???’ % r)

s1 = 72
s2 = 85
r = (s2-s1)/s1*100
name ='Xiaoming'
print('hello, %s, grades improved: %.2f %%'% (name,r))
print(' hello, %s, grades improved: %.4s %%'% (name,r))

Use list and tuple

It is also a built-in data type of python.

One of the built-in data types in Python is the list: list. List is an ordered collection, you can add and delete
elements in it at any time .
Insert picture description here
Syntax and definition:
a = []: []------square brackets indicate collection; [][]

len(classmates)-1: Indicates the index of the last element in the list.
L[3] = L[len(classmates)-1] Method of adding elements:
append(): Insert an element at the end of the list (a parameter)
insert(): Insert an element at the specified index. (Two parameters)
classmates = ['Zhang San','Li Si','Wang Wu','Xiao Ming']
print(len(classmates))

What is the length of classmates?

Exceeding the list index will report an error

IndexError: list index out of range

How to add'Xiaohong' to the list of classmates

classmates.append('Little Red')

append(): Add elements to the list. The methods in the list are called with the dot of'.'.

append(): The added element is at the end of the list.

#How to add to the specified position of the list, eg: add to the first position

classmates.append(0,'Xiaobai')

TypeError: append() takes exactly one argument (2 given)

#append(): Only one parameter can be accepted, we gave it two parameters, so it will report an error
classmates.insert(0,'小白')

insert(): Insert an element at the specified index.

Delete element:
#pop(): delete the last element in the list
#pop(index): delete the element at the specified index

classmates = ['Zhang San','Li Si','Wang Wu','Xiao Ming']
print(classmates) #Delete
element

classmates.pop()
print(classmates)
classmates.pop(1)
print(classmates)

List built-in methods:
pop(): delete the last element in the list
pop(index): delete the element at the specified index
append(value): insert an element at the end of the list (a parameter)
insert(index, value): at the specified index, Insert element. (Two parameters)

List insertion and deletion exercise:
fruit = ['apple','banana','orange']
1. Add'watermelon' to the end of the fruit list, and print out fruit
2. Add'strawberry' to the back of the apple and print out fruit
3 . Delete the last element of the fruit list, and then print out fruit
4. Delete the second element of the fruit list, and then print out fruit
5. Print out'Orange '
Answer:
1.fruit.append('Watermelon')
2.fruit .insert(1,'Strawberry')
3.fruit.pop()
4.fruit.pop(2)
5.print(fruit[2])

List:

list = [1,2,3,True,’小明’,None,3.124, [] ]

Two-dimensional list:

Insert picture description hereList: A data type, ordered collection, you can add or delete elements at will.

Tuple tuple: It is also a data type, ordered, and elements cannot be added or deleted, that is: tuple cannot be modified once it is initialized. There is no way to add and delete lists (there is no append(), insert(), pop(), etc.). Definition: L=(), others are the same as list, eg: index representation, calculating tuple length: len().
classmates = ('zhangsan','lisi','wangwu',''sdf”)
money=(3000,4000,5000)
The meaning of tuple Advantages: Once the tuple is initialized, it cannot be modified, and the code is safer. If possible, If you can have tuple instead of list, try to use tuple.

list = [[]]: Two-dimensional list.
tuple = ([1,2,3],[4,5,6],[7,8,9])
If there is a list in the tuple, you can change the elements of the list.
tuple = ([1, 2, 3], [4, 5, 6], [7, 8, 9])
print(tuple[0])
print(type(tuple[0]))
print(tuple[0] .append(122))
print(tuple)
6 --------- tuple[1][2]

The defect of tuple: When you define a tuple, the elements of the tuple must be determined at the time of definition.

eg:

t = (1,2)
t
(1,2) 1. Define an empty tuple: tuple = ()
2. Define a tuple with only one element: tuple = (1,)
2. Which of the following variables are tuple types:
 a = ()
 b = (1)
 c = [2]
 d = (3,)
 e = (4,5,6)
2. Conditional judgment statement

if…else

For example, enter the age of the user, and print out different categories according to the age.

age = 20
if age >= 18:
print('Your age is %s'% age)
print("adult")

According to python's indentation rules, if the if statement judges to be True, the two indented print statements are executed.

If the judgment of the if statement is False, it will not be executed. (Otherwise do nothing.)

You can also add an else statement to if, which means that if if is judged to be False, do not execute the content of if.

To execute the content inside the else.

age = 5
if age >= 18:
print('Your age is %s'% age)
print("Adult")
else:
print('Your age is %s'% age)
print("Under adults")
Note: Don’t miss the colon:

You can use else if abbreviation: elif

age = 16
if age>=18:
print(“adult”)
elif age >= 10:
print(“youth”)
elif age >=6:
print(“youth 1”)
else:
print(“kid”)

elif is the abbreviation of else if, and there can be multiple elifs.

Syntax
'''
if <condition judgment 1>:
<execution content 1>
elif <condition judgment 2>:
<execution content 2>
elif <condition judgment 3>:
<execution content 3>
else:
<execution content n>
'''
Explanation: Judging from top to bottom, if a certain judgment is True, then after executing the sentence corresponding to the judgment, the
remaining elif and else are ignored.

Guess you like

Origin blog.csdn.net/With__Hope/article/details/89282060