Python, Day1 - Python Basics 1

Reprinted from http://www.cnblogs.com/alex3714/articles/5465198.html

1. Variable\character encoding  

Variables are used to store information to be referenced and manipulated in a computer program. They also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves. It is helpful to think of variables as containers that hold information. Their sole purpose is to label and store data in memory. This data can then be used throughout your program.

declare variable

#_*_coding:utf-8_*_

name = "Alex Li"

The above code declares a variable, the variable name is: name, and the value of the variable name is: "Alex Li" 

Rules for variable definition:

    • 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', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or' , 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

variable assignment

name = "Alex Li"

name2 = name
print(name,name2)

name = "Jack"

print("What is the value of name2 now?")

 

2. Character encoding

When the python interpreter loads the code in the .py file, it encodes the content (ascill by default)

ASCII (American Standard Code for Information Interchange, American Standard Code for Information Interchange) is a computer encoding system based on the Latin alphabet, mainly used to display modern English and other Western European languages, which can only be represented by a maximum of 8 bits (one byte ), that is: 2**8 = 256-1, so the ASCII code can only represent up to 255 symbols.

 

About Chinese

To handle Chinese characters, programmers designed GB2312 for Simplified Chinese and big5 for Traditional Chinese.

GB2312 (1980) contains a total of 7445 characters, including 6763 Chinese characters and 682 other symbols. The inner code range of the Chinese character area is from B0-F7 in the high byte and A1-FE in the low byte. The occupied code points are 72*94=6768. Among them, 5 vacancies are D7FA-D7FE.

GB2312 supports too few Chinese characters. The Chinese character extension specification GBK1.0 in 1995 included 21886 symbols, which are divided into Chinese character area and graphic symbol area. The Chinese character area includes 21003 characters. GB18030 in 2000 is the official national standard to replace GBK1.0. The standard includes 27,484 Chinese characters, as well as Tibetan, Mongolian, Uyghur and other major minority languages. The current PC platform must support GB18030, and there is no requirement for embedded products. Therefore, mobile phones and MP3s generally only support GB2312.

From ASCII, GB2312, GBK to GB18030, these encoding methods are backward compatible, that is, the same character always has the same encoding in these schemes, and later standards support more characters. Among these encodings, English and Chinese can be handled uniformly. The method to distinguish Chinese encoding is that the highest bit of the high byte is not 0. According to the programmer's name, GB2312, GBK to GB18030 belong to the double-byte character set (DBCS).

The default internal code of some Chinese Windows is still GBK, which can be upgraded to GB18030 through the GB18030 upgrade package. However, the characters added by GB18030 relative to GBK are difficult for ordinary people to use. Usually, we still use GBK to refer to the Chinese Windows internal code.

 

 

Obviously, ASCII code cannot represent all kinds of characters and symbols in the world. Therefore, it is necessary to create a new encoding that can represent all characters and symbols, namely: Unicode

Unicode (Unicode, Universal Code, Unicode) is a character encoding used on computers. Unicode was created to solve the limitations of the traditional character encoding scheme. It sets a unified and unique binary encoding for each character in each language, and stipulates that although some characters and symbols are represented by at least 16 bits (2 bytes), that is: 2 **16 = 65536,
Note: The minimum size is 2 bytes, maybe more

UTF-8 is the compression and optimization of Unicode encoding. It no longer uses at least 2 bytes, but classifies all characters and symbols: the content in ascii code is stored in 1 byte, European characters Save with 2 bytes, East Asian characters with 3 bytes...

Therefore, when the python interpreter loads the code in the .py file, it will encode the content (ascill by default), if it is the following code:

Error: ascii code cannot represent Chinese

#!/usr/bin/env python
 
print "hello world"

Correction: It should be displayed to tell the python interpreter what encoding to use to execute the source code, ie:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
print "hello world"

Notes

  When the line is watched: # the commented content

  Multi-line comment: """ Commented content"""

  

  

 

3. User input 

#!/usr/bin/env python
#_*_coding:utf-8_*_


#name = raw_input("What is your name?") #only on python 2.x
name = input("What is your name?")
print("Hello " + name )

When entering the 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 -*-
 
import getpass
 
# Assign the content entered by the user to the name variable
pwd = getpass.getpass("Please enter your password: ")
 
