In the process of coding our work , If the logic of a piece of code is complex , It's not particularly easy to understand , You can add notes appropriately , To help yourself Or other coders interpret the code .
Comments are for programmers to see , In order to make it easy for programmers to read the code , The interpreter ignores comments . Use your familiar language , It is a good coding habit to annotate the code properly ( Be careful to deduct salary without writing notes ).
With # start ,# Everything on the right is for illustration , It's not really a program to execute , To assist in explaining .
# Output hello world
print("hello world")# Output hello world
Shift + 3
, perhaps Ctrl + ?
Can be generated # Number
Comments are usually written at the top of the code , Try not to follow the code . Keep good coding habits
With ‘’’ Start , And ‘’’ end , We call it multiline annotation .
''' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The Buddha bless never BUG Buddha says : Office room in office building , Programmers in the office ; Programmers write programs , And program for drinks . Drunk only sit on the Internet , Drunken to sleep under the net ; Drunk and sober day after day , Online next year after year . I wish I could die in the computer room , Don't bow to the boss ; Mercedes Benz and BMW , Bus self programmer . People laugh at me for being crazy , I laugh at my life ; No beautiful girls in the street , Which one belongs to the programmer ? '''
For reuse , And often need to modify the data , Can be defined as a variable , To improve programming efficiency .
The syntax for defining variables is : Variable name = A variable's value
.( there = The function is to assign values .)
After defining a variable, you can use the variable name to access the variable value .
# Define a variable to represent this string . If you need to modify the content , Just modify the value corresponding to the variable
# Be careful , Variable names do not need to be enclosed in quotation marks
weather = " It's a beautiful day "
print(weather)
print(weather)
print(weather)
explain :
1) A variable is a variable , It can be modified at any time .
2) The program is used to process data , Variables are used to store data .
stay Python In order to meet different business needs , Also divide the data into different types .
Focus on :int、float、String、List
python There is no double type , either char Character type
Tuple: and List similar , A collection of data represented by one data
Dictionary: It is similar to the function of dictionary in reality
# int
money = 100
print(100)
# float
price = 99.9
print(price)
# boolean
# Variables should be known by name , Don't use Chinese pinyin , Will be looked down upon
# male True, Woman False
sex = True
print(sex)
# String
# Single or double quotation marks can be used for strings , But it must appear in pairs
str = 'hello '
str2 = 'world'
print(str + str2)
# Nesting of single and double quotation marks
str3 = '" ha-ha "'
str4 = "' ha-ha '"
print(str3)
print(str4)
# Single and double quotation marks match closely , The same cannot be nested
# str5 = "" Hey "" Incorrect usage
# list
name_list = [' Zhang Fei ', ' Guan yu ']
print(name_list)
# obtain list Subscript is 0 String , Subscript from 0 Start calculating :0、1、2、3....
print(name_list[0])
# tuple
age_tuple = (18, 19, 20)
print(age_tuple)
# dictionary Dictionaries
person = {
'name': ' Zhang San ', 'age': 18}
print(person)
stay python in , Just define a variable , And it has data , Then its type has been determined , We don't need developers to take the initiative To explain its type , The system will automatically identify . That is to say, when using " Variable has no type , Data has type ".
str5 = "hello"
print(type(str5))
#<class 'str'>
#str yes string An abbreviation of
If you want to view the data type stored in a variable temporarily , have access to type( The name of the variable ), To see the data type stored in the variable .
In computer programming languages , identifier ( Or variables ) Is the name used by the user when programming , Used to give variables 、 Constant 、 function 、 Statement block and so on , To establish a relationship between the name and the use .
Identifiers are made up of letters 、 Underline and numbers make up ($ And so on ), And Cannot start with a number .
Case sensitive .
Out of commission keyword .
Make a meaningful name , Try to see what it means at a glance ( Improve code availability Readability ) such as : name It's defined as name , Define what students use student
# The correct sample
name = " Zhang San "
age = 18
# Wrong naming
a = " Zhang San "
b = 18
1) Little hump nomenclature (lower camel case): The first word begins with a lowercase letter ; The first letter of the second word is capitalized , for example :myName、aDog
2) Big hump nomenclature (upper camel case): The first letter of each word is capital , for example :FirstName、LastName.
3) Another naming method is to underline “_” To connect all the words , such as send_buf.
Python The command rules of follow PEP8 standard
Some identifiers with special functions , This is the so-called keyword .
keyword , Has been python Official use of , Therefore, developers are not allowed to define identifiers with the same name as keywords .
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
Convert to an integer
print(int("123")) # 123 Convert a string to an integer
print(int(123.78)) # 123 Convert an integer to a floating point number
print(int(True)) # 1 Boolean value True Converting to an integer is 1
print(int(False)) # 0 Boolean value False Converting to an integer is 0
# The conversion will fail in the following two cases
''' 123.456 and 12ab character string , Both contain illegal characters , Cannot be converted to an integer , Will report a mistake print(int("123.456")) print(int("12ab")) '''
Convert to floating point number
f1 = float("12.34")
print(f1) # 12.34
print(type(f1)) # float Will string "12.34" Convert to floating point number 12.34
f2 = float(23)
print(f2) # 23.0
print(type(f2)) # float Convert an integer to a floating point number
Convert to string
str1 = str(45)
str2 = str(34.56)
str3 = str(True) #True
print(type(str1),type(str2),type(str3))
Convert to Boolean
print(bool(1)) #True, Not 0 All the integers of are True
print(bool(' ')) #True, So is the space True
print(bool(0.1)) #True, Not 0 All floating-point numbers are True
# The following situations are False
print(bool(0)) #False
print(bool(0.0)) #False
print(bool('')) #False, All strings without content are False
print(bool("")) #False
print(bool({
})) #False, As long as there is data in the dictionary , Cast to bool, Just go back to True
print(bool([])) #False, As long as there is data in the list , Cast to bool, Just go back to True
print(bool(())) #False As long as there is data in the tuple , Cast to bool, Just go back to True
tuple1 = (0)
print(bool(tuple1)) #False
tuple2 = (0, 0)
print(bool(tuple)) #True
With a=10 ,b=20 For example, calculate
Be careful : In mixed operation , The priority order is : ** higher than * / % // higher than + - , To avoid ambiguity , It is recommended to use () To handle shipping
Operator priority . also , When different types of numbers are mixed , Integers will be converted to floating-point numbers for operation .
>>> 10 + 5.5 * 2
21.0
>>> (10 + 5.5) * 2
31.0
Be careful : stay python in , + You can splice strings only when both ends are strings , Data that is not a string type can be passed through str() Strong to string , Splicing again
Multiplication of strings , Is how many times the string is repeated
print('11' + '22') #1122
print(' hello world' * 3) # hello world hello world hello world
# Assign values to multiple variables at the same time ( Use the equal sign to connect )
>>> a = b = 4
>>> a
4
>>> b
4
>>> # Multiple variable assignments ( Separated by commas )
>>> num1, f1, str1 = 100, 3.14, "hello"
>>> num1
100
>>> f1
3.14
>>> str1
"hello"
# Example :+=
>>> a = 100
>>> a += 1 # Equivalent to execution a = a + 1
>>> a
101
# Example :*=
>>> a = 100
>>> a *= 2 # Equivalent to execution a = a * 2
>>> a
200
# Example :*=, Operation time , The expression to the right of the symbol calculates the result first , And then with the value of the variable on the left
>>> a = 100
>>> a *= 1 + 2 # Equivalent to execution a = a * (1+2)
>>> a
300
The following hypothetical variables a by 10, Variable b by 20:
Interview questions : What is the output of the code , Why is there such an output .
a = 34
a > 10 and print('hello world') # Output
a < 10 and print('hello world') # No output
a >10 or print(' Hello world ') # No output
a <10 or print(' Hello world ') # Output
reflection :
Short circuit problem of logic operation
Why is the rule when logic and operation and logic or operation take value .
and and or Short circuit effect
age = 10
print(" I this year %d year " % age)
name = " Zhang San "
print(" My name is %s, Age is %d" % (name, age))
stay Python in , The way to get the data input by keyboard is to use input function
password = input(" Please input a password :")
print(' The password you just entered is :%s' % password)
Be careful :
input() What is put in the parentheses of is the prompt information , A simple tip for users before getting data
input() After getting the data from the keyboard , It will be stored in the variable to the right of the equal sign
input() Any value entered by the user will be treated as a string
if Sentences are used to make judgments , Its use format is as follows :
if The conditions to judge :
When conditions are met , What to do
# Example
if age >= 18:
print(" I'm an adult ")
A small summary :
if The function of the judgment : That is, when you meet a certain Condition to execute the code block statement , Otherwise, code block statements are not executed .
Be careful :if The next line of code is indented with a tab key , perhaps 4 A space .PyCharm Can press Ctrl + Alt + L Direct format code
if-else The use format of
if Conditions :
The operation when the condition is satisfied
else:
Operation when conditions are not met
age = 18
if age >= 18:
print(" You are an adult ")
else:
print(" You're a minor ")
age = int(input(" Please enter age :"))
if age >= 18:
print(" You are an adult ")
else:
print(" minors ")
elif The function of
if xxx1:
Thing 1
elif xxx2:
Thing 2
elif xxx3:
Thing 3
explain :
When xxx1 When satisfied , Do something 1, And then the whole if end
When xxx1 When not satisfied , So judge xxx2, If xxx2 Satisfy , Then do something 2, And then the whole if end
When xxx1 When not satisfied ,xxx2 Not satisfied , If xxx3 Satisfy , Then do something 3, And then the whole if end
Example :
score = int(input(" Please enter the score "))
if score >= 90:
print(" good ")
elif score >= 80:
print(" good ")
elif score > 60:
print(" pass ")
else:
print(" fail, ")
stay Python in for Loop can traverse any sequence of items , Such as a list or a string .
fo The format of the loop
for Temporary variable in Iteratable objects such as lists or strings :
Code executed when the loop meets the conditions
for The use of recycling
for s in "hello":
print(s)
range Can generate numbers for for Loop traversal , It can pass three parameters , respectively start 、 End and step .
for i in range(5):
print(i)
a_list = [' Zhang San ', ' Li Si ', ' Wang Wu ']
for i in a_list:
print(i)