Python BASICS (1 ),

Source: Internet
Author: User

Python BASICS (1 ),
I. Version Selection

Shocould I use Python 2 or Python 3 for my development activity? Reposted from Python Official Website

Short version: Python 2.x is legacy, Python 3.x is the present and future of the language

Python 3.0 was released in 2008. the final 2.x version 2.7 release came out in mid-2010, with a statement of extended support for this end-of-life release. the 2.x branch will see no new major releases after that. 3.x is under active development and has already seen over five years of stable releases, including version 3.3 in 2012, 3.4 in 2014, and 3.5 in 2015. this means that all recent standard library improvements, for example, are only available by default in Python 3. x.

We can see that Python 2.x will not be updated after the last version is released.

Applicable to Python 2.x scenarios:

However, there are some key issues that may require you to use Python 2 rather than Python 3.

  • Firstly, if you're deploying to an environment you don't control, that may impose a specific version, rather than allowing you a free selection from the available versions.
  • Secondly, if you want to use a specific third party package or utility that doesn't yet have a released version that is compatible with Python 3, and porting that package is a non-trivial task, you may choose to use Python 2 in order to retain access to that package.
Ii. Basic knowledge of Python

1. Installation

Install Python on Mac

Because Mac comes with Python 2.7, it is best to use homebrew to install Python3.X, so that you do not need to modify the Python that comes with the system.

First install Homebre, and thenbrew install python3Install it.

But pay attention to the version when using it !!!

Install Python on Linux

The general Linux release comes with Python2.X by default. You also need to download the latest source code package and remember to modify the environment variables. In order to make other software provided by the system work normally, you also need to modify some configuration files, such as common yum.

After the installation, remember to use the python -- version command to verify that the version is correct.

2. How to Write and run Python programs

Use the Python interactive command line to write a program

Use the python command to open the file. It is easy to use, but cannot be saved. However, it can be used for routine testing. However, remember to press the table key when entering multiple rows and note the indentation.

Use a text editor

For example, Notepad ++, Sublime Text, and Pycham.

For example, you can directly select the "run" button for pycham and use F5 for Sublime Text.

When saving the file, use ". py" to end and declare that this is a Python program file.

 

To run a Python program, you must add executable permissions to the file.

Chmod + x hello. py

However, you must declare the interpreter in the program file. Otherwise, an error will be reported.

  

There is another way to execute python hello. py without permission.

  

Iii. Python Basics

1.1 Data Type

Integer, int, integer, such as 1, 20, and 100;

Floating Point Number, float, decimal point, such as 1.1 and 100.2;

String, str, any text enclosed in single or double quotation marks, such as 'Tom ', "haha", and '123 ';

Boolean. A boolean value can only be True or False. Boolean values can be calculated using and/or/not.

1.1 Variables

The variable name must be a combination of uppercase and lowercase letters, numbers, and _, but cannot start with a number;

Common naming methods, such as name_list and Name_List.

2.1 Input and Output

Python 2.X

In Python2.X, raw_input and input functions both have input functions, but there are differences, as shown in:

  

It can be seen that input is a variable by default. Therefore, when you enter tom directly, the prompt is not defined. You must add a single quotation mark to the prompt. If the input is str, the output is normal.

Python 3.X

In this version, input is a character by default, so no single quotation marks are required for input;

  

Because the default input is the numeric type, you need to add an int to convert it into an integer;

  

Input in Python 2. X is similar to eval function in Python 3. X.

  

2.2 practices

Enter a name and print it.

#!/usr/bin/env python3name = input("Please input your name: ")print(name)

Execution result

Please input your name: tomtom

3.1 conditional judgment if... else

If <condition judgment 1>: <execution 1> elif <condition Judgment 2>: <execution 2> elif <condition judgment 3 >:< execution 3> else: <execution 4>

According to the indentation rule of Python, if the if statement determines that it is True, the two-line indent statement will be executed; otherwise, nothing will be done. If the if statement is followed by an else statement, it means that if the if statement is False, the if statement is executed instead of the content of the if statement. Do not write less colons. If multiple judgments are used, elif can be used.

If the execution order of a statement is determined from the top down. if it is True in a certain judgment, the remaining elif and else are ignored after the corresponding statement is executed.

3.2 practices

Enter a name and a job. If the input name is tom and the job is cat, output "You are Tomcat! "

