Source: Internet
Author: User

Second, the initial Python

1. The first line of Python code

>>> print ' Hello World!!! '
Hello World!!!

2. Python Interpreter declaration

#!/usr/bin/env python

3. Coding and Coding Declaration

# _*_ Coding:utf-8 _*_


Single-line Comment #

"' Multiple lines of comment

5. Script Parameters


SYS.ARGV #将输入的参数 $0,$1. Put it in a list, similar to the Shell's $*

6, byte code

If the file m.py file is imported into a file, then the M.pyc file is generated, and if the m.py file and the M.pyc file function the same, the import M.pyc file is preferred

7. Variables

To refer to something stored in an address in memory

name1= "Changqiangqiang"


If the name1 changes at this time, but the name2 does not change

But if name1 is not a string but a collection, then name2 will change;

In the C language, there are no strings, but characters, such as Hello, are composed of 5 characters, because Python is implemented by C, so the Python string is made up of C's character array [' H ', ' e ' ... ' o '].

String attributes: Once modified, it needs to be recreated (center space).

The evil "+" number: If the string is superimposed with the "+" sign, each "+" number needs to be re-opened into memory to create a space, resulting in degraded performance.

There are two types of data structures:

The first is the upright type: As long as the value changes, you need to re-open space;

The second is the reference type: value change, no need to re-open space;

The concept of the Python buffer pool

Within a certain range of values, which is the string within the buffer pool, the same variable points to the same string with the same ID value.

The Python interpreter performs the process of loading memory--and lexical analysis------and compile-and-byte code (c language is machine code)--Execute

8. Python Input and output

Name=raw_input (">>>")

Import Getpass

Pwd=getpass.getpass (">>>")

9. Process Control

"= =" only means the same value, "is" flag memory address is the same

If ...

Elif ...

else ...

10. Initial basic Data type

Scope two categories:

The first class is a single value: A number, a string, a Boolean value

The second class is the collection: list, tuple, dictionary, hash table (set)

String: The Evil string concatenation (+), do not use, using string formatting instead of

Two types of string formatting:

First type: name= "I am%s"% (' QQ ')

Second type: name= "I am {0} age{1}"

Print Name.format (' Alex ', 18)

Slice of string: name= ' Hello ' name[0]= ' a ' name[0:2]= ' he '

Len (name)-How many characters Name[-1]==name[len (name)-1]

String segmentation: Names= "Qq,hello" Name.split (",") =["QQ", "Hello"]--> character segmentation result as List

Created lists are essentially objects, both strings and lists support indexing


Common features of strings:

Remove whitespace





List of common actions: List content modification, memory address does not change (ID value is the same), does not create new memory space








Convert to String (opposite to split)

The same and different points for STR, list, and tuple:

Same point: Slice, index, Len (), include, loop;

Different points: Str modified after re-open space, list modified memory address unchanged, tuple does not allow modification;

Dictionary: Key-value pairs, dictionaries are unordered

Dictionary loop: for K,v in Name.items ():

Print K,v

12, the initial knowledge of the text operation

Find File

Open file: File_obj=file (file path, mode)

File operation, read and write: File_obj.read () #将所有写入内存

File_obj.readlines () #不仅读入内存, does not behave as a list

Mode: r--> read w--> If the file exists, rewrite it a--> append w+ (read-write)


For lines in File_obj.readlines: #每次循环, read-only one line, avoid all read-in memory

For line in File_obj.xreadlines (): #迭代器

File_obj.write ()

File_obj.writeline ()

File_obj.close () #关闭文件


First job:

Requirements: Write the login interface, enter the user name and password, after successful authentication display welcome information, the wrong three times after the lock.

[Email protected]:/scripts/seminor11/day01# cat login.py
#!/usr/bin/env python
# _*_ Coding:utf-8 _*_
Import Getpass
Import Sys
Chiper_file= ' Account.txt '


lock_file= ' lock_file.txt '

Lock_file_list = []
While Limit_times < 3:
Username=raw_input (' Please enter user name: '). Strip ()
f = File (Lock_file, ' R ')
For line in F.readlines ():
line = Line.strip ()
Lock_file_list.append (line)
F.close ()
If username in lock_file_list:
Print "\033[41;37m This account has been locked and cannot be logged in. Contact your administrator to unlock!!! \033[0m "
Sys.exit ()
f = File (Chiper_file, ' RB ')
For line in F.readlines ():
line = Line.strip ()
Line_list=line.split (';')
If not Chiper_dict.has_key (username):
Print "The user name does not exist, please re-enter!!!"
Limit_times +=1
Password=getpass.getpass (' Please enter password: '). Strip ()
If chiper_dict[username] = = Password:
Print "Welcome to login my system, HAHAHA!!!"
Sys.exit ()
Print "Authentication error, please re-enter!!"
Limit_times + = 1
F.close ()
Print "User name is locked"
f = File (Lock_file, ' AB ')
F.write (' {0}{1} '. Format (username, ' \ n '))
F.close ()

Second job:

Level three Menu

You can select to go to each submenu in turn

Required Knowledge: list, dictionary

Includes flowchart, README

[Email protected]:/scripts/seminor11/day01# cat menu.py
#!/usr/bin/env python
#_ *_ Coding:utf-8 _*_
Province= (' Shaanxi ', ' Gansu ', ' Guangdong ')
city={' Shaanxi ': [' Xian ', ' Xianyang ', ' Yanan ', ' Hanzhong '],
' Gansu ': [' Lanzhou ', ' Dingxi ', ' Tianshui ', ' Pingliang '],
' Guangdong ': [' Guangzhou ', ' Shenzhen ', ' Zhuhai ', ' Shantou '],

county={' Dingxi ': [' Tongwei ', ' Longxi ', ' Lintao '],
' XI ' an ': [' lintong ', ' Changan ', ' Taibai '],


Province= ""

While True:
Print Province
Num1_province=int (raw_input (' Please enter the number of provinces you want to view: '))

If not num1_province in range (1,len (province) +1):
print ' You have entered a wrong number,please try Again! '
print ' \ n you want to view the province is%s, its subordinate municipal units are as follows: \ n '% (Province[num1_province-1])

For I in range (len (city[province[num1_province-1])):
Print "%s,%s"% (i + 1,city[province[num1_province-1]][i])
Print "%s,%s"% (0, ' Return to previous level ')

Num1_city=int (raw_input (' Please enter the number of the city you want to query: '))

If not num1_city in range (0,len (city[province[num1_province-1]) +1):
print ' You have entered a wrong number,pliase try again!! '
elif num1_city = = 0:

For I in range (len (county[city[province[num1_province-1]][num1_city-1])):
Print "%s,%s"% (I+1,county[city[province[num1_province-1]][num1_city-1]][i])

Again=raw_input (' Do you want to continue querying (yes/no): '). Strip ()
If again = = ' No ':


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.