Python Commands for Beginners
An Introduction to Essential Python Commands for New Programmers
Website Visitors:List of basic python commands and data types:
Assignments and Expressions
In Python, an assignment is a statement that binds a value to a variable. An expression is a combination of values, variables, and operators that evaluates to a single value.
Assignments
An assignment statement has the following syntax:
|
|
The left-hand side of the assignment operator (=
) is a variable name, and the right-hand side is an expression that evaluates to a value. The value of the expression is assigned to the variable.
For example, the following assignment statement assigns the value of 10 to the variable x
:
|
|
Expressions
An expression is a combination of values, variables, and operators that evaluates to a single value. Expressions can be used to perform calculations, make comparisons, and control the flow of execution. Expressions are a combination of numbers, symbols, or other values that produce a result when evaluated.
There are many different types of expressions in Python. Some of the most common types of expressions include:
- Arithmetic expressions: These expressions perform mathematical operations, such as addition, subtraction, multiplication, and division.
- Logical expressions: These expressions evaluate to a Boolean value, which can be either
True
orFalse
. Logical expressions are used to make comparisons and control the flow of execution. - Comparison expressions: These expressions compare two values and evaluate to a Boolean value.
- String expressions: These expressions consist of a sequence of characters. String expressions can be used to create strings, print text, and format data.
- List expressions: These expressions consist of a sequence of values. List expressions can be used to create lists, store data, and perform operations on lists.
- Dictionary expressions: These expressions consist of a set of key-value pairs. Dictionary expressions can be used to create dictionaries, store data, and perform operations on dictionaries.
Expressions can be used in a variety of ways in Python. They can be used to perform calculations, make comparisons, and control the flow of execution. Expressions can also be used to create variables, objects, and data structures.
Keyword
A keyword is a reserved word in a programming language that performs a specific purpose. In your first Python example, you briefly encountered the keywords for and in. Note that keywords will often appear in bold in this course.
Values: True, False, None
Conditions: if, elif, else
Logical operators: and, or, not
Loops: for, in, while, break, continue
Functions: def, return
print()
: used to display a message or value on the console.
|
|
Return
The return
statement in Python is used to exit a function and specify the value to be returned to the caller of the function. When a return statement is executed in a function, that particular function execution is stopped and the code that follows will not be executed.
Example:
|
|
Input/Output Commands
print()
- used to print output to the consoleinput()
- used to take input from the user
Example:
|
|
Variables and Data Types
Variable: Variable is an instance of a data type class, represented by a unique name within the code, that stores changeable values of the specific data type.
-
variable_name = value
: used to assign a value to a variable. -
Variable types:
- Numeric:
int
,float
,complex
- String:
str
- Boolean:
bool
- NoneType:
None
- Numeric:
-
int
- used to define integers -
float
- used to define floating-point numbers -
bool
- used to define boolean values -
str
- used to define strings -
list
- used to define lists -
tuple
- used to define tuples -
set
- used to define sets -
dict
- used to define dictionaries
Example:
|
|
You can also use string concatenation like print(“Hello " + SomeVariable). Checkout this post on data types for more information:
Global variables vs local variables
In Python, a variable’s scope determines where it can be accessed and modified. There are two types of variable scopes: global and local.
A global variable is a variable that is defined outside of any function and can be accessed and modified from anywhere in the code. Global variables are often used to store data that needs to be shared between functions or modules.
A local variable is a variable that is defined inside a function and can only be accessed and modified within that function. Once the function exits, the local variable is destroyed and cannot be accessed from outside the function.
Here’s an example to illustrate the difference between global and local variables:
|
|
In this example, x
is a global variable that can be accessed and modified from anywhere in the code. Inside the my_function
function, x
is accessed as a global variable, and y
is a local variable that can only be accessed inside the function. When we try to access y
outside the function, it raises a NameError
because y
is not defined in the global scope. If you’d like to declare y as global variable, in the function, use global
keyword before y as shown below:
|
|
To delete a variable use del variableName
. This will delete that variable name.
Converting Data Types in Python
In Python, data types can be converted from one type to another using built-in functions. There are two types of data type conversion: implicit and explicit.
Implicit data type conversion is performed automatically by the Python interpreter. This type of conversion is used when the data type of an expression is not explicitly specified. For example, if you add an integer and a float together, the Python interpreter will automatically convert the integer to a float before performing the addition operation.
Implicit conversion is where the interpreter helps us out and automatically converts one data type into another, without having to explicitly tell it to do so.
Explicit data type conversion is performed by the programmer using built-in functions. This type of conversion is used when the data type of an expression needs to be explicitly specified. For example, if you want to convert a string to an integer, you would use the int()
function.
By contrast, explicit conversion is where we manually convert from one data type to another by calling the relevant function for the data type we want to convert to.
Here are some examples of implicit and explicit data type conversion in Python:
|
|
Sorted type
In Python, the sorted()
function is used to sort the elements of a list, tuple, or any iterable in ascending order by default. It returns a new sorted list without modifying the original iterable.
Here’s an example of how to use sorted()
:
|
|
Type() function
The type()
function in Python is used to get the type of an object. It returns the type of the object as a string.
Here’s an example of how to use type()
:
|
|
This will output <class 'int'>
, indicating that my_variable
is of type integer.
Max and Min Functions
The max() function returns the largest numeric input passed into it. The min() function returns the smallest numeric input passed into it.
|
|
None data type
In Python, None is a special constant representing the absence of a value or a null value. It is often used to signify that a variable or a function does not return anything.
|
|
Comments
#
: used to add comments in your code.
Arithmetic Operators
+
: addition-
: subtraction*
: multiplication/
: division//
: integer division%
: modulus (remainder)**
: exponentiation
Comparison Operators
==
: equal to!=
: not equal to>
: greater than<
: less than>=
: greater than or equal to<=
: less than or equal to=
: assignment
Python comparison operators return Boolean results (True or False) with strings:
Expression | Description |
---|---|
“a” == “a” | If string “a” is identical to string “a”, returns True. Else, returns False. If the words are the same, return True. Else, return False. |
“a” != “b” | If string “a” is not identical to string “b” |
“a” > “b” | If string “a” has a larger Unicode value than string “b” |
“a” >= “b” | If the Unicode value for string “a” is greater than or equal to the Unicode value of string “b” |
“a” < “b” | If string “a” has a smaller Unicode value than string “b” |
“a” <= “b” | If the Unicode value for string “a” is smaller than or equal to the Unicode value of string “b” |
print("Wednesday" > "Friday")
In Python, when comparing strings using the > (greater than) or < (less than) operators, it compares the strings lexicographically based on the Unicode values of their characters. Unicode values: A to Z, are from numbers 65 to 90. A is 65, B is 66, C is 67 and so on.. similarly, for values a to z, unicode value is from 97 to 122. a is 97, b is 98, c is 99 and so on…
In the case of “Wednesday” > “Friday”, the comparison evaluates to True. This is because in the Unicode character set, the letter “W” has a greater Unicode value than the letter “F”. Therefore, when comparing the two strings lexicographically, “Wednesday” is considered greater than “Friday”.
|
|
Logical Operators
and
: logical andor
: logical ornot
: logical not # can also be used as:print(not 55 = 'yellow')
Example:
|
|
Check out more about operators in the Python Operators article here
Conditional Statements
if
statement: used to check a condition and execute a block of code if the condition is true.if-else
statement: used to execute a block of code if the condition is true, and another block of code if the condition is false.if-elif-else
statement: used to execute a block of code if the first condition is true, another block of code if the second condition is true, and a final block of code if none of the conditions are true.
Example:
|
|
You can also specify if and else statements in a single liner like shown below:
|
|
We can also use return
command for conditions like:
|
|
|
|
In the above example, if number % 2 ==0, then the program returns true and exits the function immediately. return false
statement will only execute when number % 2 is not equal to 0. We can also specify conditions like this, instead of using else condition.
Loops
In Python, both the while
loop and the for
loop are used to execute a block of code repeatedly, but they differ in their approach and usage.
-
while
loop: Thewhile
loop is used when you don’t know the exact number of iterations in advance. A while loop executes the body of the loop while a specified condition remains True. They are commonly used when there’s an unknown number of operations to be performed, and a condition needs to be checked at each iteration. The loop continues to execute as long as the condition specified in thewhile
statement isTrue
. The condition is evaluated before each iteration of the loop. The loop will continue to execute until the condition becomesFalse
.-
Example:
1 2 3 4
i = 0 while i < 5: print(i) i += 1
-
-
for
loop:-
The
for
loop is used when you know the exact number of iterations in advance. -
The loop iterates over a sequence (such as a list, tuple, string, or range) and executes the block of code for each element in the sequence.
-
The loop variable takes on the value of each element in the sequence during each iteration.
-
Example:
1 2 3 4 5 6 7 8
fruits = ['apple', 'banana', 'cherry'] for fruit in fruits: print(fruit) # Example2: numbers = [1,2,3,4,5] sq_numbers = [x**2 for x in numbers] print(sq_numbers)
-
The main differences between while
and for
loops are:
-
Iteration control:
while
loop: The loop continues as long as the condition isTrue
.for
loop: The loop iterates over a sequence, with the loop variable taking on the value of each element in the sequence.
-
Readability and purpose:
while
loop: Typically used when the number of iterations is not known in advance or when the loop needs to be controlled by a specific condition.for
loop: Typically used when the number of iterations is known in advance or when you want to iterate over a sequence of elements.
-
Initialization and increment:
while
loop: You need to initialize and increment the loop variable manually.for
loop: The loop variable is automatically assigned the next value from the sequence.
Example:
|
|
Use
for
loops when there’s a sequence of elements that you want to iterate. Usewhile
loops when you want to repeat an action until a condition changes.
Range
In Python, the range
function is used to generate a sequence of numbers. It’s often used in for loops to iterate over a sequence of numbers.
The basic syntax of the range
function is:
|
|
Where:
start
is the starting number of the sequence (inclusive). If omitted, it defaults to 0.stop
is the ending number of the sequence (exclusive).step
is the increment between numbers in the sequence. If omitted, it defaults to 1.
Note that with range function, the result would be one less than the stop number. If you want to print numbers from 10 to 30, then in your range function, you should specify as range(10,31) so that the last number 31 is omitted and numbers till 30 are printed.
Here are some examples of each type of range
function in Python:
range(stop)
range(5)
generates the sequence0, 1, 2, 3, 4
range(10)
generates the sequence0, 1, 2, 3, 4, 5, 6, 7, 8, 9
range(x+3, y, z)
starts from a defined variable x, and adds 3 to it. if x is 2, then range starts from 5. range(5,y,z)
range(start, stop)
range(1, 6)
generates the sequence1, 2, 3, 4, 5
range(5, 10)
generates the sequence5, 6, 7, 8, 9
range(10, 15)
generates the sequence10, 11, 12, 13, 14
range(start, stop, step)
range(0, 10, 2)
generates the sequence0, 2, 4, 6, 8
range(1, 10, 3)
generates the sequence1, 4, 7
range(5, 20, 5)
generates the sequence5, 10, 15
Negative step
range(10, 0, -1)
generates the sequence10, 9, 8, 7, 6, 5, 4, 3, 2, 1
range(10, 0, -2)
generates the sequence10, 8, 6, 4, 2
Large ranges
range(100)
generates the sequence0, 1, 2, ..., 99
range(1000, 2000)
generates the sequence1000, 1001, 1002, ..., 1999
Note that range returns an iterator, not a list. This means it’s memory-efficient and can be used with large ranges without consuming too much memory. If you need to convert a range object to a list, you can use the list function:
|
|
Break
A break statement in Python provides a way to exit out of a loop before the loop’s condition is false. Once a break statement is encountered, the program’s control flow jumps out of the loop and continues executing the code after the loop.
|
|
Inorder to stop the infinite loop, use the
break
command to exit out of the loop.
Pass
A pass statement in Python is a placeholder statement which is used when the syntax requires a statement, but you don’t want to execute any code or command.
Lists and Tuples
Lists
list_name = [value1, value2, ...]
: used to create a list of values.list.append(value)
: used to add a value to the end of a list.list.insert(index, value)
: used to insert a value at a specific index in a list.list.remove(value)
: used to remove the first occurrence of a value from a list.list.pop(index)
: used to remove the value at a specific index from a list.list.index(value)
: used to find the index of the first occurrence of a value in a list.len(list)
: used to find the length of a list.list[0]
: starting value in the list
Complete details about lists are given here: Lists Explained
Example:
|
|
Tuples
tuple_name = (value1, value2, ...)
: used to create a tuple of values.- Tuples are immutable, which means their values cannot be changed once they are created.
len()
- used to get the number of elements in a tuple[]
- used to access individual elements in a tuple
Complete details about tuples are given here:Tuples Explained
Example:
|
|
Set Operations
len()
- used to get the number of elements in a setadd()
- used to add an element to a setremove()
- used to remove an element from a setunion()
- used to get the union of two sets (i.e., all unique elements from both sets)intersection()
- used to get the intersection of two sets (i.e., all elements that are common to both sets)difference()
- used to get the difference between two sets (i.e., all elements in the first set that are not in the second set)
Example:
|
|
{ } are called sets in Python.
Dictionaries
In Python, a dictionary is a built-in data type that stores a unordered and random collection of key-value pairs. Dictionaries are mutable, meaning they can be modified after creation.
Here are some key features of dictionaries in Python:
- Each key is unique and maps to a specific value.
- Keys can be strings, integers, or any other immutable type.
- Values can be any type, including strings, integers, lists, and even other dictionaries.
- Dictionaries are unordered, meaning the order of the key-value pairs is not preserved and are used with
{}
brackets - You can access a value by its key using the square bracket notation, e.g.,
my_dict['key']
. - You can add or update a key-value pair using the assignment operator, e.g.,
my_dict['new_key'] = 'new_value'
. - You can remove a key-value pair using the
del
statement, e.g.,del my_dict['key']
.
Here are some ways to add and remove values from dictionaries in Python:
Adding values to a dictionary:
-
Assignment: You can add a new key-value pair to a dictionary using the assignment operator (=).
1 2 3
my_dict = {'name': 'John', 'age': 30} my_dict['city'] = 'New York' print(my_dict) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
-
Update method: You can use the
update()
method to add multiple key-value pairs to a dictionary at once.1 2 3
my_dict = {'name': 'John', 'age': 30} my_dict.update({'city': 'New York', 'country': 'USA'}) print(my_dict) # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
-
Dictionary comprehension: You can use dictionary comprehension to create a new dictionary with additional key-value pairs.
1 2 3
my_dict = {'name': 'John', 'age': 30} new_dict = {**my_dict, 'city': 'New York', 'country': 'USA'} print(new_dict) # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
Removing values from a dictionary:
-
Del statement: You can use the
del
statement to remove a key-value pair from a dictionary.1 2 3
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'} del my_dict['age'] print(my_dict) # Output: {'name': 'John', 'city': 'New York'}
-
Pop method: You can use the
pop()
method to remove a key-value pair from a dictionary and return the value.1 2 3 4
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'} age = my_dict.pop('age') print(my_dict) # Output: {'name': 'John', 'city': 'New York'} print(age) # Output: 30
-
Clear method: You can use the
clear()
method to remove all key-value pairs from a dictionary.1 2 3
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'} my_dict.clear() print(my_dict) # Output: {}
Note that if you try to remove a key that doesn’t exist in the dictionary, you’ll get a
KeyError
. You can use thein
operator to check if a key exists in the dictionary before trying to remove it.
Examples:
dictionary_name = {key1: value1, key2: value2, ...}
: used to create a dictionary of key-value pairs.dictionary[key]
: used to access the value associated with a key in a dictionary.dictionary[key] = value
: used to add or modify a key-value pair in a dictionary.dictionary.keys()
: used to get a list of keys in a dictionary.dictionary.values()
: used to get a list of values in a dictionary.len()
- used to get the number of key-value pairs in a dictionary[]
- used to access the value associated with a key in a dictionary
Example:
|
|
|
|
Quick differences between set,list,string,tuple and dictionary:
Feature by Data Structure | Dictionary | Set | List | String | Tuple |
---|---|---|---|---|---|
Definition | Stores key:value pairs | An unordered collection of unique elements | A sequential, mutable collection of any data type | A sequential, immutable collection of textual data | A sequential, immutable collection of any data type |
Representation | { ‘a’:[42], ‘b’:[23,6,1] } | {’^2’, ‘mc’, ’ equal’, ‘E’} | [ ‘a’,‘b’, 3, 4 ] | “call me ishmael” | ( ‘commander’,’lambda’) |
How to create? | x = {}, x = dict() | x = set() | x = [], x = list() | x = (), x = str() | x = (‘a’,’b’,), x=tuple() |
Is structure mutable and allow duplicate elements? | immutable keys but mutable and duplicate values | mutable but unique elements only | mutable and allows duplicate elements | immutable but allows duplicate elements | immutable but allows duplicate elements |
Is the structure iterable? | no, it is unordered and random | no, it is unordered and unique | yes, and with numeric index assignment | yes, but with a sequence of textual data | yes, and with numeric index assignment |
Dictionaries versus Lists
Dictionaries are similar to lists, but there are a few differences:
Both dictionaries and lists:
-
are used to organize elements into collections;
-
are used to initialize a new dictionary or list, use empty brackets;
-
can iterate through the items or elements in the collection; and
-
can use a variety of methods and operations to create and change the collections, like removing and inserting items or elements.
Dictionaries only:
-
are unordered sets;
-
have keys that can be a variety of data types, including strings, integers, floats, tuples;.
-
can access dictionary values by keys;
-
use square brackets inside curly brackets { };
-
use colons between the key and the value(s);
-
use commas to separate each key group and each value within a key group;
-
make it quicker and easier for a Python interpreter to find specific elements, as compared to a list.
Lists only:
-
are ordered sets;
-
access list elements by index positions;
-
require that these indices be integers;
-
use square brackets ;
-
use commas to separate each list element.
String Operations
len()
- used to get the length of a string+
- used to concatenate strings*
- used to repeat a string[]
- used to access individual characters in a string
Checkout more about strings here: Strings Explained
Example:
|
|
Slicing and Joining Strings
In Python, you can slice and join strings using various methods. Here are some examples:
Slicing Strings
You can slice a string using the []
operator, specifying the start and end indices. The syntax is string[start:stop:step]
.
start
: The starting index of the slice (inclusive). Defaults to 0 if omitted.stop
: The ending index of the slice (exclusive). Defaults to the end of the string if omitted.step
: The increment between indices. Defaults to 1 if omitted.
Examples:
my_string = "hello"; print(my_string[1:4]) # Output: "ell"
my_string = "hello"; print(my_string[:4]) # Output: "hell"
my_string = "hello"; print(my_string[1:]) # Output: "ello"
|
|
Joining Strings
You can join multiple strings using the +
operator or the join()
method.
Using the +
operator
Example: print("Hello, " + "world!") # Output: "Hello, world!"
Using the join()
method
The join()
method takes an iterable of strings as an argument and concatenates them with a separator.
Example: print(", ".join(["apple", "banana", "cherry"])) # Output: "apple, banana, cherry"
You can also use the join()
method with a generator expression:
Example: print(" ".join(str(i) for i in range(5))) # Output: "0 1 2 3 4"
Combining slicing and joining strings
|
|
List Operations
len()
- used to get the length of a list+
- used to concatenate lists*
- used to repeat a list[]
- used to access individual elements in a listappend()
- used to add an element to the end of a listinsert()
- used to insert an element at a specific index in a listremove()
- used to remove an element from a listpop()
- used to remove and return the last element from a listsort()
- used to sort a list in ascending orderreverse()
- used to reverse the order of elements in a list
Example:
|
|
Branching
Branching in Python refers to the use of conditional statements to control the flow of a program. The most common branching statements in Python are if
, elif
(short for “else if”), and else
.
Here’s a basic example of branching in Python using if
, elif
, and else
:
|
|
In this example:
- The
if
statement checks ifx
is greater than 10. - The
elif
statement checks ifx
is less than 10. - The
else
statement is executed if none of the above conditions are met.
You can have multiple elif
statements to check for additional conditions. The code inside the block associated with the first true condition encountered will be executed, and the rest of the blocks will be skipped.
Functions
Block of code which is executed only when it is called. Repeated code is placed in this function block and it is called when needed in the script.
Defining Functions
def function_name(parameter1, parameter2, ...):
: used to define a function with parameters.return value
: used to return a value from a function.
Example:
|
|
Calling Functions
function_name(argument1, argument2, ...)
: used to call a function with arguments.
When you want to call the function, you should use function name and brackets (). In your function if you have a print statement, and you call that function using a print command outside that function, it will not result in anything because your function already has a print statement. When you use print again, it looks for a return value from the function. As there is no return value (you are printing a value not returning anything), it will not pick anything to print. So output will be none.
|
|
If you directly call myfunction()
, it will print the output as “This is function”. But if you use print (myfunction())
it displays none
in the output because there is no return value from the function. If you want to use print() for sure outside the function, then you should change the print command to return command as shown below:
|
|
Variable Annotation
In Python, annotation refers to the ability to add metadata to variables, functions, and other objects. This metadata is not used by the Python interpreter itself, but it can be accessed and used by other tools, such as type checkers, IDEs, and documentation generators.
Variable annotations (or type annotations), in particular, are a way to add a type hint or a description to a variable. They were introduced in Python 3.5 as part of the typing module.
Here’s an example:
|
|
In this example, name
and age
are variables with annotations. The : str
and : int
parts specify the expected type of the variable.
|
|
Annotations can be used for several purposes:
- Type hinting: As shown above, annotations can be used to specify the expected type of a variable. This can help with code readability and can be used by type checkers to catch type-related errors.
- Documentation: Annotations can be used to add a brief description of a variable, making it easier for others (and yourself) to understand the code.
- IDE integration: Many Integrated Development Environments (IDEs) can use annotations to provide features like code completion, type checking, and code refactoring.
It’s worth noting that annotations are not enforced by the Python interpreter, so you can still assign a value of a different type to a variable with an annotation. However, using annotations can help you write more maintainable and self-documenting code.
File Handling
Opening and Closing Files
file = open(filename, mode)
: used to open a file.file.close()
: used to close a file.read()
- used to read the contents of a filewrite()
- used to write data to a file
Modes in Python for file handling:
-
r - Read mode which is the default mode. Opens file for reading, error if the file does not exist.
-
w - Write mode which opens file for writing. Creates a new file if does not exist or truncates the existing file.
-
a - Append mode opens file for writing at the end of the file without truncating it. Creates a new file if does not exist.
-
r+ - Open file for both reading and writing. The file must exist.
-
w+ - Open file for both reading and writing. Creates a new file if does not exist or truncates the existing file.
-
a+ - Open file for both reading and appending. The file must exist.
-
x - Open file for exclusive creation, failing if the file already exists.
-
b - Binary mode which is used for binary files. Added to any of the above modes like rb, wb, etc.
-
t - Text mode (default). Open file for updating (reading and writing), failing if file does not exist.
Example:
|
|
Reading from Files
file_object = open(file_path, mode)
: used to open a file with a specified file path and mode.file_object.read()
: used to read the contents of a file.file_object.readline()
: used to read a single line from a file.file_object.readlines()
: used to read all lines from a file and return them as a list.
Writing to Files
file_object = open(file_path, mode)
: used to open a file with a specified file path and mode.file_object.write(string)
: used to write a string to a file.file_object.writelines(iterable)
: used to write an iterable to a file.
Appending to Files
file = open(filename, 'a')
: used to open a file in append mode.file.write(string)
: used to append a string to a file.
Closing Files
file_object.close()
: used to close a file that has been opened with theopen()
function.
Exception Handling
try-except Block
try
- used to wrap code that may raise an exceptionexcept
- used to handle exceptions that are raised in atry
blockfinally
- used to execute code regardless of whether an exception is raised
try-except-else Block
try:
# code that might raise an exception
except exception_type:
# code to handle the exception
else:
# code to execute if no exceptions are raised
Example:
|
|
Some key points:
-
The except block runs only if the exception mentioned occurs. Otherwise program flow moves to else.
-
Multiple except blocks can be used to handle different exceptions.
-
else block runs even if the exception was handled in except and program didn’t crash.
-
Code in else is guaranteed to run only when try succeeds without any exception.
try-except-finally Block
-
try:
# code that might raise an exception
-
except exception_type:
# code to handle the exception
-
finally:
# code to execute regardless of whether an exception was raised or not
Here is an example of using the try, except and finally blocks in Python:
|
|
The key points about try, except and finally:
-
try block contains the code that may raise an exception.
-
except block handles the specific exception. Here it handles ZeroDivisionError.
-
finally block contains the cleanup code that must be executed whether exception occurred or not.
-
Code in finally block is executed after try and except blocks.
-
If no exception occurs, finally runs after try block.
-
If exception occurs and is handled in except, finally runs after except.
-
finally block is useful to close files, database connections etc. to avoid resource leaks.
-
Code in finally ensures resources are cleaned even if program crashes in try or except.
So in summary, finally allows executing important cleanup code regardless of normal or exceptional program flow through try and except blocks.
Modules
Checkout Python Modules post for more information.
import
- used to import modules or packagesfrom
- used to import specific functions or classes from a module
Example:
|
|
Refactoring: When a code is updated to be more self-documenting and clarify the intent
Suggested Article
If you’d like to continue reading, checkout our other articles on python here or browse all other topics here.
Conclusion
This is not an exhaustive list of all Python commands and libraries, but it covers many of the most commonly used ones. As you continue to learn and use Python, you will likely encounter many more commands and libraries that are not listed here. Please let us know your feedback about this article in the comments section below.
Your inbox needs more DevOps articles.
Subscribe to get our latest content by email.