Catalog
@ (Development Foundation)
1. variable
Variables are used to store information to be referenced and manipulated in computer programs. Their sole purpose is to mark and store data in memory. These data can then be used throughout the program. The value of a variable stored in memory. This means that creating variables opens up a space in memory.
Based on the data type of the variable, the interpreter allocates the specified memory and decides what data can be stored in memory. Therefore, variables can specify different data types, which can store integers, decimals or characters.
Declare variables
name = "nepoleon"
Rules for defining variables
- Variable names can only be any combination of letters, numbers, or underscores
- The first character of a variable name cannot be a number
- The following keywords cannot be declared as variable names ['and','as','assert','break','class','continue','def','del','elif','else','except','exec','last','for','from','global','if','import','in','is','lambda','not','or','pass','print','return','try','while']
Naming rules
- Hump type
MyName = uppercase for each word "zzk" - Underline
My_name= "zzk" is underlined - Variable names, do not be Chinese, Pinyin, or too long names, words do not mean, etc.
Multiple variable assignment
a = b = c = 3
Multiple variables specify multiple variables
a,b,c = 1,"tom",666
constant
Constants are invariant quantities, such as pai 3.141592653, or those that do not change during the running of a program.
In Python, there is no special grammar for constants, and programmers conventionally use all capitals of variable names to represent constants.
NUMERBER = 56
There is a special constant definition grammar in c language, const int count = 60; once defined as a constant, the change will report an error.
2. User interaction and annotations
Program interaction
Read user input
name = input("What is your name?") print("My name is",name)
Enable users to enter multiple messages
name = input("What is your name?:") age = input("Your age:") hometown = input("Where is your hometown?") print('''My name is %s,\nmy age is %s,\nmy hometown is %s''' %(name,age,hometown))
The output is as follows:
My name is,zk, my age is 22, my hometown is anhui
Notes
Code comment can be divided into single line and multi-line comment, single line comment with #, multi-line comment with three pairs of double quotation marks """"
def subclass_exception(name, parents, module, attached_to=None): """ Create exception subclass. Used by ModelBase below. If 'attached_to' is supplied, the exception will be created in a way that allows it to be pickled, assuming the returned exception class will be added as an attribute to the 'attached_to' class. """ class_dict = {'__module__': module} if attached_to is not None: def __reduce__(self): # Exceptions are special - they've got state that isn't # in self.__dict__. We assume it is all in self.args. return (unpickle_inner_exception, (attached_to, name), self.args) def __setstate__(self, args): self.args = args class_dict['__reduce__'] = __reduce__ class_dict['__setstate__'] = __setstate__ return type(name, parents, class_dict)
Code Annotation Principles:
- Instead of annotating all the code, you just need to annotate important, or unintelligible, comments.
- Notes can be in Chinese or English, but not in Pinyin.
# 3. Basic data types
### What is a data type?
We humans can easily distinguish between numbers and characters, but computers can't. Although computers are powerful, they are silly in some ways. Unless you tell them clearly that 1 is a number and that "Han" is a word, it can't tell the difference between 1 and "Han". Therefore, in every programming language there will be something called data type. In fact, the commonly used data types are clearly divided. If you want the computer to perform numerical operations, you pass the number to it. If you want him to process the text, you pass the string type to him.
Digital data
#### int (integer)
On a 32-bit machine, the number of integers is 32 bits, ranging from - 2 ^ 31 ^ to 2 ^ 31 ^ - 1, i.e. - 2147483648 to 2147483647.
On a 64-bit system, the number of integers is 64 bits, ranging from - 2 ^ 63 ^ to 2 ^ 63 ^ - 1, i.e. - 9223372036854775808 to 9223372036854775807.
#### long (long shaping)
There's no longer a long type in Python 3. It's all int.
>> a = 2**64 >> type(a) >> <class 'int'>
#### Floating point type
Floating point number is a numerical representation of a specific subset of rational numbers, which is used to approximate any real number in a computer. Specifically, the real number is obtained by multiplying the integer power of a radix (usually 2 in a computer) by an integer or a fixed number (i.e., the tail), which is similar to the scientific counting method with a radix of 10.
python's floating point number is the elementary school in mathematics (infinite circular decimal or finite decimal).
Why is it called float floating-point?
Floating-point numbers are decimal numbers. They are called floating-point numbers because they are expressed in scientific notation.
The decimal position of a floating-point number is variable, for example,
1.23109 and 12.3108 are equal.
Floating point numbers can be written mathematically, such as 1.23, 3.14, -9.01, and so on. But for large or small floating-point numbers, it is necessary to use scientific counting to express 10 instead of e:
1.23*109 is 1.23e9, or 12.3e8, 0.000012 can be written as 1.2e-5, etc.
Integers and floating-point numbers are stored differently in computers. Integer operations are always accurate, while floating-point operations may have rounding errors.
complex
complex is composed of real and imaginary numbers.
To understand complex numbers, in fact, we need to know imaginary numbers first about complex numbers. Imaginary number (that is, false and unreal number): A number whose square is complex is called an imaginary number.
Complex numbers are numbers a + b i, where a and b are real numbers and I are imaginary units (i.e. - 1 roots). In complex a + b i, A is called the real part of the complex number, b is called the imaginary part of the complex number (imaginary number refers to the number whose square is negative), and I is called the imaginary unit.
When the imaginary part is equal to zero, the complex number is real; when the imaginary part is not equal to zero, the complex number is called imaginary number.
Note, the imaginary part of the letter j can be capitalized.
Character string
Strings are ordered and immutable
The quotation marks in python are considered strings
name = "nep" # Double quotation marks age = "22" # Character string n_age = 22 # int hometown = ''' Anhui ''' #triple quotes job = 'vfx' # Single quotation mark
There is no difference between single quotation marks and double quotation marks. Three quotation marks must be used for multi-line comments.
Translation
Both single and double quotation marks cannot cancel the meaning of special characters. If you want all characters in quotation marks to cancel special meaning, add r before quotation marks, such as name = r'l thf'
-
unicode strings must be preceded by r, such as name = ur'l thf'
String operation
s = "hello word" #Indexes s = 'hello' >>> s[1] 'e' >>> s[-1] 'o' #Section >>> s = 'abcdefghigklmn' >>> s[0:7] 'abcdefg' >>> s[7:14] 'higklmn' >>> s[:7] 'abcdefg' >>> s[7:] 'higklmn' >>> s[:] 'abcdefghigklmn' >>> s[0:7:2] 'aceg' >>> s[7:14:3] 'hkn' >>> s[::2] 'acegikm' >>> s[::-1] 'nmlkgihgfedcba' len(s) # Length of strings s.swapcase() # Case interchange s.capitalize() # title case s.casefold() #All unity is lowercase s.center() # Centralized display for example print(s.center(30,"#")) s.count() # Statistics of the number of a character, space is also a character, S. count ("o, 0, 5)"o"between 0 and 5. s.endswith() # Judge what ends and return to True/False s.strip() #String blanks removed s.lstrip() # Remove the left space s.rstrip() #Remove the space on the right isdigit() #Is the judgment a number? s.title() # Capital letters for each word islower() #Is it all lowercase? isupper() #Is it all capitalized? lower() #All converted to lowercase upper() #All converted to uppercase isspace() #Is the judgement blank? istitle() #Determine whether the title is capitalized?
expandtabs() expands the tab key, provided there is a tab key in the string
a = "a\tb\tc" # \ t is the tab key print(a.expandtabs(8)) # Eight spaces between each character
find() Finds the index position of the character. If it is a negative number, it means that the search failed, and find() can also find the beginning.
s = "Hello,word" s.find("o",0,5)
The difference between index() returning index value and find()
s.index("a") # a is not in the string s, returns an error, find() is not error-free, output-1
format() string formatting
s14 = "my name is {0},i am {1} years old" s14.format("Tom",23) # It can be done as well. s15 = "my name is {name},i am {years} years old" s15.format(name = "zk","years" = 22)
join() joins two strings
a = "-" name = ["tom","san","kite"] s = "abcde" print(a.join(name)) # Output tom-san-kite print(a.join(s)) # a-b-c-d-e
How many bits does the left side of ljust() begin to align
s = "hello word" s.ljust(30,"-") # 30 characters left to right, followed by-
replace() substitution character
a = "hello word" a.replace("o","-") # Replace all o a.replace("o","-",1) # Replace the first o
split() splits and returns the list.
Boolean type
Boolean type is very simple, just two values, one True (true) and one False (false), mainly used for logical judgment.
a = 3 b =5 a < b # Establishment is True True a > b # Failure is False False
bool type has only two values: True and False
The bool value is categorized as a number because we are also accustomed to using 1 for True and 0 for False.
Format output
Following is the formatting of different methods
- Input as user input, +connect two strings
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author: Nepoleon Chou name = input ("name:") age = input("age:") job = input("job:") info = ''' --------------info of '''+ name +''''----------------- Name: ''' + name + ''' Age: ''' + age + ''' Job:''' + job print(info)
- The above writing is too cumbersome. We can use% s and% D as formatted output. We can write these:
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author: Nepoleon Chou # Format output% s for string # % d means that only the numeric% f floating point can be input name = input ("name:") age = int(input("age:")) job = input("job:") salary = input("salary:") info = ''' --------------info of %s----------------- Name: %s Age: %d job: %s Salary: %s '''% (name,name,age,job,salary) print(info)
- You can also use. format to format the output, which will be used more in the future:
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author: Nepoleon Chou name = input ("name:") age = int(input("age:")) job = input("job:") salary = input("salary:") info2 = ''' ----------------info of {_name}------------ Name = {_name} Age = {_age} job = {_job} Salary = {_salary} ''' .format(_name=name, _age=age, _job=job, _salary=salary) print(info2)
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author: Nepoleon Chou name = input ("name:") age = int(input("age:")) job = input("job:") salary = input("salary:") info3 = ''' ---------------info of {0}---------- Name = {0} Age = {1} Job = {2} Salary = {3} ''' .format(name,age,job,salary) print(info3)
operator
Computers can carry out many kinds of operations, not only add, subtract, multiply and divide so simple, operations can be divided into arithmetic operations, comparison operations, logical operations, assignment operations, member operations, identity operations, bit operations. Today we only learn arithmetic operations, comparison operations, logical operations, assignment operations.
Arithmetic operation
Comparison operator
Assignment operation:
Logical operation
Identity operation
while cycle
In Python programming, the while statement is used to execute a program in a loop, that is, under certain conditions, to execute a program in a loop to deal with the same tasks that need to be processed repeatedly.
Execution statements can be a single statement or block of statements. The judgment condition can be any expression, and any non-zero or null value is true.
When the condition false false false is judged, the loop ends.
Use while to guess age:
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author: Nepoleon Chou # Guess age only three times, then quit Age_of_Nepoleon = 24 count = 0 #0 start counting while True: #When the condition is satisfied if count == 3: #If you enter it three times break count += 1 guess_age = int(input("Age_of_Nepoleon:")) if guess_age == Age_of_Nepoleon: print("yes,You are Right!") break elif guess_age > Age_of_Nepoleon: print("No,it's too bigger") else: print("No,it's too smaller")
Optimize the above code:
Age_of_Nepoleon = 24 count = 0 while count<3: count += 1 guess_age = int(input("Age_of_Nepoleon:")) if guess_age == Age_of_Nepoleon: print("yes,You are Right!") break elif guess_age > Age_of_Nepoleon: print("No,it's too bigger") else: print("No,it's too smaller") else: print("you have tried much time...breakDown")
There are two other important commands in the while statement: continue, break to skip the loop, continue to skip the loop, break to exit the loop, and "judgment condition" can also be a constant, indicating that the loop must hold. The specific usage is as follows:
# continue and break usage i = 1 while i < 10: i += 1 if i%2 > 0: # Skip Output in Non-even Numbers continue print i # Output Binary Numbers 2, 4, 6, 8, 10 i = 1 while 1: # Cyclic condition 1 must hold print i # Output 1~10 i += 1 if i > 10: # Jump out of the loop when i is greater than 10 break
Infinite Dead Cycle
If the conditional judgement statement is always true, the loop will be executed indefinitely, as shown in the following example:
#!/usr/bin/env python count = 0 while True: print("Hello",count) count+=1
for cycle
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author: Nepoleon Chou for i in range(0,10,2): #One for every two outputs print("loop",i)
Continue, break to skip the cycle, continue is to skip this cycle, berak ends all the cycles.
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author: Nepoleon Chou for i in range(0,10): #One for every two outputs if i <7: continue #Skip directly when you encounter less than 7 elif i == 9: break #Jump out of the loop when it's equal to 9 print("loop",i)
if...else
if conditions:
Conditional execution of code
elif conditions:
If the above conditions are not satisfied, let's go this way.
elif conditions:
If the above conditions are not satisfied, let's go this way.
elif conditions:
If the above conditions are not satisfied, let's go this way.
else:
If all the above conditions are not satisfied, go ahead.
When entering a password, if you want to be invisible, you need to use the getpass method in the getpass module, that is:
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author: Nepoleon Chou import getpass # Ciphertext module username = input('username:') password = getpass.getpass('password:') #ciphertext #password = input('password:') #Plaintext _username = 'Nepoleon' _password = '1234' if _username == username and _password == password: #If the output username and password match the username and password set by the user print('Welcome user {name} login...' .format(name=username)) else: print('Invalid username or password!') print(username,password)