Training day2 python

Today is the second day of training python, in the first day, the teacher taught some simple basic operation, then go back and I own a lot of practice, and did my homework

1. Assignment:

Achieve a landing procedure

code show as below

with open(r'file1.text','w',encoding='utf-8') as f:
 3     f.write('用户名:lzh,密码:108595.\n用户名:lzh,密码:1998.')
 4 
 5 def login():
 6     user = ''
 7     pwd = ''
 8     dict1 = {}
 9     with open('file1.text','rt',encoding='utf-8')as w:
10         for line in w:
11             line = line.split('\n')[0].split(',')
12             for data in line:
13                 if '用户名'in data:
14                     user = data[4:]
15                 else:
16                     pwd = data[3:]
17                 dict1[user] = pwd
18     while True:
19 user1 = input ( 'Enter Username:') strip ().
20 is
User1 in dict1 IF 21 is: 
22 is I =. 1 
23 is the while I <=. 3: 
24 pwd1 = INPUT ( 'Enter password:') Strip (). 
25 IF pwd1 == dict1 [user1]: 
26 is Print ( 'successful landing! ') 
27 BREAK 
28 the else: 
29 I = I +. 1 
30 the else: 
31 is Print (' wrong password more than three times')! 
32 the else: 
33 is Print ( '! user does not exist') 
34 is BREAK 
35 
36 Login () 
operation results 
please enter your user name: lzh 
enter password: 123 
Please enter password: 111 
Please enter password: 000 
wrong password more than three times!

2. Learn

Class today about a lot of things, mainly the following notes

(1)

A dictionary is disordered
1. Follow the key takes / stored value
>>> dict = { 'name': 'HY', 'Age': 23 is, 'Sex': 'MALE', 'School': 'ahpu'}
> >> print (dict [ 'school' ]) # take school
ahpu

 

GET 2. ()
>>> Print (dict.get ( 'School'))
ahpu
>>> Print (dict.get ( 'SAL'))
None
>>> Print (dict.get ( 'SAL', '15000 ')) the first argument is a # key, the second parameter is the default value, if the key is present then take the corresponding value, or default value
15,000

 

3. len ()
>>> print (len (dict))
4

 

4. members in operation in and Not
>>> Print ( 'name' in dict)
True
>>> Print ( 'SAL' in dict)
False

 

5. Remove del
>>> del dict [ 'name']

 

6. pop()
>>>dict1 = dict.pop('name')
>>>print(dict)
{'age' : 23, 'sex' : 'male', 'school' : 'ahpu'}
>>>print(dict1)
hy

 

>>> dict.popitem () # a random pop
>>> Print (dict)
{ 'name': 'HY', 'Age': 23 is, 'Sex': 'MALE'}

 

7. keys(),values(),items()
>>>print(dict.keys())
dict_keys(['name', 'age', 'sex', 'school'])

 

>>>print(dict.values())
dict_values([ 'hy', 23, 'male', 'ahpu'])

 

>>>print(dict.items())
dict_items([('name', 'hy'), ('age', 23), ('sex', 'male'), ('school', 'ahpu')])

 

8. cycle for
# loop all the dictionary Key
>>> I in for dict:
       Print (I)

 

9. update()
>>>dict2 = {'work' : 'student'}
>>>dict.update(dict2)
>>>print(dict)
{'name' : 'hy', 'age' : 23, 'sex' : 'male', 'school' : 'ahpu', 'work' : 'student'}

 

(2) tuple (in parentheses, separated by commas)
# Tuples are immutable type, the assigned immutable
>>> tuple = (1,2,3,4,5,6)
1. Press index values
>>> Print (tuple [2])
. 3
2. Section
>>> Print (tuple [0:. 6])
(1,2,3,4,5,6)
>>>print(tuple[0:6:2])
(1,3,5)
3. Only ()
>>> print (len (tuple))
6
4. members in operations in and not
>>> Print (1 in tuple)
True
>>> Print (1 not in tuple)
False
5. 循环
>>>for i in tuple:
       print(i)
(3) File:
# File read and write, using
# Text operation
#open (Parameter 1: file name, 2 parameters: operating mode Parameter 3: specifies the character encoding)
# F referred to handle
# R: read, read-only mode and can only be read but not write, being given file does not exist.
# W: only write, can not read, there is time to write the contents of the file back to the file and then emptied; file does not exist when the content is written after the file is created.
# A: you can be appended. File exists, write to the end of the file; the file does not exist when the content is written after the file is created.
# B mode is a common pattern, because all the files on the hard disk is stored in binary form, should be noted that: b mode read and write files, must not add encoding parameters, because no longer binary coding.
# File base has three modes of operation (default mode of operation is r mode):
        # r Read mode is
        # W mode Write
        # A to the append mode
