current position:Home>Python notes-day12-exception capture (registration, login)
Python notes-day12-exception capture (registration, login)
2022-05-15 06:03:35【Wandering mage 12】
Preface
python Grammar learning , Leave it to those who need it , Understand everything !!
# coding=utf8
# @time:2022/4/21 15:04
# Author Haoyu
# One 、 Application of data persistence
# 1. Application of data persistence
'''''''''
1) The data that needs to be persisted should be saved through a file
2) When you need this persistent data , Do not give values directly , Instead, read the data from the file
3) If the persistent data changes , You need to write the latest value to this file again
'''''''''
'''''''''
# give an example : Count code execution times ?
# num = 0 # The number of times when the last execution
with open('resource/count.txt','rt',encoding='utf-8') as f:
num = int(f.read())
num += 1
with open('resource/count.txt','wt',encoding='utf-8') as f:
f.write(str(num))
print(num)
'''''''''
# Two 、 Log in to the registration system
# 1. Display the option interface
# 2. Give a choice
# 3. Realize the corresponding function according to the selection
'''''''''
Extra code :
# resource/page The contents of the document :
==========================
** Welcome to XX Management system **
@ 1. deng record
@ 1. notes book
@ 1. refund Out
===========================
# filemanager/filemanager.py Content
# Define a file reading function
def read_file(file_url:str):
with open(file_url,'rt',encoding='utf-8') as f:
return f.read()
def write_file(file_url:str,date:str,mode='w'):
with open(file_url,mode,encoding='utf8') as f:
f.write(date)
# resource/users.py Content
'''''''''
# _______________________________________
'''''''''
# Official code !!!!!!!!!!!!!!!!!!!!!
import filemanager.filemanager # Call the read file content package module
def show_main_page():
# 1) Call directly page.txt Contents of the document
# with open('resource/page.txt','rt',encoding='utf-8') as f:
# page = f.read()
# print(page)
#2) Encapsulate the file reading into a function module ( package ), Call directly
page = filemanager.filemanager.read_file('resource\page.txt')
while True:
# Print page
print(page)
# Give a choice
value=int(input(' Please select 1~3:'))
# Choose what you can't do
if value == 1:
print(' Sign in ')
login()
elif value == 2:
print(' register ')
register()
elif value == 3:
print(' sign out ')
return
else:
print(' Other situations ')
# notes Volume function module
def register():
# 1. Enter account number and password
user_name = input(' Please enter your account number :')
password = input(' Please input a password :')
# 2. Judge whether the account can be registered
# 1) First get all accounts that have been registered before
all_user = eval(filemanager.filemanager.read_file('resource/users.txt'))
# 2) Check whether the currently entered account is already in the registered account
if user_name in all_user:
print(' This account has been registered ')
return
# 3. register
# {} -> {user:pw}
all_user[user_name] = password
filemanager.filemanager.write_file('resource/users.txt',str(all_user))
print(' congratulations !!!! Registered successfully !')
# Login function module
def login():
# 1. Enter account number and password
user_name = input(' Please enter your account number :')
password = input(' Please input a password :')
# 2. Judge whether the login is successful
# 0) Get the previously registered account and the corresponding password
users = eval(filemanager.filemanager.read_file('resource/users.txt'))
# 1) Judge whether the entered account is a registered account
if user_name not in users:
print(' The account is not registered , Please register your account first ')
return
# 2) Judge whether the entered password is the same as the password at the time of registration
if users[user_name] != password:
print(' Wrong password ')
return
print(' Login successful ')
if __name__=='__main__':
show_main_page()
'''''''''
# 3、 ... and 、 Exception trapping
# 1. abnormal
# Program error is also called program exception ; If an exception occurs during the execution of the program , Then the program will end where there is an exception .
'''''''''
print('123')
list1 = [1,2,3]
print(list1[4]) # Report errors
print('321')
'''''''''
# 2. Exception trapping
# Exception capture is to prevent the program from crashing when there is another exception , Don't complain , Can continue to execute ;
# When to catch exceptions : Clearly know that some code may have errors , But there is no way or need to modify this code to avoid exceptions , You can use exception capture .
'''''''''
1) Grammar 1 :( Catch all types of exceptions )
try:
Code segment 1( Code snippets that need to catch exceptions )
except:
Code segment 2( A code segment that executes only when an exception occurs )
Other statements ......
Execution process : Execute the code segment first 1, If there is no exception, do not execute the code segment 2, Directly execute the following (try) The sentence of ;
If there is an anomaly , The program doesn't crash , Execute the code snippet now 2, Execute other statements after execution
# give an example
try:
age = int(input(' Please enter age :'))
except:
print(' Incorrect age entered ')
print(' Continue to open the game ')
2) Grammar II :()
try:
Code segment 1( Code snippets that need to catch exceptions )
except Exception types :
Code segment 2( Only when the specified exception type occurs will )
# give an example
try:
print(int('abc'))
except ValueError:
print(' Something unusual happened ')
print(' Continue to open the game ')
3) Grammar 3 :()
try:
Code segment 1( Code snippets that need to catch exceptions )
except ( Exception types 1, Exception types 2,.....):
Code segment 2( Only when the specified exception type occurs will )
'''''''''
try:
print(int('abc'))
except ValueError:
print(' Something unusual happened ')
print(' Continue to open the game ')
More secure sharing , Please pay attention to 【 Security info】 WeChat official account !
copyright notice
author[Wandering mage 12],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/131/202205110607424375.html
The sidebar is recommended
- Introduction to the differences between Python and Java
- Explain Python CONDA in detail
- The pycham downloaded by MAC reports an error as soon as it is opened. The downloaded Python interpreter is also the latest version
- From entry to mastery, python full stack engineers have personally taught Python core technology and practical combat for ten years
- Python is used to detect some problems of word frequency in English text.
- How to choose between excel, database and pandas (Python third-party library)?
- WxPython download has been reporting errors
- Pyside6 UIC and other tools cannot be found in the higher version of pyside6 (QT for Python 6). How to solve it?
- About Python Crawlers
- Successfully imported pandas, unable to use dataframe
guess what you like
How to extract some keywords in the path with Python
Python encountered a problem reading the file!
When Python is packaged into exe, an error is reported when opening assertionerror: C: \ users \ Acer \ appdata \ local \ temp\_ MEI105682\distutils\core. pyc
Eight practical "no code" features of Python
Python meets SQL, so a useful Python third-party library appears
100 Python algorithm super detailed explanation: a hundred dollars and a hundred chickens
[fundamentals of Python] Python code and so on
When Python uses probit regression, the program statement is deleted by mistake, and then it appears_ raise_ linalgerror_ Unrecognized error of singular
Python testing Nicholas theorem
Accelerating parallel computing based on python (BL) 136
Random recommended
- Python dynamic programming (knapsack problem and longest common substring)
- Django uses queryset filter save, and an 'queryset' object has no attribute 'Save' error occurs. Solution?
- Analysis of built-in functions in Python learning
- Python office automation - 90 - file automation management - cleaning up duplicate files and batch modifying file names
- Python office automation - 91 - word file Automation - word operation and reading word files
- After python, go also runs smoothly on the browser
- Self taught Python 26 method
- Summary of Python Tkinter component function examples (code + effect picture) (RadioButton | button | entry | menu | text)
- Python implementation of official selection sorting of Luogu question list
- Application of Django template
- Get project root path and other paths in Python project
- Get, rename, and delete file names in Python projects
- How to set the width and height of Python operation table
- Python string preceded by 'f' R 'B' U '
- JSON and other types convert to each other in Python
- Key value of key combination in pynput in Python
- Conversion of Python PDF file to word file
- Interface testing uses Python decorators
- Get the current time in Python
- Python course notes -- Python string, detailed explanation of related functions
- Python file and folder operations
- Python file content operation
- Three basic data quality evaluation methods and python implementation
- Python data structure and mathematical algorithm examples (continuously updating)
- GUI interface mail sending program based on SMTP protocol server and python language
- Python application tool development: mail sending GUI program
- Python application tool development: PIP instruction GUI program
- Application development based on Python and MySQL database: student information score management system version 1.0
- [Python] sort and sorted
- [Python] create a two-dimensional array with list, which is easy to step on
- Multiply [email protected]
- About creating in Python project folder__ init__. Understanding of PY
- Python, zsbd
- Smplify introduction and in python2 7 operation in environment
- Boost(2):boost. Python library introduction and simple examples
- Boost (3): encapsulate C + + classes into Python classes
- Boost (5): extract the type of C + + language and extract class from Python object
- Boost(6):Boost. How Python converts C + + parameter and return value types
- Boost(7):Boost. Python encapsulates overloaded functions and passes default parameters
- Boost(8):Boost. Python implements Python objects and various types of built-in operations and methods