# print the input
print(pwd)

 

4. Introduction to the module  

The power of Python is that it has a very rich and powerful standard library and third-party library. Almost any function you want to achieve is supported by the corresponding Python library. In the future courses, various commonly used libraries will be explained in depth. Now , let's learn 2 simple ones symbolically.

sys

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys

print(sys.argv)


#output
$ python test.py helo world
['test.py', 'helo', 'world'] #Get the parameters passed when executing the script

  

you

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import them

os.system("df -h") #call system command

fully combine  

import os,sys

os.system(''.join(sys.argv[1:])) #Take the user's input parameters as a command to os.system for execution

  

5. What the hell is .pyc?

1. Is Python an interpreted language?

When I first learned Python, the first thing I heard about Python was that Python is an interpreted language, and I kept believing it until I discovered the existence of *.pyc files. If it is an interpreted language, what is the generated *.pyc file? c should be the abbreviation of compiled!

In order to prevent other people learning Python from being misunderstood by this sentence, then we will clarify this issue in the text and clarify some basic concepts.

  

2. Interpreted and compiled languages 

Computers cannot recognize high-level languages, so when we run a high-level language program, we need a "translator" to convert the high-level language into a machine language that the computer can understand. This process is divided into two categories, the first is compilation, and the second is interpretation.

Before the program is executed, a compiled language will first perform a compilation process on the program through the compiler to convert the program into machine language. There is no need for translation at runtime, and direct execution is fine. The most typical example is the C language.

Interpreted languages ​​do not have this compilation process, but when the program is running, the program is interpreted line by line through the interpreter, and then runs directly. The most typical example is Ruby.

Through the above examples, we can summarize the advantages and disadvantages of interpreted languages ​​and compiled languages, because compiled languages ​​have already "translated" the program before the program is run, so there is less "translation" at runtime. ” process, so the efficiency is relatively high. But we can't generalize, some interpreted languages ​​can also optimize the entire program when translating the program through the optimization of the interpreter, so that it is more efficient than compiled languages.

In addition, with the rise of virtual machine-based languages ​​such as Java, we cannot divide languages ​​purely into interpreted and compiled languages.

Taking Java as an example, Java is first compiled into a bytecode file by a compiler, and then interpreted into a machine file by an interpreter at runtime. So we say that Java is a language that is compiled and then interpreted.

 

3. What is Python? 

In fact, Python, like Java/C#, is also a language based on virtual machines. Let's first briefly understand the running process of Python programs on the surface.

When we enter python hello.py on the command line, we actually activate the Python "interpreter" and tell the "interpreter": you are about to start working. But before the "interpretation", the first work performed is actually compiling, the same as Java.

Students who are familiar with Java can think about how we execute a Java program on the command line:

javac hello.java

java hello

 

It's just that when we use IDEs such as Eclipse, the two are integrated into one. In fact, the same is true for Python. When we execute python hello.py, it also performs such a process, so we should describe Python in this way. Python is a language that is compiled and then interpreted.

4. Briefly describe the running process of Python

Before talking about this problem, let's talk about two concepts, PyCodeObject and pyc file.

The pyc we see on the hard disk naturally does not need to say much, but in fact PyCodeObject is the result of the actual compilation of the Python compiler. We can simply know it first, and continue to look down.

When the python program runs, the compiled result is stored in the PyCodeObject located in the memory. When the Python program runs, the Python interpreter writes the PyCodeObject back to the pyc file.

When the python program runs for the second time, first the program will look for the pyc file in the hard disk. If it is found, it will be loaded directly, otherwise the above process will be repeated.

So we should locate PyCodeObject and pyc files in this way. We say that pyc files are actually a persistent way of saving PyCodeObject.

 

6. First knowledge of data types 

1. Numbers

2 is an example of an integer.
Long integers are simply larger integers.
3.23 and 52.3E-4 are examples of floating point numbers. The E mark represents a power of 10. Here, 52.3E-4 means 52.3*10-4.
(-5+4j) and (2.3-4.6j) are examples of complex numbers, where -5, 4 are real numbers and j is an imaginary number. What is a complex number in mathematics? .

