Python basics 1 and python Basics

Source: Internet
Author: User

Python basics 1 and python Basics

Start python

Summary:

1. Introduction to python

Ii. Installation

3. The first python Program

Iv. Variable and character encoding

V. user input

Vi. Data Types

7. All objects

8. Data Operations

9. if else process judgment

10. while Loop

11. for Loop

12. break and continue

 

1. Introduction to python

Python introduction:

Python is the famous Guido van rosum (Guido van norsum) programming language designed to pass the boring Christmas Day during the Christmas Day of 1989) the name of the programming language is because he is a fan of a comedy group named Monty Python and ranks fifth in the latest tibench ranking python.

 

Python classification:

When writing Python code, we get a Python code.pyA text file with the extension. To run the code, you must run the Python interpreter..pyFile. Since the entire Python language is open-source from the standard to the interpreter, theoretically, anyone can write a Python interpreter to execute Python code (of course, difficult) as long as the level is high enough ). In fact, there are indeed a variety of Python interpreters.

  • Cpython

Python official version, which is implemented in C language and most widely used. CPython converts source files (py files) into bytecode files (. python file), and then run on the Python Virtual Machine. After running, the memory is released and the program is exited.

  • Jython

Jython is an implementation method of Python. Jython compiles Python code as a Java bytecode and then runs it by JVM (Java Virtual Machine). In other words, there is no difference between this Python program and Java program, the source code is different.

  • IronPython

IronPython is the C # Implementation of Python, And it compiles the Python code into the C # intermediate code (similar to Jython), and then runs it. NET language interoperability is also very good.

  • Pypy

PyPy is another Python interpreter whose goal is the execution speed. PyPy uses JIT technology to dynamically compile Python code (note that it is not an explanation), so it can significantly improve the execution speed of Python code.

Most Python code can be run in PyPy, but PyPy and CPython are somewhat different, which leads to different results for the same Python code to be executed in two interpreters. If your code is to be executed in PyPy, you need to understand the differences between PyPy and CPython.

 

Python code running process:

 

Ii. Installation

1. windows

1. Download the installation package

Https://www.python.org/downloads/

2. Installation

Default installation path: C: \ python3

3. Configure Environment Variables

Right-click the computer and choose Properties> advanced system Settings> advanced environment variables> Path in the second content box. one row, double-click] --> [append the Python installation directory to the variable value and use; Separate]

For example: the original value; C: \ python3. Remember that there is a semicolon before it.

 

2. linuxPython is provided in linux, but most of them are python2.6. Upgrade to python3.
3. The first python Program
The first python program to learn the programming language is hello world. Let's take a look at how python is implemented. In linux, enter the python command to enter the interaction mode. Check the following code against the version:
1 # python2.x2 print "hello world"3 4 #python3.x5 print("hello world")

 

Iv. Variable and character encoding

1. Variable Declaration

1 name=“WD”

The variable name is declared above, and the value is WD.

 

2. variable definition rules

  • Variable names can only be any combination of letters, numbers, or underscores
  • The first character of the variable name cannot be a number.
  • The following keywords cannot be declared as variable names

['And', 'as', 'assert ', 'Break', 'class', 'contine', 'def', 'del ', 'elif ', 'else', 'Got t', 'exec ', 'Finally', 'for ', 'from', 'global', 'if', 'import', 'in ', 'Is ', 'lambda', 'not ',' or ', 'pass', 'print', 'raise ', 'Return', 'try', 'while ', 'with', 'yield ']

 

3. Variable assignment

1 name = "WD" 2 name1 = name3 name = "jack" 4 print (name, name1) 5 Results: 6 jack WD

The above results show that when one variable assigns a value to another variable, changing the previous variable does not affect the value of the latter variable.

 

4. character encoding

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

ASCII (American Standard Code for Information Interchange) is a computer coding system based on Latin letters. It is mainly used to display modern English and other Western European languages, it can only be expressed in 8 bits (one byte), that is, 2 ** 8 = 256-1. Therefore, the ASCII code can only represent 255 symbols at most.

Obviously, ASCII codes cannot represent all types of characters and symbols in the world. Therefore, you need to create a new encoding that can represent all characters and symbols, that is, Unicode.