#!/usr/bin/env python3#__author__ = 'jack'name = input("Please input your name:   ")job = input("Please input your job: ")if job == 'cat':    print("You are Tomcat!")elif job == 'dog':    print("Your are dog.")else:    print("I don't know ...")

 

# Execution result Please input your name: kittyPlease input your job: I don't know... Please input your name: dogPlease input your job: dogYour are dog.

4.1 while LOOP

In Python programming, the while statement is used to execute a program cyclically. That is, under a certain condition, a program is executed cyclically to process the same task that needs to be processed repeatedly. The basic form is:

While judgment condition: execution statement ......

The execution statement can be a single statement or statement block. The condition can be any expression, and any non-zero or non-null value is true. When the condition is false, the loop ends.

Sample Code:

#!/usr/bin/env python3i = 0while i<3:    print(i)    i += 1
# Execution result 012

The while statement also has two important commands: continue and break to skip the loop; continue is used to skip the loop, and break is used to exit the loop.

Sample Code:

# Continue and break usage I = 1 while I <10: I + = 1 if I % 2> 0: # Skip output continue print I # output dual number 2, 4, 6, 8, 10i = 1 while 1: # print I # output 1 ~ must be set when the loop condition is 1 ~ 10 I + = 1 if I> 10: # break out of the loop when I is greater than 10

The else statement is used in the loop, and the statements in the else will be executed after normal execution.

Sample Code:

#! /Usr/bin/pythoncount = 0 while count <5: print count, "is less than 5" count = count + 1 else: print count, "is not less than 5" # output result 0 is less than 51 is less than 52 is less than 53 is less than 54 is less than 55 is not less than 5

4.2 practices

You must specify a lucky number, and then guess the output bingo!

#!/usr/bin/env python3luckey_num = 6while True:    choice = int(input("Please input you want :"))    if choice == luckey_num:        print("Bingo!!!")        break    elif choice > luckey_num:        print("Too bigger!!!")    else:        print("Too smaller!!!")

 

# Execution result Please input you want: 10Too bigger !!! Please input you want: 5Too smaller !!! Please input you want: 6 Bingo !!!

5. for Loop

A Python for loop can traverse any series of projects, such as a list or a string. Sample Code:

For I in range (10): print (I) # execution result 0123456789

Print the list cyclically. Sample Code:

#! /Usr/bin/pythonfruits = ['bana', 'apple', 'mango'] for index in range (len (fruits): print ('current fruit :', fruits [index]) print ("Good bye! ") # Execution result current fruit: banana current fruit: apple current fruit: mangoGood bye!

6. list and tuple

A built-in data type in Python is list: list. List is an ordered set that allows you to add and delete elements at any time.

For example, to print all the animals, you can use a list representation. for sample code, see 5for loop.

6.1 basic list operations

Append

Clear

Copy

Count statistical element

Extended

Index

Insert specified Index insert

Pop deletes the last element.

Remove Delete specified Element

Reverse flip

Sort sorting, which supports numbers and letters, but does not support mixed sorting

Zoo. append () add an element to zoo;

  

Zoo. copy () copy to another list;

  

Zoo. clear () clears the list;

  

Zoo. extend () extension, which combines two lists;

  

Zoo. count () counts the number of elements;

  

Zoo. index () outputs the index of an element;

  

Zoo. insert () inserts an element into the specified index;

  

Zoo. pop () deletes the last element;

  

Zoo. remove () deletes the specified element;

  

Zoo. sort () sorting, but cannot mix numbers and letters in Python 3. x;

  

Zoo. resverse () Flip;

  

Slice, similar to a character slice.

  

6.2 tuple

Another ordered list is tuple. Tuple and list are very similar, but tuple cannot be modified once initialized.

List and tuple are Python's built-in ordered sets. They are a variable and an immutable set. Use them as needed.

Iv. file I/O

1. 1 open function

To read and write a file, you must first use the Python built-in open () function to open a file and create a file object. The related auxiliary methods can call it for reading and writing.

file object = open(file_name [, access_mode][, buffering])

 

The parameters are described as follows:

  • File_name: The file_name variable is a string value that contains the name of the file you want to access.
  • Access_mode: access_mode determines the file opening mode: Read-only, write, append, and so on. For all values, see the complete list below. This parameter is not mandatory. The default file access mode is read-only (r ).
  • Buffering: If the buffering value is set to 0, there will be no storage. If the buffering value is set to 1, the row is stored when the file is accessed. If the buffering value is set to an integer greater than 1, it indicates the buffer size of the storage zone. If the value is negative, the buffer size in the storage area is the default value.