int (integer)

  On a 32-bit machine, the number of integers is 32 bits, and the value range is -2**31 to 2**31-1, that is, -2147483648 to 2147483647.
  On a 64-bit system, the number of integers is 64 bits. The value range is -2**63~2**63-1, that is -9223372036854775808~9223372036854775807
long (long integer)
  is different from the C language, Python's long integer does not specify the bit width, that is: Python does not limit the size of the long integer value, but in fact, due to limited machine memory, the long integer value we use cannot be infinitely large.
  Note that since Python 2.2, if an integer overflow occurs, Python will automatically convert integer data to long integers, so now not adding the letter L after the long integer data will not cause serious consequences.
float
       Literacy first http://www.cnblogs.com/alex3714/articles/5895848.html 
  Floating point numbers are used to deal with real numbers, that is, numbers with decimals. Similar to the double type in C language, it occupies 8 bytes (64 bits), of which 52 bits represent the base, 11 bits represent the exponent, and the remaining one represents the sign.
complex (complex number)
  A complex number consists of a real part and an imaginary part. The general form is x+yj, where x is the real part of the complex number and y is the imaginary part of the complex number, where x and y are real numbers.
Note: There is a small number pool in Python: -5 to 257
 
2. Boolean value
  Real or fake
  1 or 0
3. String
"hello world"
Evil string concatenation:
  The string in python is embodied as a character array in the C language. Every time you create a string, you need to open up a continuous space in the memory, and once you need to modify the string, you need to open up space again, the evil + sign Every time it appears, it will re-create a space within it.
String formatted output
name = "alex"
print "i am %s " % name
 
#output: i am alex

PS: String is %s; Integer %d; Float %f

String common functions:
  • remove whitespace
  • Split
  • length
  • index
  • slice
4. List
Create a list:
name_list = ['alex', 'seven', 'eric']
or
name_list = list(['alex', 'seven', 'eric'])

Basic operation:

  • index
  • slice
  • addition
  • delete
  • length
  • slice
  • cycle
  • Include
5. Tuples (immutable lists)
Create a tuple:
ages = (11, 22, 33, 44, 55)
or
ages = tuple((11, 22, 33, 44, 55))
 
6. Dictionary (unordered)
Create a dictionary:
person = {"name": "mr.wu", 'age': 18}
or
person = dict({"name": "mr.wu", 'age': 18})

Common operations:

  • index
  • new
  • delete
  • key, value, key-value pair
  • cycle
  • length

Seven, data operation  

Arithmetic operations:

Comparison operation:

Assignment operation:

logic operation:

Member operations:

Identity operation:

Bit operation:

#!/usr/bin/python
 
a = 60            # 60 = 0011 1100
b = 13            # 13 = 0000 1101
c = 0
 
c = a & b;        # 12 = 0000 1100
print "Line 1 - Value of c is ", c
 
c = a | b;        # 61 = 0011 1101
print "Line 2 - Value of c is ", c
 
c = a ^ b; # 49 = 0011 0001 #The same is 0, the difference is 1
print "Line 3 - Value of c is ", c
 
c = ~a;           # -61 = 1100 0011
print "Line 4 - Value of c is ", c
 
c = a << 2;       # 240 = 1111 0000
print "Line 5 - Value of c is ", c
 
c = a >> 2;       # 15 = 0000 1111
print "Line 6 - Value of c is ", c

*Bitwise negation operation rule (bitwise negation plus 1) Detailed explanationhttp://blog.csdn.net/wenxinwukui234/article/details/42119265

 

Operator precedence:

More content: slam here

  

Eight, expression if ... else

Scenario 1. User login verification

# Prompt for username and password
 
# Verify username and password
# If wrong, output the wrong username or password
# If successful, output welcome, XXX!


#!/usr/bin/env python
# -*- coding: encoding -*-
 
import getpass
 
 
name = raw_input('Please enter username:')
pwd = getpass.getpass('Please enter your password:')
 
if name == "alex" and pwd == "cmd":
    print("Welcome, alex!")
else:
    print("Username and password are incorrect")

Scenario 2. Age guessing game

Set your age in the program, and then start the program to let the user guess. After the user enters, it will prompt the user whether the input is correct according to his input. If it is wrong, the prompt is whether the guess is too big or too small.

#!/usr/bin/env python
# -*- coding: utf-8 -*-


