Day02 get started quickly
Course objective: learn the most basic grammar knowledge of python, and quickly realize some simple functions with code
Course overview:
- Initial code (codebook)
- Initial programming experience
- output
- Initial data type
- variable
- notes
- input
- Conditional statement
1. Code (password book)
All data in the computer is essentially stored in a combination of 0 and 1.
In the computer, the Chinese memory will be converted into 010101... And finally stored on the hard disk.
In the computer, there is a concept of coding (codebook).
martial -> 01111111 00011010 010110110 Rich -> 01001111 10010000 001110100 Qi -> 11111111 00000000 010101010
There are many kinds of codes in computers.
Each code has its own set of codebook and maintains its own set of rules, such as: utf-8 code: martial -> 01111111 00011010 010110110 Rich -> 01001111 10010000 001110100 Qi -> 11111111 00000000 010101010 gbk code: martial -> 11111111 00000010 Rich -> 01001111 01111111 Qi -> 00110011 10101010 Therefore, when using different encoding to save the file, the 0 stored in the file on the hard disk/1 It's also different.
matters needing attention:
To save a file in the form of a code, you need to open the file with this code!
If used UTF-8 Code to save Wu Peiqi: 01111111 00011010 010110110 01001111 10010000 001110100 11111111 00000000 010101010 GBK Code form to open: garbled code
2. Initial programming experience
-
The encoding must be consistent (write and read)
-
The default Python interpreter reads files in the form of UTF-8
-
Change the default interpreter read code to GBK
-
Suggestion: the codes of all python code files should be saved and read in UTF-8
# -*- coding:gbk -*- print("hello word")
3. Output
Present the results or data to the user.
print("hello word")
print(" * * ") print(" * * * * ") print(" * * * * * * ") print(" * * * * * * * * ") print(" * * * * * * * * * * ") print(" * * * * * * * * * * * * ") print(" * * * * * * * * * * * * ") print(" * * * * * * * * * * * * ") print(" * * * * * * * * * * * * * * ") print(" * * * * * * * * * * * * * * * * ") print(" * * * * * * * * * * * * * * * * * * ") print(" * * * * * * * * * * * * * * * * * * * * ") print(" * * * * * * * * * * * * * * * * * * * * * * ") print(" * * * * * * * * * * * * * * * * * * * * * * * * ") print(" * * * * * * * * * * * * * * * * * * * * * * * * ") print(" * * * * * * * * * * * * * * * * * * * * * * * * ") print(" * * * * * * * * * * * * * * * * * * * * * * * * * * ") print(" * * * * * * * * * * * * * * * * * * * * * * * * * * * * ") print(" * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ") print(" * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ") print(" * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ") print(" * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ") print(" * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ") print(" * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ")
About output:
-
By default, a newline character will be added at the end of print:
print("Look at the picturesque scenery") print("I wanted to sing poetry to increase the world") Output: Look at the picturesque scenery I wanted to sing poetry to increase the world
-
I don't want to add new lines at the end of print
print("Looking at the picturesque scenery", end = ",") print("I wanted to sing poetry to increase the world", end = ". ") Output: Look at the picturesque scenery. I wanted to recite poetry to increase the world.
4. Initial data type
When we first went to school, the teacher taught us numbers, Pinyin, Chinese characters, true and false judgment, and then we wrote a composition according to what we learned. The teacher checked and graded it
Now learn programming. Wu Peiqi hands us int, str, bool, etc., and then we write code according to these contents. After writing the code, we hand it over to the python interpreter to run
4.1 integer (int)
Integer, integer.
print statement | Output results | operator | Operator meaning |
---|---|---|---|
print( 2+10 ) | 12 | + | Add up |
print( 2*10 ) | 20 | * | Multiply |
print( 10/2 ) | 5 | / | to be divisible by |
print( 10%3 ) | 1 | % | Surplus |
print( 2**4 ) | 16 | ** | power |
4.2 string (str)
Use single / double / triple quotation marks when writing strings (single / double / triple quotation marks in English)
print("Beijing China") # Double quotation mark print('Tianjin, China') # Single quotation mark print("""Changping District, Beijing, China""") # Three quotation marks (can represent multi line string)
For string operations:
-
Plus: two strings can be spliced by a plus sign
print("Xiao Ming" + "They are three good students") Output: Xiao Ming is a three good student
-
Multiply: integer * string, which is used to splice the string repeatedly N times
print(10 * "hello word") Output: hello wordhello wordhello wordhello wordhello wordhello wordhello wordhello wordhello wordhello word
4.3 boolean type (bool)
Boolean types have two values: True and False
print(1 > 2) Output: False print(1 == 1) Output: True
name = input("Please enter your user name:") if name == "alex": # True print("User login succeeded") else: # false print("User login failed")
Supplement:
1 == 1 You can compare between integers 2 > 3 You can compare two strings 1 == "alex" Integer and string can only be compared for equality, not size
4.4 type installation and replacement
We have a preliminary understanding of the data type int/str/bool above. They all have their own different definitions.
-
int, when defining an integer, it must be a number without quotation marks, for example: 5, 8, 9
-
str, when defining a string, it must be enclosed in double quotation marks, for example: "Xiao Ming", "hello word"
-
bool, when Boolean value is defined, only True and False can be written
Different data types have different functions. For example, integers can add, subtract, multiply and divide, while strings can only add (splice) and multiply.
If you want to convert, you can follow a basic rule: wrap what you want to convert with this type, such as str(666), int(666), etc
Convert to integer:
# Convert string to integer int("666") int("999") "6" + "9" # The two strings are spliced, and the result: string "69" int(6) + int(9) # Result: 15 # report errors int("hello word") # Convert boolean type to integer int(True) # After conversion, it is equal to 1 int(False) # 0 after conversion
Convert to character:
# Integer conversion string str(345) str(666) + str(9) = 6669 # Convert boolean type to string str(True) "True" str(False) "False"
Convert to boolean type:
# Integer to Boolean bool(1) True bool(2) True bool(-3) True bool(0) False bool Only 0 for type conversion false # String to Boolean bool("alex") True bool("") False Only the result of empty string conversion is False, The rest are all True
-
Three sentence type conversion:
-
When all other types are converted to Boolean types, all other types are True except empty string and 0
-
String to integer conversion is that only strings in the form of string "998" can be converted to integer, and other errors are reported
-
If you want to convert to what type, just wrap it in this type of English.
str(...) int(...) bool(...)
-
5. Variables
In fact, variables are aliases and nicknames in our life. Let the variable name point to a value. The format is: [variable name = value]. In the future, the corresponding value can be operated through the variable name.
name = "Xiao Ming" print(name) # Xiao Ming
age = 18 name = "alex" flag = 1 > 18 # false address = "Beijing China"+"Changping" addr = "Beijing China" + "Changping" + name # Changping alex, Beijing, China print(addr) print(flag)
matters needing attention: age = 18 number = 1 = 2 # false
be careful:
- Assign age=18 to the variable
- Let age refer to age=18
5.1 specification of variable name
ge = 18 name = "alex" flag = 1 > 18 # false address = "Beijing China"+"Changping"
Three specifications: (an error will be reported as long as there is one)
- Can only contain alphanumeric underscores
- Cannot start with a number
- Cannot be named with python built-in keywords
*['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']*
Two suggestions:
-
Underline connection naming (lowercase)
school_name = "Tsinghua University"
-
See the name and know the meaning
age = 18 color = "red"
Exercise:
name = "manu ginobili " name0 = "Parker" name_1 = "Duncan " _coach = "Gregg Popovich " _ = "kawaii" 1_year = "1990" # error year_1_ = "1990" _1_year = "1990" nba-team = "Spurs" # error new*name = "Leonard" # error
5.2 memory pointing relationship of variables
Scenario 1
name = "wupeiqi"
Create an area in the computer's memory to store the string value "xiaoming", and the name variable name points to this area.
Scenario 2
name = "wupeiqi" name = "alex"
Create an area in the computer's memory to save the string "xiaoming", the name variable name points to this area, and then create an area in the memory to save the string "xiaohong", the name variable name points to the area where "alex" is located, and no longer points to the area where "xiaoming" is located (the data that no one points to will be marked as garbage and automatically collected by the interpreter)
Scenario 3
name = "wupeiqi" new_name = name
Create an area in the computer's memory to save the string "wupeiqi", and the name of the name variable points to this area. new_ The name variable name points to the name variable. Because it is pointed to the variable name, it will automatically point to the memory area represented by the name variable.
Scenario 4
name = "wupeiqi" new_name = name name = "alex"
Create an area in the computer's memory to save the string "wupeiqi", and the name of the name variable points to this area (gray line), and then new_name points to the memory area that name points to, and finally creates an area to store "alex", so that the name variable points to the area where "alex" is located
Scenario 5
num = 18 age = str(num)
Create an area in the computer's memory to hold the integer 18, and the name variable name points to this area. Through type conversion, a string "18" is created in memory according to the integer 18, and the age variable points to the memory area where the string is stored.
So far, the description of variable memory has been finished. As we are all beginners, we only need to understand the above knowledge points about variable memory management. More about memory management, garbage collection, resident mechanism and other issues will be explained in later courses.
6. Notes
When writing code, if you want to annotate a written content, that is, the interpreter ignores and will not run according to the code.
When writing code, if you want to annotate a written content, that is, the interpreter ignores and will not run according to the code.
-
Single-Line Comments
# Declare a name variable name = "alex" age = 19 # This indicates the age of the current user Note: shortcut points command + ? , control + ?
-
multiline comment
# Declare a name variable # Declare a name variable # Declare a name variable name = "alex" """ Multiline comment content Multiline comment content Multiline comment content """ age = 19
7. Input
Input can realize the interaction between program and user.
# 1. Input on the right ("please enter user name:") is to let the user input content. # 2. Assign the content entered by the user to the name variable. name = input("Please enter user name:") if name == "alex": print("Login successful") else: print("Login failed")
data = input(">>>") print(data)
Special note: anything entered by the user is essentially a string.
-
Prompt to enter the name, then splice a "baked cake" behind the name, prompt to enter the name, then splice a "baked cake" behind the name, and finally print the result.
name = input("Please enter user name:") text = name + "Clay oven rolls" print(text)
-
Prompt for name / location / behavior, then splice and print: xx in xx.
name = input("Please enter user name:") address = input("Please enter the location:") action = input("Please enter behavior:") text = name + "stay" + address + action print(text)
-
Prompt for two numbers and calculate the sum of the two numbers.
number1 = input("Please enter a number:") # "1" number2 = input("Please enter a number:") # "2" value = int(number1) + int(number2) print(value)
8. Conditional statements
if condition : Code after the condition is established... Code after the condition is established... Code after the condition is established... else: Code executed after the condition is not true... Code executed after the condition is not true... Code executed after the condition is not true...
name = input("enter one user name:") if name == "alex": print("sb") else: print("db")
Reminder: unified indentation problem (all use four spaces = tab).
name = input("enter one user name:") if name == "alex": print("sb") print("sb") else: print("db")
8.1 basic condition statement
-
Example 1
print("start") if True: print("123") else: print("456") print("end") # Output results start 123 end
-
Example 2
print("start") if 5==5: print("123") else: print("456") print("end")
-
Example 3
num = 19 if num > 10: print("num The corresponding value of the variable is greater than 10") else: print("num The corresponding value of the variable shall not be greater than 10")
-
Example 4
username = "wupeiqi" password = "666" if username == "wupeiqi" and password == "666": print("Congratulations on your successful login") else: print("Login failed")
-
Example 5
username = "wupeiqi" if username == "wupeiqi" or username == "alex": print("VIP Large member users") else: print("Ordinary users")
-
Example 6
number = 19 if number%2 == 1: print("number It's an odd number") else: print("number It's an even number")
number = 19 data = number%2 == 1 if data: print("number It's an odd number") else: print("number It's an even number")
-
Example 7
if condition: establish
print("start") if 5 == 5: print("5 Equal to 5") print("end")
8.2 multi condition judgment
if condition A: A True, execute all code in this indentation ... elif condition B: B True, execute all code in this indentation ... elif condition C: C True, execute all code in this indentation ... else: above ABC None.
num = input("please enter a number") data = int(num) if data>6: print("It's too big") elif data == 6: print("It is just fine") else: print("It's too small")
score = input("Please enter a score") data = int(score) if data > 90: print("excellent") elif data > 80: print("good") elif data > 70: print("in") elif data > 60: print("difference") else: print("fail,")
8.3 conditional nesting
if condition A: ... elif condition B: ...
if condition A: if condition A1: ... else: ... elif condition B: ...
Simulated 10086 customer service
print("Welcome to call 10086. We provide the following services: 1.Related to telephone charges; two.Business handling; three.Artificial services") choice = input("Please select service serial number") if choice == "1": print("Toll related services") cost = input("Please press 1 to check the telephone charge;Please press 2 to pay the phone bill") if cost == "1": print("The balance of telephone charge is 100") elif cost == "2": print("Interaction fee") else: print("Input error") elif choice == "2": print("Business handling") elif choice == "3": print("Artificial services") else: print("Serial number input error")
summary
- What is coding? Why is there garbled code when opening a file?
- How does pycharm set file encoding?
- What is the default code used by the python interpreter when opening a code file? How to modify?
- print input
- How to realize the conversion between data type formats and related?
- Naming conventions for variables
- The contents entered by the user through input are of string type.
- Conditional statements.
...
elif condition B:
...
```python if condition A: if condition A1: ... else: ... elif condition B: ...
Simulated 10086 customer service
print("Welcome to call 10086. We provide the following services: 1.Related to telephone charges; two.Business handling; three.Artificial services") choice = input("Please select service serial number") if choice == "1": print("Toll related services") cost = input("Please press 1 to check the telephone charge;Please press 2 to pay the phone bill") if cost == "1": print("The balance of telephone charge is 100") elif cost == "2": print("Interaction fee") else: print("Input error") elif choice == "2": print("Business handling") elif choice == "3": print("Artificial services") else: print("Serial number input error")
summary
- What is coding? Why is there garbled code when opening a file?
- How does pycharm set file encoding?
- What is the default code used by the python interpreter when opening a code file? How to modify?
- print input
- How to realize the conversion between various data type formats and related?
- Naming conventions for variables
- The contents entered by the user through input are of string type.
- Conditional statements.