author |Vishal Mishra
compile |VK
source |Towards Data Science
Welcome to Python course . In this chapter , We are going to study the document 、 Exception handling and other concepts . Let's start .
__name__ == '__main__'
What does that mean? ?
Usually , At every Python In the project , We'll all see the above statement . So what is it for , We are here to understand .
In short , stay Python in ,__name__
It's a special variable , It tells us the name of the module . Whenever it runs directly python file , It sets special variables before executing the actual code .__name__
It's a special variable . Determine according to the following points __name__
The value of the variable -
- If it runs directly python file ,
__name__
The name will be set to main. - If you import a module into another file ,
__name__
The name will be set to the module name .
__name__
'__main__'
first_module.py. Direct operation
first_module.py Import from other modules
Output
In first_module.py, Running from Import
In second_module.py. Second module’s name: main
In the example above , You can see , When you're in another python When the first module is imported into the file , It will enter else Conditions , Because the name of the module is not main. however , stay second_module.py, The name is still main.
So we use it under the following conditions
- When we want to perform certain specific tasks , We can call this file directly .
- If the module is imported into another module , And when we don't want to perform certain tasks .
It's best to create a main Method , And in if __name__ == __main__
Internal calls . therefore , if necessary , You can still call from another module main Method .
We can still call main Method to call another module's main Method , because main Methods should exist in the first module .
What to do if something goes wrong
Python Exception handling in
When we write any program in any programming language , Sometimes even if the statement or expression is syntactically correct , There are also errors in the execution process . Errors detected during the execution of any program are called exceptions .
Python The basic terminology and syntax used to handle errors in is try and except sentence . Code that can cause an exception to occur is placed in try In block , Exception handling in except Implementation in block .python The syntax for handling exceptions in is as follows -
try and except
try:
Do your operation …
...
except ExceptionI:
If there is any abnormality ExceptionI, Execute this block .
except ExceptionII:
If there is any abnormality ExceptionII, Execute this block .
...
else:
If there is no abnormality , Then execute this block .
finally:
No matter whether there is any abnormality , This block will always execute
Let's use an example to understand this . In the following example , I'm going to create a function to square numbers , In order to calculate the square , The function should always accept a number ( In this case, it's an integer ). But the user doesn't know about him / What kind of input does she need to provide . When the user enters a number , It works well , But if the user provides a string instead of a number , What's going to happen .
def acceptInput():
num = int(input("Please enter an integer: "))
print("Sqaure of the the number {} is {}".format(num, num*num))
acceptInput()
Please enter an integer: 5
Sqaure of the the number 5 is 25
It throws an exception , The program suddenly ended . therefore , To execute programs gracefully , We need to handle exceptions . Let's look at the following example -
def acceptInput():
try:
num = int(input("Please enter an integer: "))
except ValueError:
print("Looks like you did not enter an integer!")
num = int(input("Try again-Please enter an integer: "))
finally:
print("Finally, I executed!")
print("Sqaure of the the number {} is {}".format(num, num*num))
acceptInput()
Please enter an integer: five
Looks like you did not enter an integer!
Try again-Please enter an integer: 4
Finally, I executed!
Sqaure of the the number 4 is 16
such , And we can provide logic for handling exceptions . But in the same example , If the user enters a string value again . What will happen then ?
So in this case , It's best to enter... In a loop , Until the user enters a number .
def acceptInput():
while True:
try:
num = int(input("Please enter an integer: "))
except ValueError:
print("Looks like you did not enter an integer!")
continue
else:
print("Yepie...you enterted integer finally so breaking out of the loop")
break
print("Sqaure of the the number {} is {}".format(num, num*num))
acceptInput()
Please enter an integer: six
Looks like you did not enter an integer!
Please enter an integer: five
Looks like you did not enter an integer!
Please enter an integer: four
Looks like you did not enter an integer!
Please enter an integer: 7
Yepie...you enterted integer finally so breaking out of the loop
Sqaure of the the number 7 is 49
How to handle multiple exceptions
Can be in the same try except Block to handle multiple exceptions . You can have two ways -
- Provide different exceptions on the same line . Example :ZeroDivisionError,NameError :
- Provides multiple exception blocks . When you want to provide a separate exception message for each exception , It's very useful . Example :
except ZeroDivisionError as e:
print(“Divide by zero exception occurred!, e)
except NameError as e:
print(“NameError occurred!, e)
Include at the end except Exception:block
It's always good , You can catch any unwanted exceptions you don't know about . This is a general exception capture command , It will cause any type of exception in the code .
# Handle multiple exceptions
def calcdiv():
x = input("Enter first number: ")
y = input("Enter second number: ")
try:
result = int(x) / int(y)
print("Result: ", result)
except ZeroDivisionError as e:
print("Divide by zero exception occured! Try Again!", e)
except ValueError as e:
print("Invalid values provided! Try Again!", e)
except Exception as e:
print("Something went wrong! Try Again!", e)
finally:
print("Program ended.")
calcdiv()
Enter first number: 5
Enter second number: 0
Divide by zero exception occured! Try Again! division by zero
Program ended.
How to create a custom exception
It's possible to create your own exceptions . You can use it. raise Keywords to do .
The best way to create a custom exception is to create a class that inherits the default exception class .
This is it. Python Exception handling in . You can see a complete list of built-in exceptions here :https://docs.python.org/3.7/l...
How to deal with documents
Python File processing in
Python Use file objects to interact with external files on your computer . These file objects can be any file format on your computer , It can be an audio file 、 Images 、 text file 、 E-mail 、Excel file . You may need different libraries to handle different file formats .
Let's use ipython Command to create a simple text file , We'll learn how to do it in Python Read from the file .
%%writefile demo_text_file.txt
hello world
i love ipython
jupyter notebook
fourth line
fifth line
six line
This is the last line in the file
Writing demo_text_file.txt
Open file
You can open a file in two ways
Define an inclusion file Object's variables . After processing a file , We have to use file Object methods close Turn it off again :
f = open("demo_text_file.txt", "r") --- f.close()
Use with keyword . There is no need to explicitly close the file .
with open(“demo_text_file.txt”, “r”): ## Read the file
stay open In the method , We have to pass the second parameter that defines the file access pattern .“r” It's for reading files . Similarly ,“w” Means write ,“a” Indicates that it is attached to a file . In the table below , You can see more common file access patterns .
Read the file
stay python in , There are many ways to read a file -
- fileObj.read()=> The entire file will be read into the string .
- fileObj.readline() => The file will be read line by line .
- fileObj.readlines()=> The entire file will be read and a list will be returned . Use this method with care , Because this will read the entire file , So the file size should not be too large .
# Read entire file
print("------- reading entire file --------")
with open("demo_text_file.txt", "r") as f:
print(f.read())
# Read the file line by line
print("------- reading file line by line --------")
print("printing only first 2 lines")
with open("demo_text_file.txt", "r") as f:
print(f.readline())
print(f.readline())
# Read the file and return it as a list
print("------- reading entire file as a list --------")
with open("demo_text_file.txt", "r") as f:
print(f.readlines())
# Use for Loop read file
print("\n------- reading file with a for loop --------")
with open("demo_text_file.txt", "r") as f:
for lines in f:
print(lines)
------- reading entire file --------
hello world
i love ipython
jupyter notebook
fourth line
fifth line
six line
This is the last line in the file
------- reading file line by line --------
printing only first 2 lines
hello world
i love ipython
------- reading entire file as a list --------
['hello world\n', 'i love ipython\n', 'jupyter notebook\n', 'fourth line\n', 'fifth line\n', 'six line\n', 'This is the last line in the file\n']
------- reading file with a for loop --------
hello world
i love ipython
jupyter notebook
fourth line
fifth line
six line
This is the last line in the file
Writing documents
And read similar ,python The following are provided 2 A way to write a file .
- fileObj.write()
- fileObj.writelines()
with open("demo_text_file.txt","r") as f_in:
with open("demo_text_file_copy.txt", "w") as f_out:
f_out.write(f_in.read())
Read write binary
You can use binary mode to read and write any image file . Binary contains data in byte format , This is the recommended way to process images . Remember to use binary mode , With “rb” or “wb” Mode open file .
with open("cat.jpg","rb") as f_in:
with open("cat_copy.jpg", "wb") as f_out:
f_out.write(f_in.read())
print("File copied...")
File copied...
Sometimes when the file is too large , Block reading is recommended ( Read fixed bytes at a time ), In this way, there will be no out of memory exceptions . You can provide any value for the block size . In the following example , You'll see how to read a file in a block and write to another file .
### Copy the image with a block
with open("cat.jpg", "rb") as img_in:
with open("cat_copy_2.jpg", "wb") as img_out:
chunk_size = 4096
img_chunk = img_in.read(chunk_size)
while len(img_chunk) > 0:
img_out.write(img_chunk)
img_chunk = img_in.read(chunk_size)
print("File copied with chunks")
File copied with chunks
Conclusion
Now you know how to do exception handling and how to use Python Documents in .
Here is Jupyter Notebook Link to :https://github.com/vishal2505...
Link to the original text :https://towardsdatascience.co...
Welcome to join us AI Blog station :
http://panchuang.net/
sklearn Machine learning Chinese official documents :
http://sklearn123.com/
Welcome to pay attention to pan Chuang blog resource summary station :
http://docs.panchuang.net/