my_age = 28

user_input = int(input("input your guess num:"))

if user_input == my_age:
    print("Congratulations, you got it !")
elif user_input < my_age:
    print("Oops,think bigger!")
else:
    print("think smaller!")

  

Outer variables, which can be used by inner code
Inner variables, should not be used by outer code

 

Nine, expression for loop

The simplest loop is 10 times

#_*_coding:utf-8_*_
__author__ = 'Alex Li'


for i in range(10):
    print("loop:", i )

output:

loop: 0
loop: 1
loop: 2
loop: 3
loop: 4
loop: 5
loop: 6
loop: 7
loop: 8
loop: 9

Requirement 1: The above program is still the same, but when the number of cycles is less than 5, it will not leave, and jump directly to the next cycle

for i in range(10):
    if i<5:
        continue #Do not go down, go directly to the next loop
    print("loop:", i )

Requirement 2: The above program is still the same, but when the number of cycles greater than 5 is encountered, it will not leave and exit directly.

for i in range(10):
    if i>5:
        break #Don't go down, just jump out of the whole loop
    print("loop:", i )

 

十、while loop   

 There is a kind of cycle called an infinite loop. Once triggered, it will run forever, and the sea will dry up.

rotten code

count = 0
while True:
    print("You are the wind and I am the sand, lingering to the end of the world...", count)
    count +=1
    

 

In fact, except for time, nothing is eternal. It is better to write less dead loops. 

The above code loops 100 times and exits

 

count = 0
while True:
    print("You are the wind and I am the sand, lingering to the end of the world...", count)
    count +=1
    if count == 100:
        print("Fuck the wind and sand, you stinky men who take off your pants are human, and put on your pants are ghosts..")
        break
        

 

 

Returning to the example of the for loop above, how to let the user guess the age continuously, but only give a maximum of 3 chances, and then exit the program if the guess is wrong.

#!/usr/bin/env python
# -*- coding: utf-8 -*-


my_age = 28

count = 0
while count < 3:
    user_input = int(input("input your guess num:"))

    if user_input == my_age:
        print("Congratulations, you got it !")
        break
    elif user_input < my_age:
        print("Oops,think bigger!")
    else:
        print("think smaller!")
    count += 1 #each loop counter +1
else:
    print("It's wrong to guess so many times, you idiot.")

  

 

 door knowledge

1. bytes type

 

Two, three yuan luck

1
result  =  1  if  条件  else  2

If condition is true: result = value 1
If condition is false: result = value 2

3. System

  • binary, 01
  • octal, 01234567
  • decimal, 0123456789
  • Hexadecimal, 0123456789ABCDEF binary to hexadecimal conversion http://jingyan.baidu.com/album/47a29f24292608c0142399cb.html?picindex=1

Computer memory address and why use hexadecimal?

Why use hexadecimal
1. Computer hardware is 0101 binary, and hexadecimal is just a multiple of 2, which makes it easier to express a command or data. Hexadecimal is shorter, because when converting, a hexadecimal number can top 4 binary digits, that is, a byte (8-digit hexadecimal can be represented by two hexadecimal digits)
2. The earliest ASCII character set is 8bit (later expanded, but the basic unit is still 8bit), 8bit can be expressed directly with 2 hexadecimals, no matter reading or storage, it is more convenient than other hexadecimals
3. Computer The CPU operation also follows the ASCII character set, and develops in such a way as 16, 32, and 64, so the hexadecimal system is also better when data is exchanged
. Hexadecimal calculation used


Where is hexadecimal used?
1. Network programming, when data exchange needs to parse bytes, it is a byte-by-byte process, and 1 byte can be expressed by two hexadecimals of 0xFF. Through the network packet capture, you can see that the data is transmitted in hexadecimal.
2. Data storage, storage to hardware is the 0101 method, and the expression method of storage to the system is the byte method

3. The definition of some common values, such as: the color expression in html that we often use is the hexadecimal method, and 4 hexadecimal digits can express millions of color information.

 

4. Everything is an object

In Python, everything is an object, and objects are created based on classes

Therefore, the following values ​​are objects: "wupeiqi", 38, ['Beijing', 'Shanghai', 'Shenzhen'], and are objects generated according to different classes.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324853458&siteId=291194637