Table of contents
+ concatenated string disadvantages
Format symbols commonly used in python
Set type annotations for variables
Use type annotations in annotations
Type annotations for formal parameters
Type annotations for return values
data input
foreword
- We can get input from the keyboard using the input() statement
- We can use a variable to accept the keyboard input data obtained by the input statement
Syntax: accept variable =input("prompt statement")
name=input("请告诉我你是谁:")
print("我的名字是:%s" % name)
Note: No matter what data you write in the input statement, it will treat the data as a string.
data output
Function: output the variable content to the console
Newline output: print(data 1, data 2, data 3)
Output without wrapping: print(data 1, data 2, data 3, end="")
name="cjc"
age="24"
print("名字为",name,"年龄为",age)
print("---")
print("名字为",name,"年龄为",age,end="")
print("---")
Note: This output statement is often mixed with format strings.
string
String: Also known as text, it is composed of any number of characters, such as Chinese, English, various symbols, numbers, etc. so called string
Three ways to define strings
- Single quote definition method: name='cjc'
- Double quote definition method: name="cjc"
- Three quotation mark definition method: name="""cjc"""
Note: The three-quote definition method is the same as the writing method of multi-line comments, and also supports newline operations. If you accept it with a variable, it is a string; if you do not accept it with a variable, it will be used as a multi-line comment.
name1='cjc'
print(type(name1))
name2="cjc"
print(type(name2))
name3="""
cjc"""
print(type(name3))
Result: The execution results are all string types
nested quotes
- Single quotation mark definition method, can contain double quotation marks
- Double quotes definition method, can contain single quotes
- You can use the escape character (\) to deactivate the quotation marks and turn them into ordinary strings
concatenation of strings
Preface: If we have two string literals, we can concatenate them into a string, which can be completed by +
print("我是个"+"大帅哥")#我是个大帅哥
However, the simple splicing of two string literals seems stupid, and splicing is generally used between literals and variables or between variables and variables
name="cjc"
print("my name is "+name+" we could learn python each other")
Notice:
- Strings cannot be concatenated by + and integers and other types
- + Splicing is relative to multiple parameters connected by commas, each parameter connected by commas will have a space after splicing
string formatting
+ concatenated string disadvantages
- There are too many variables, it is too troublesome to stitch together
- Strings cannot be concatenated with other types
Understanding: First occupy a position (the placeholder is usually represented by %), and later a variable will come, I will turn it into a string and put it in the booth position
class_num=57
avg_salary=16781
message="python是大数据学科,北京第%d期,毕业平均工资:%s" % (class_num,avg_salary)
print(message)
Notice:
- There can be multiple variables, enclosed in parentheses, separated by commas, and the following parameters correspond to the previous placeholders one by one
- %s means that the following variables will replace the previous placeholders in string mode
- Numbers can also be occupied by %s, here is to convert numbers into strings
Format symbols commonly used in python
Formatting precision control
Preface: As shown in the figure below, 19.99 becomes 19.990000
We can use the auxiliary symbol "mn" to control the width and precision of the data
- m: Width control, requires a number (rarely used), if the width is set to be smaller than the number itself, then this setting will not take effect
- .n: Control the precision of the decimal point, the requirement is a number, and the decimal will be rounded
example
- %5d: means to control the width of the integer to 5 digits, such as the number 11, if it is set to 5d, it will become: [space][space][space]11, use these three spaces to make up the width
- %5.2f: Indicates that the width is controlled to 5, and the decimal point precision is set to 2
- %.2f: Indicates that the width is not limited, and only the precision of the decimal point is limited to 2
string quick format
Syntax: f"{variable1}{variable2}"
Note: f is actually the meaning of format
name="传智播客"
set_up_year=2006
stock_price=19.9
print(f"我是{name},我成立于:{set_up_year}年,我今天的股价是:{stock_price}")
Quick Format Features
- ignore the type
- No precision control (suitable for quick use when there is no requirement for precision)
format the expression
expression: a code statement with a definite execution result
Specific case
string size comparison
Preface: In the program, the characters used in the string have their corresponding ASCII values, and each character can correspond to the code value of the previous number. The comparison of strings is based on the comparison of the size of the digital code value
string comparison method
Understanding: Strings are compared bit by bit, that is, they are compared one by one. As long as one bit is larger, the whole will be larger
variable type annotation
Meaning: Where data interaction is involved in the code, provide data type annotations (displayed descriptions)
The main function
- Help third-party IDE tools (such as pycharm) perform type inference on code, and assist in code hinting
- Help developers type annotations on variables themselves
support location
- variable type annotation
- Annotations for function method parameter lists and return value types
Set type annotations for variables
Normal setting method
Syntax 1: variable:type
Use type annotations in annotations
Syntax 2: #type: type
Note: Type annotations are only suggestive, not decisive, and will not affect the operation of the program
function type annotation
Type annotations for formal parameters
def 函数/方法名(形参名:类型,形参名:类型):
函数体
Type annotations for return values
def 函数/方法名(形参名:类型,形参名:类型) -> 返回值类型:
函数体
def add(x:int,y:int):
return x+y
def func(data:list) ->list:
return data
Union type annotation
Note: Union annotations can be defined using the union type, and the module Union needs to be imported when using it
Syntax: Union[type,...,type]
from typing import Union
my_list:list[Union[int,str]]=[1,2,"hello"]
my_dict:dict[str:Union[str,int]]={"name":"lili","age":18}
def func(data:Union[int,str])->Union[int,str]:
pass