Unicode (unified code, universal code, Single Code) is a character encoding used on a computer. Unicode is generated to address the limitations of traditional character encoding schemes. It sets a uniform and unique binary encoding for each character in each language, it is specified that some characters and symbols are represented by at least 16 bits (2 bytes), that is, 2*16 = 65536,
Note: here we will talk about at least 2 bytes, maybe more

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

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

1 #! /Usr/bin/env python2 print "Hello, world"

Error: ascii code cannot indicate Chinese Characters

The following code should be displayed to the python Interpreter:

1 #! /Usr/bin/env python2 #-*-coding: UTF-8-*-3 4 print "Hello, world"

 

5. Notes

Single Row gaze: # commented content

Multi-line comment: "commented content """

 

V. user input

1. python2.x

In python2.x, there are two user input functions: input and raw_input.

  • Raw_input

In python2, raw_input uses your input content as a string by default. For example:

1 #! /Usr/bin/env python2 # _ * _ coding: UTF-8 _ * _ 3 name = raw_input ("input your name:") 4 print type (name) 5 print ("Hello" + name) 6 RESULTS: 7 input your name: 11118 <type 'str'> 9 Hello 1111
  • Input

The input in pyton2 identifies whether the input content is a number or a string by default. When the input content is a string
For variable processing. For example:

1 #! /Usr/bin/env python 2 # _ * _ coding: UTF-8 _ * _ 3 msg = 'wd '4 name = input ("input your name :") 5 print type (name) 6 print ("Hello" + name) 7 results: 8 input your name: msg 9 <type 'str'> 10 Hello WD

 

2. python3.x

User input is optimized in python3. Only the input method is used and the input content is processed as a string. For example:

1 #! /Usr/bin/env python2 # _ * _ coding: UTF-8 _ * _ 3 name = input ("input your name:") 4 print (type (name )) 5 print (name) 6 RESULTS: 7 input your name: WD8 <class 'str'> 9 WD

 

Vi. Data Types
1. Number

2 is an integer example.
A long integer is a larger integer.
3.23 and 52.3E-4 are floating point numbers. E indicates the power of 10. Here, 52.3E-4 indicates 52.3*10-4.
(-5 + 4j) and (2.3-4.4.7) are examples of plural numbers. Where-5 and 4 are real numbers, j is virtual numbers, and what is the plural in mathematics ?.

Int (integer)

On a 32-bit machine, the number of digits of an integer is 32 bits and the value range is-2 ** 31 ~ 2 ** 31-1, I .e.-2147483648 ~ 2147483647
In a 64-bit system, the number of digits of an integer is 64-bit, and the value range is-2 ** 63 ~ 2 ** 63-1, that is,-9223372036854775808 ~ 9223372036854775807 long (long integer)
Different from the C language, the Length Integer of Python does not specify the Bit Width. That is, Python does not limit the size of the Length Integer. However, due to limited machine memory, the length integer value we use cannot be infinitely large.
Note: Since Python2.2, if an integer overflows, Python will automatically convert the integer data to a long integer. Therefore, without the letter L after the long integer data, it will not cause serious consequences.
Float (float) first literacy http://www.cnblogs.com/alex3714/articles/5895848.html
Floating point numbers are used to process real numbers, that is, numbers with decimals. Similar to the double type in C, it occupies 8 bytes (64-bit), where 52 bits represent the bottom, 11 bits represent the index, and the remaining one represent the symbol.
Complex (plural)
A complex number is composed of a real number and a virtual number. Generally, x + yj is used. x is the real number of a complex number, and y is the virtual number of a complex number. Here, x and y are both real numbers. Note: there is a small number pool in Python:-5 ~ 257 2. boolean value true or false 1 or 03, string
1 “hello world”

4. bytes type

The most important new feature of Python3 is to make a clearer distinction between text and binary data. The text is always Unicode, represented by the str type, and the binary data is represented by the bytes type. Python3 won't mix str and bytes in any implicit way, which makes the distinction between the two very clear. You cannot concatenate strings and byte packets, search for strings in a byte packet (or vice versa), or input a string as a byte packet parameter (or vice versa ). This is a good thing, but it is mixed in python2. For example, when using socket network programming in pytho2 to pass strings, however, in python3, the string must be converted to the bytes type.

Conversion principle diagram:

1 >>>'€20'.encode('utf-8')2 b'\xe2\x82\xac20'3 >>> b'\xe2\x82\xac20'.decode('utf-8')4 '€20'

 