1.2 complete list of open files in different modes:

R open the file in read-only mode. The file pointer will be placed at the beginning of the file. This is the default mode. Rb opens a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode. R + open a file for reading and writing. The file pointer will be placed at the beginning of the file. Rb + opens a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file. W open a file for writing only. If the file already exists, overwrite it. If the file does not exist, create a new file. Wb opens a file in binary format and is only used for writing. If the file already exists, overwrite it. If the file does not exist, create a new file. W + open a file for reading and writing. If the file already exists, overwrite it. If the file does not exist, create a new file. Wb + opens a file in binary format for reading and writing. If the file already exists, overwrite it. If the file does not exist, create a new file. A. Open a file for append. If the file already exists, the file pointer is placed at the end of the file. That is to say, the new content will be written to the existing content. If the file does not exist, create a new file for writing. AB opens a file in binary format for append. If the file already exists, the file pointer is placed at the end of the file. That is to say, the new content will be written to the existing content. If the file does not exist, create a new file for writing. A + open a file for reading and writing. If the file already exists, the file pointer is placed at the end of the file. When the file is opened, the append mode is used. If the file does not exist, create a new file for reading and writing. AB + opens a file in binary format for append. If the file already exists, the file pointer is placed at the end of the file. If the file does not exist, create a new file for reading and writing.

1.3 attributes of a File object

After a file is opened, you have a file object. You can obtain various information about the file.

The following lists all attributes related to the file object:

Attribute description file. closed returns true if the object has been closed; otherwise, false is returned. File. mode: returns the access mode of the opened file. File. name: the name of the returned file. File. softspace if a space character must be followed after print is output, false is returned. Otherwise, true is returned.

The identifier 'R' indicates reading, so that a file is successfully opened.

If the file does not exist, the open () function runs out of an IOError and provides the error code and detailed information to tell you that the file does not exist:

F = open ('passwd. txxt ', 'R') print (f. read ())
F. close () # execution result Traceback (most recent call last): File "/Users/jack/Documents/git/change/Demo/s1/ts1.py", line 3, in <module> f = open ('passwd. txxt ', 'R') FileNotFoundError: [Errno 2] No such file or directory: 'passwd. txxt'

If the file is successfully opened, you can call the read () method to read all the content of the file at a time. Python reads the content to the memory, which is represented by a str object:

  

F = open('passwd.txt ', 'R') print (f. read ())
F. close () # Run the result admin

The last step is to call the close () method to close the file. After the file is used, it must be closed because the file object occupies system resources and the number of files that can be opened at the same time in the operating system is limited:

f.close()

An IOError may occur during file read/write operations. If an error occurs, the subsequent f. close () will not be called. Therefore, to ensure that the file is properly closed when an error occurs, try... finally:

File = open('passwd.txt ', 'R') try: data = file. read () print (data) finally: file. close () print (file. closed) # execution result adminTrue

Every write is a little complicated, so you can use the with statement to automatically call the close () method:

with open('passwd.txt') as f:    print(f.read())

The "with" Statement calls the "context manager" method in Python for the "f" file object. That is, it specifies "f" as a new file instance pointing to/etc/passwd content. In the code block opened by "with", the file is opened and can be read freely.

However, once the Python code exits from the "with" code segment, the file is automatically closed. Trying to read content from f after we exit the "with" code block will cause the same ValueError as above. Therefore, by using "with", you can avoid explicitly disabling file operations. Python will quietly close the file for you in a different Python style behind the scenes.

 

If the file is small, read () is the most convenient one-time reading. If the file has dozens of GB, the memory will be full. Therefore, we can call the read (size) method repeatedly to read size bytes each time. In addition, call readlines () to read all the content at a time and return the list by row. Therefore, you need to decide how to call it as needed.

If it is a configuration file, it is most convenient to call readlines.

With open('passwd.txt ') as f: for line in f: print (line) # execution result adminhahatomjack

 

With open('passwd.txt ') as f: for line in f. readlines (): print (line) # running result adminhahatomjack

2.1 write files

The only difference between writing a file and reading a file is that when the open () function is called, the incoming identifier 'W' or 'wb 'indicates writing a text or binary file:

With open('passwd.txt ', 'w') as f: f.write('zoo'{}runtime result, then the passwd.txt file zoo

Note that if the mode is 'w', the file cannot be read at the same time and the file content will be overwritten.

 

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.