# read the contents of a file in two formats (default read content mode to mode b):
        # T mode text
        # b mode bytes
        # Note that: t, b both modes can not be used alone, with the need to r / w / one of a conjunction.
# Open will have two resources, one is the python interpreter python files and resources, the end of the program will automatically recover python
# The other is the operating system to open the file of resources, the operating system does not automatically recover after the file is open, you need to manually recover resources
1. The file read and write operations
Write File # W
F = Open (FilePath, MODE = 'wt', encoding = 'UTF-. 8') # r may be added before the route path escape character becomes a normal character
f.write ( 'hello hy!' )
f.close () # file resource recovery
Read File # R & lt
F = Open (FilePath, 'RT', encoding = 'UTF-. 8') # default rt, mode may write
File reached, f.read = ()
Print (File)
f.close ()
Append file # A
F = Open (FilePath, 'AT', encoding = 'UTF-. 8') # default AT
f.write ( 'Hello YH')
f.close ()
# Write the differences between files and append: write file is written to a new file, or overwrite the original file content, additional content is added at the end of an existing file content
Context Management # file processing of
#with comes close () function is invoked automatically close after the file processing () closes the file
#写文件
with open(FilePath, mode = 'wt', encoding = 'utf-8') as f:
    f.write('life is short, u need python!')
#读文件
with open(FilePath, mode = 'rt', encoding = 'utf-8') as f:
    file = f.read()
    print(file)
#文件追加
with open(FilePath, mode = 'at', encoding = 'utf-8') as f:
    f.write('life is short, u need python!')

2. pictures and video read and write operations
Picture # write
Import Requests
PIC = requests.get (picPath) # from bing search image links
with Open (picPath, 'wb') AS f:
    f.write (pic.content)
# Read pictures
with Open (picPath, 'rb') AS f:
    File = f.read ()
    Print (File)
Image # copy operation
with Open (picPath1, 'RB') AS F1, Open (picPath2, 'WB') AS F2:
    PIC = f1.read ()
    f2.write (PIC)
# Video operation ditto
# Read file line by line
with Open (picPath1, 'rb') AS f1, Open (picPath2, 'wb') AS F2:
    # f1.read () # in order to open all the contents of the file, if the file size exceeds the memory size can cause memory overflow
    for i in f1: # read the contents of the file line by line, line by line written to the file content, to avoid memory overflow
        f2.write (i)
 
(4) function
# Function must be defined after the call
The syntax of the function #
# def :( full name define), the keyword is used to declare defined functions
# Function name: See name EENOW
# (): parentheses, it is stored outside of acceptable parameters
def cup (parameter 1, parameter 2, ...):
    '' '
    function declaration
    cups for drinking water containers and
    ' ''
    function body
    return Return value
# Function occurs in the definition phase of matter
  # 1. Turn on the python interpreter
  # 2. Load the python .py file
  # 3.python interpreter detects py file syntax, but will only detect python syntax, the function will not be executed body of code
Examples #
# registration function
the Register DEF ():
    '' '
    registration function
    ' ''
    the while True:
        the User the INPUT = ( 'Please enter your user name') .strip ()
        pwd = the INPUT ( 'Please enter your password') .strip ()
        re_pwd the INPUT = ( ' confirm password ') .strip ()
       
        # determines whether or not the same password twice
        iF pwd == re_pwd:
           
            # format string three methods
            user_info1 =' username:% s, password:% s'% (user, pwd )
            user_info2 = 'user name:} {password: {}'. the format (user, pwd)
           
            # f corresponds to a string before write back calls in this way more available format python3.6
            user_info3 = f 'username: user { }, password: pwd {} '
           
            # writing user information file
            Open with (f'c: / the Users / administortra / Desktop /} {User .txt ',' W ', encoding =' UTF-. 8 ') AS F:
                f.write (user_info3)
           
            BREAK
       
        the else:
            Print (' two passwords do not match, please re-enter! ')
           
# call the function function name () that is calling the function
register ()
 
 

 

 

 

Guess you like

Origin www.cnblogs.com/jacob1998/p/11013267.html