Python basic syntax
1. Identifier
- The first character must be a letter in the alphabet or an underscore _.
- The other parts of the identifier consist of letters, numbers and underscores.
- Identifiers are case sensitive.
- In Python 3, Chinese can be used as variable names, and non-ASCII identifiers are also allowed.
2. Python reserved words
[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]
3 escape character
- \t tab
- \n newline
- The character after \ represents the original meaning of the character
- r "" Everything in the quotation marks is the original meaning of the string
- f" "Format string constant.
4 placeholder
- %s string placeholder
- %f floating point placeholder
- %d integer placeholder
5. Basic data types
Standard data type
Number
Python3 supports int, float, bool, complex (plural). In Python 3, there is only one integer type int. The
built-in type() function can be used to query the type of object pointed to by a variable.
print(type(a), type(b), type(c), type(d))
print(type(a), type(b), type(c), type(d))
<class ‘int’> <class ‘float’> <class ‘bool’> <class ‘complex’>
In addition, isinstance can also be used to judge:
a = 111
isinstance(a, int)
True
The difference between isinstance and type is
- type() does not consider the subclass to be a superclass type.
- isinstance() will consider the subclass to be a superclass type.
5 + 4 # Addition
9
4.3-2 # Subtraction
2.3
3 * 7 # Multiplication
21
2/4 # Division, get a floating point number
0.5
2 // 4 # Division, get an integer
0
17% 3 # Take the remainder
2
2 ** 5 # Power
32
String (string)
str = 'Runoob'
print (str) # 输出字符串
print (str[0:-1]) # 输出第一个到倒数第二个的所有字符
print (str[0]) # 输出字符串第一个字符
print (str[2:5]) # 输出从第三个开始到第五个的字符
print (str[2:]) # 输出从第三个开始的后的所有字符
print (str * 2) # 输出字符串两次,也可以写成 print (2 * str)
print (str + "TEST") # 连接字符串
Output result
Runoob
Runoo
R
noo
noob
RunoobRunoob
RunoobTEST
String commonly used functions
- find() --> Check whether the string is included, and return the position of the string, if not, return -1
str="Hello World"
str.find("Hello") # 返回值:0
str.find("W") # 返回值:6, 这里需要注意下:空格也是一个字符。W前面有个空格,所以W位置是6
str.find("R") # 返回值:-1,并不包含在Hello World中,如果不包含返回-1
- index() --> Check whether the string contains the specified character, and return the starting index value, if not, an error will be reported
str.index("Hello") # 返回值:0
str.index("o") # 返回值:4
str.index("W") # 返回值:6
str.index("R") # 返回值:报错信息 ,因为R并不包含其中。 所以建议慎用,如果值不存在程序报错就完蛋了。
- len() --> Returns the length of the string, starting from 0
len(str) #返回值:10
- count() --> Collect the number of times the specified character appears in the string
str.count("o") 返回值:2, o字符在Hello World中存在两个。
# 也可以指定count()函数从某个位置开始查找。 语法为:count(" ",start,end)
str.count('o',5,10) 返回值:1, 原因:指定位置后会从索引5开始检索,以索引10结束。 5到10之间只存在一个'o'
str.count('o',4,len(str)) 返回值: 2,索引从4开始,到字符串结束。len(str)字符串长度
- replace() --> replace string
str.replace('hello','HELLO') # 把小写的hello替换为大写的HELLO
str.replace('W','B') # 把W替换为B
- split() string cutting
str.split('o') #以列表的形式返回["hell","w","rld"] ,hello world 里面的o被切割掉
- upper() --> convert all characters to uppercase
str.upper() #返回值为 HELLO WORLD
- title() --> convert the first letter to uppercase
str.title() #返回值:Hello World
- center() --> returns a new string with the original string centered and filled with spaces to the length and width
str.center(80) #返回值: ( Hello World ) 其字符串两头被空格填充
- join() --> Insert a specified character after the string to construct a new string
_str="_"
list=["I","Love","You"]
_str.join(list) # 返回值: I_Love_You 每个列表元素后面都插入一个下划线
- isspace() --> Detect whether the string contains only spaces, if it returns Trun, otherwise return False. In general, it is to judge non-empty verification
str=" "
strOne="早上好!"
str.isspace() # 返回trun
strOne.isspace #返回false
- isalnum() --> Check whether it contains only numbers or letters. Use: It can be used to judge the password. Generally, you cannot enter Chinese characters or spaces in the password.
strOne="a123"
strTwo="a 456"
strOne.isalnum() # 返回trun
strTwo.isalnum() # 返回false ,因为包含空格
- isdigit() --> Check if the character contains only digits, return Trun and False
str='123'
strone='a123'
str.isdigit() 返回trun
strone.isdigit() 返回false
- isalpha() --> Check whether the string contains only letters
str="abcd"
strone="123abacd"
str.isalpha() # 返回 trun
strone.isalpha() # 返回false
operation
a,b = 6, 8 I want a=8 b=6. What should I do? Realize in 2 ways
method one
a,b = 6, 8
print(f"a = {a}\tb = {b}")
c = a
a = b
b = c
print(f"a = {a}\tb = {b}")
a = 6 b = 8
a = 8 b = 6
Method Two
a,b = 6, 8
print(f"a = {a}\tb = {b}")
a, b = b, a
print(f"a = {a}\tb = {b}")
a = 6 b = 8
a = 8 b = 6
Complete string reverse order and statistics
- Design a program that requires only a string with a length of less than 31 to be entered, otherwise the user is prompted to re-enter
- Print out the length of the string
- Use slices to print out the string in reverse order
# 1
print("请输入一个字符串")
str1 = ''
s_input = True
while s_input:
str1 = input("input:")
if len(str1) >= 31:
print("请重新输入一个字符串")
else:
s_input = False
print(f"str1: {str1}")
# 2
print(f"字符串长度: {len(str1)}")
# 3
str2 = str1[::-1]
print(f"str2: {str2}")
It is required to enter the user name and password from the keyboard to verify whether the format complies with the rules. If not, print out the reason for the non-compliance, and prompt to re-enter
• The length of the user name is 6-20, and the user name must start with a letter. The
length of the password is at least 6 digits , Cannot be a pure number, cannot have spaces
import re
user_name = ''
pwd = ''
s_input = True
while s_input:
user_name = input("用户名:")
reg = '^.{6,20}$'
obj = re.match(reg, user_name)
pwd = input("密码:")
verify_user_name = user_name.isalpha() is False and obj is not None
verify_user_pwd = pwd.isdigit() is False and len(pwd) > 6
if verify_user_name and verify_user_pwd:
print(f"用户名: {user_name}")
print(f"用户名: {pwd}")
s_input = False
else:
print(f"用户名或密码不对")