About hexadecimal:

  • Binary, 01
  • Octal, 01234567
  • Decimal, 0123456789
  • Hexadecimal, 0123456789 ABCDEF binary to hexadecimal conversion http://jingyan.baidu.com/album/47a29f24292608c0142399cb.html? Picindex = 1

 

7. All objects

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

Therefore, the following values are all objects: 22, "WD", ['A', 'B', 'C'], and are generated based on different classes.

 

8. Data Operations

Arithmetic Operation:

 

Comparison:

 

Assignment operation:

 

Logical operation:

 

Member calculation:

 

Identity calculation:

 

Bitwise operation:

 

Operator priority:

 

9. if else process judgment

Basic Syntax:

1 # Syntax 1 2 if condition: 3 pass 4 5 # syntax 2 6 if condition: 7 pass 8 else: 9 pass10 11 # syntax 3 12 if condition: 13 pass14 elif condition: 15 pass16... 17 else: 18 pass
View Code

Show column 1 if else:

1. Simulate user logon. The account and password are correct and the welcome information is printed.

2. incorrect user name or password Printing

 1 #/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author:W-D 4 user="WD" 5 passwd="123qwe" 6 username=input("username:") 7 password=input("password:") 8 if user==username and passwd==password: 9     print("welcome!")10 else:11     print("Invalid username or password! ")
View Code

Column 2: if elif else

1. Guess the number. Print the correct guess.

2. Guess big print guess big, guess small print guess small

1 num=222 guess_num=int(input("guess number:"))3 if guess_num > num:4     print("Too bigger!")5 elif guess_num < num:6     print("Too smaller!")7 else:8     print("yes, you are right!")
View Code  

Trielement operation of if:

1 result = value 1 if condition else value 2

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

Display column:

A = 22b = 33 number = a if a> B else B # print (number) Result: 33

 

10. while Loop

If the while LOOP does not have a clear ending mark, it will enter an endless loop. Therefore, we usually need to end the condition when writing the while loop.

Basic Syntax:

1 while end condition: 2 pass 3 4 # eg: 5 I = 1 6 while I <10: # The end condition is I greater than 10 7 print (I) 8 I + = 1 9 results: 10 111 212 313 414 515 616 717 818 9
View Code

Column 1:

It's still a digital game. Now we let players keep guessing, but at most three times.

1 #/usr/bin/env python 2 #-*-coding: UTF-8-*-3 # Author: W-D 4 count = 0 5 while count <3: 6 num = 22 7 guess_num = int (input ("guess number:") 8 if guess_num> num: 9 print ("Too bigger! ") 10 elif guess_num <num: 11 print (" Too smaller! ") 12 else: 13 print (" yes, you are right! ") 14 break # The role of break 15 count + = 1 will be mentioned later
View Code

In python, while has more invincible syntaxes. The above code is also used as an example,

1 #/usr/bin/env python 2 #-*-coding: UTF-8-*-3 # Author: W-D 4 count = 0 5 while count <3: 6 num = 22 7 guess_num = int (input ("guess number:") 8 if guess_num> num: 9 print ("Too bigger! ") 10 elif guess_num <num: 11 print (" Too smaller! ") 12 else: 13 print (" yes, you are right! ") 14 break # It will be mentioned later that break function 15 count + = 116 else: # The while condition does not meet the 17 print (" you have tried too wrong times! ") 18 results: 19 guess number: 3320 Too bigger! 21 guess number: 3322 Too bigger! 23 guess number: 3324 Too bigger! 25 you have tried too hours times!
While invincible syntax

 

11. for Loop

For Loop condition: the loop condition is an iteratable object, such as an array, dictionary, and file object.

Basic Syntax:

1 for variable in iteratable objects: 2 pass 3 4 eg: 5 for I in range (, 2): 6 #0 represents the start position, 2 represents the step size, 10 is the end position, but not included. 7 print (I) 8 Results: 9 010 211 412 613 8
View Code

 

12. break and continue

1. The role of break in a loop is to jump out of the loop and terminate the loop. For example, in the previous column, enter the correct number to stop the loop.

2. The function of continue in a loop is to jump out of this loop and the loop will continue.

Continue application scenarios:

Print them cyclically from 1 to 10. If the number is 5, do not print them.

1 for I in range (,): 2 if I = 5:3 continue # When the loop reaches 5, skip this loop and do not execute print4 print (I)
View Code

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.