Python is arguably the most popular programming language on planet earth. This article aims to provide a fast way to get started with python. This is not a replacement for an in-depth tutorial. Check out the tutorial section in Python documentation if you have a few weeks to spare. Otherwise, read on.
I will be using Python 3 in this article since Python 2.7 is already sentenced to death. You should have Python 3.5 or later to follow the examples in this article.
This article assumes you have some programming experience in some other languages. If you have never programmed before, this tutorial is not for you.
What Is Python?
Python is a high level, interpreted programming language developed by Guido van Rossum. Python is dynamically typed, meaning you do not have to specify the data type of the variable when you define one. Python supports multiple programming paradigms. You are free to write your programs in object oriented way or in functional way or even in imperative way.
The latest version of Python at the time of this writing is 3.8 and 3.9 is already in development. The development of Python language is controlled by the non-profit Python Software Foundation.
That is all I can fit into a quick start. Check out the general Python FAQ if you want to know more.
Installation
If you are using a modern Linux distribution, Python should be already installed in your operating system. Open a terminal and type python3
. The Python shell will start and you can see the specific version number of your Python installation.
If you are on Windows, go to the Windows downloads section in Python website and download the latest Python 3 release. When you run the installer, do not forget to check the box that says Add python to your path
.
For Mac OS, go to the Mac OS downloads section in Python website and download the latest Python 3 release.
Depending on your operating system, you may have to type python
or python3
to invoke the Python interpreter. To find out which command to use, open a terminal (Command prompt or Powershell in Windows) and run the python3
command. If the python interpreter starts, you are all set to follow this guide. If it does not, try the command python
. You should be able to start Python 3 interpreter with one of these commands.
In certain cases, you may be able to invoke Python 3 interpreter using the command py
. I will be using python3
command in this article but you should use whichever is working for you.
Note for Windows users: I will be using an application called Terminal
to run commands and programs but it is not available natively in Windows. You have to use either the Command Prompt
or the Powershell
. Whenever you see Terminal
in this article, just substitute it with Command Prompt
or Powershell
.
Hello, World!
Let us get straight into the hello world ritual. Open a terminal and run the python3
command.
Python 3.6.8 (default, Oct 7 2019, 12:59:55)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
You will see a cursor blinking. This means the interpreter is ready to accept inputs from you. Type print("Hello, World!")
and press enter. You should see Hello, World!
printed on the console.
Python 3.6.8 (default, Oct 7 2019, 12:59:55)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")
Hello, World!
>>>
Great!. You have successfully executed your first program. The Python shell is a very powerful tool. It can help you to try out your ideas quickly before typing them into an actual file.
Now we have to put this in an actual python file and run it using python interpreter. Open your favourite text editor or IDE and create a hello.py
file. Enter the following line in it.
print("Hello, World!")
Open a terminal and use the cd
command to navigate to the directory which contains hello.py
file. Run the following command.
python3 hello.py
You should see Hello, World!
printed on to the screen.
A note on text editors and IDEs: Almost all modern text editors and IDEs have some level of support for Python. Once you start building complex applications with python, you should consider using a dedicated Python IDE. I use Visual studio code. PyCharm is another excellent option.
Comments
In python, comments start with a #
and continue untill the end of the line. You can start a comment in its own line or add it to the same line containing your program.
print("Hello") # Prints a message
# Prints a message
print("Hello")
I will use comments throughout this article to explain code fragments.
Data Types
Python’s type hierarchy is as follows.
None
Number
Integral
Integer
Boolean
Real
Complex
Sequence
Immutable sequence
String
Tuple
Bytes
Mutable sequence
List
Byte Array
Set types
Set
Frozen set
Mappings
Dictionary
There are few more types such as NotImplemented
, callable types (which includes functions and methods), modules etc but I have omitted those since it is beyond the scope of a quick start guide.
Here is a graphical hierarchy of most commonly used types.
Let us start with the simplest types first.
Strings
Strings are represented by either single quotes or double quotes. Both "Hello, World!"
and 'Hello, World!'
are valid string literals. Here is how you define a string variable in Python.
my_string = "This is a string"
Strings can be added together to create new strings.
first_name = "Harry"
last_name = "Potter"
full_name = first_name + " " + last_name
print(full_name)
This will output Harry Potter
.
Since python 3.6, you can use format strings to perform the same operation. If you have Python 3.6 or later, the above program can be rewritten as follows.
first_name = "Harry"
last_name = "Potter"
full_name = f"{first_name} {last_name}"
print(full_name)
The f
at the beginning of the string indicates that it is a formatted string. You can directly insert the value of a variable into a string literal by enclosing it in a pair of curly braces.
Strings supports multiplication also. This is a perfectly valid python program.
ten_harry = "Harry" * 10
print(ten_harry)
This will produce the output HarryHarryHarryHarryHarryHarryHarryHarryHarryHarry
.
Strings are immutable in python. Trying to modify a string will produce an error. The below program will result in a TypeError
.
name = "harry"
name[0] = "b"
There is a built-in len()
function to find the length of a string.
name = "Ned Stark"
length = len(name)
print(length) # Prints out 9
Numbers
Python has two types of numbers; integers and floating point numbers. The following operations are allowed on numbers.
Operation | Operator | Example | Output |
---|---|---|---|
Addition | + | 2 + 3 | 5 |
Subtraction | - | 3 - 2 | 1 |
Multiplication | * | 2 * 3 | 6 |
Division | / | 3 / 2 | 1.5 |
Integer division | // | 3 // 2 | 1 |
Modulus (Remainder) | % | 5 % 2 | 1 |
Exponent | ** | 2 ** 3 | 8 |
Numbers are also immutable. Besides integers and floating point numbers, python has a complex number type. I am not going to cover it here. Refer the docs if you are interested in complex numbers.
Lists
Lists are similar to arrays in other programming languages. They are heterogeneous and can be extended dynamically. You can create a list with numbers and strings in it.
There are two ways to define lists. You can either use the list()
constructor or the []
literal. []
literal can also take initial values. Literal initialisation is the preferred over construction function.
# Constructor initialisation
list1 = list()
# Literal initialisation
list2 = []
# Literal with initial values
list3 = [1, 2, 3.0, "four"]
Subscript notation is used to access the elements and modify them. As usual, list indexes start at 0.
list_obj = [1, 2, 3]
print(list_obj[2]) # Prints out 3
list_obj[2] = 4 # list_obj is now [1, 2, 4]
list_obj[3] = 5 # Error! You cannot modify a non existant index.
You can use the append
method to add new items and remove
method to remove an item from the list. If you have the same item more than once in the list, the remove
method will remove the first item from the list. There is also a pop
method to remove the last item from the list.
list_obj = [1, 2, 3]
list_obj.append(4) # list_obj is now [1, 2, 3, 4]
list_obj = [1, 2, 3, 4, 3]
list_obj.remove(3) # list_obj is now [1, 2, 4, 3]
list_obj = [1, 2, 3, 4]
list_obj.pop() # list_obj is now [1, 2, 3]
Check out the official documentation for the full list of methods.
The built-in len
function is used to get the length of a list. Remember, len
is a top-level function, not a method in the list object.
list_obj = [1, 2, 3]
length = len(list_obj) # Value of length is 3
Tuples
Tuples are the immutable siblings of lists. You can use them to store a list of values but unlike lists, you are not allowed to change the tuple after initialisation. You can either use the tuple()
constructor or the ()
literal to create new tuples. The parenthesis are optional in unambiguous situations.
t1 = tuple() # An empty tuple
t2 = () # Another empty tuple
t3 = (1, 2, 3) # Tuple containing 1, 2 and 3
t4 = 1, 2, 3 # Another tuple containing 1, 2 and 3
When creating a tuple with one element, the trailing comma is always required.
t = (1) # Wrong! Value of t is integer 5 now.
t = (1,) # Correct. t is now a tuple with element 1
Like lists, the subscript notation can be used to access values inside a tuple. Tuple index starts from 0.
t = (1, 2, 3)
print(t[0]) # Prints out 1
Trying to modify a tuple will result in a TypeError
.
t = (1, 2, 3)
t[1] = 10 # Error! 'tuple' object does not support item assignment
Things become complicated when you have a mutable object such as a list inside a tuple. You can now modify the mutable element but not the container tuple.
t = (1, [2, 3], 4)
t[1][1] = 10 # This is fine. t is now (1, [2, 10], 4)
t[1] = [2, 20] # Error. You are not allowed to modify the tuple object.
A tuple containing a mutable element is still immutable but it is not hashable. This is an important distinction. You will learn more about in this in later sections.
Another interesting feature of tuples is tuple unpacking. This can be used for swapping the values of two variables, returning multiple values from a function etc.
a = 10
b = 20
a, b = b, a # Values are swapped. Now a is 20 and b is 10.
The built-in len
function can be used to get the length of a tuple.
t = (1, [2, 3], 4)
print(len(t)) # Prints out 3
Sets
Sets are non-ordered collection of hashable elements. The order in which you insert element is not preserved in the set. You cannot use subscript notation to access elements because of this. Also, the definition says hashable not immutable. What is means is that you cannot insert an immutable object into a set if that object contains any mutable elements.
For creating sets, you can use the set()
constructor or the {}
literal. Creating an empty set is a special case. You must use the constructor method since {}
literal will create a dictionary.
set_obj = {1, 2, 3} # Set with 1, 2 and 3
another_set = set() # An empty set
not_a_set = {} # This is not a set. This will create a dictionary.
t = (1, 2)
set_obj = {t} # This is fine since t contains only immutable elements.
t = (1, [2, 3], 4)
set_obj = {t} # Error! Tuple t is not hashable.
Python sets come with the full power of sets in Mathematics. You can do union, intersection, difference etc. on them. This also means you cannot have the same element twice in the set. This property is often used to remove duplicates from a list.
s = {1, 1, 2, 2, 3, 3} # s is {1, 2, 3}
s.add(4) # s is {1, 2, 3, 4}
s.add(4) # s is still {1, 2, 3, 4}
s1 = {1, 2, 3, 4, 5}
s2 = {4, 5, 6, 7, 8}
# Union
s = s1.union(s2) # s is {1, 2, 3, 4, 5, 6, 7, 8}
# Intersection
s = s1.intersection(s2) # s is {4, 5}
# Difference
s = s1 - s2 # s is {1, 2, 3}
s = s2 - s1 # s is {6, 7, 8}
Here is how you use sets to filter out duplicates from a list. The list should not contain any non-hashable objects.
numbers = [1, 2, 3, 3, 4, 5, 1, 4]
unique_numbers = list(set(numbers)) # [1, 2, 3, 4, 5]
Like any other sequence types, you can use the len
function to find the length of a set.
Dictionaries
Dictionaries store objects as key-value pairs. This is similar to hashmaps or associative arrays in some other languages. The value can be any python object but the key must be a hashable object. Like any other sequence type, there is a literal way and a constructor way to create new dictionaries.
dict_obj = {} # New empty dictionary
another_dict = dict() # Another empty dictionary
# Dictionary with string keys and values..
person = {
"name": "Arya Stark",
"house": "Stark",
"home_land": "Winterfell",
"organisation": "Faceless men",
}
Keys are not limited to strings but they are the most common ones. Value can be compound types such as lists, tuples etc. You can even create nested dictionaries by using another dictionary as the value.
You can use the subscript notation with keys to access values. Using the subscript notation with a non-existing key will produce a key error. There is a get()
method that will return None
if the key is not present in the dictionary. The get()
method can take an optional second argument. This will be used instead of None
if the key is not present.
person = {
"name": "Arya Stark",
"house": "Stark",
"home_land": "Winterfell",
"organisation": "Faceless men",
}
name = person["name"] # Name is Arya Stark
name = person.get("name") # Name is Arya Stark
current_location = person["current_location"] # Key Error
current_location = person.get("current_location") # current_location is None
current_location = person.get("current_location", "Unknown") # current_location is Unknown
Dictionary has 3 methods for accessing the list of keys and values. These methods will return a custom iterator but you can use them as a list. Custom iterators are beyond the scope of a quick start.
person = {
"name": "Arya Stark",
"house": "Stark",
"home_land": "Winterfell",
"organisation": "Faceless men",
}
keys = person.keys() # keys is ['name', 'house', 'home_land', 'organisation']
values = person.values() # values is ['Arya Stark', 'Stark', 'Winterfell', 'Faceless men']
items = person.items() # items is [('name', 'Arya Stark'), ('house', 'Stark'), ('home_land', 'Winterfell'), ('organisation', 'Faceless men')]
None
None
indicates the absence of a value. None
is probably the most dangerous object in python.
no_value = None # An object with value None
Boolean
Boolean objects are used to indicate true or false. There are two boolean values in python, conveniently named as True
and False
.
my_boolean = True # Boolean object with value True
another_boolean = False # Boolean object with value False
The commonly used boolean operations in python are and
, or
and not
.
Operation | Result |
---|---|
True and True |
True |
True and False |
False |
False and True |
False |
False and False |
False |
True or True |
True |
True or False |
True |
False or True |
True |
False or False |
False |
not True |
False |
not False |
True |
The following comparison operators are also there if you need them.
Operator | Operation |
---|---|
== | Equal to |
!= | Not equal to |
< | Less than |
> | Greater than |
<= | Less than or equal to |
>= | Greater than or equal to |
You can also use multiple comparison operators in the same expression. For example, instead of writing number > 10 and number < 10
, you can use 10 < number < 20
Boolean operations use short circuit evaluation. and
will not evaluate the second expression if the first expression is false
and or
will not evaluate the second expression if the first expression is true
. The following code will never result in a zero-division error.
result = True or 0/0
result = False and 0/0
Apart from boolean False
, the following objects evaluate to false.
- Empty strings, tuples, lists, sets and dictionaries.
- Integer
0
and floating point0.0
None
Conditional Statements
For conditional evaluation, python has if
statements and a ternary expression. There is no switch statement in python.
if Statements
If statements execute a block of code when the condition is true.
greet = True
if greet:
print("Hello there!")
print("You got a greeting")
This syntax might feel strange at first glance. There are no parenthesis and curly braces. This is how we define blocks in python. A colon(:
) denotes the starting of the if
block and the statements in that block is indented.
The new line and indentation is optional if you have only one statement in your block.
greet = True
if greet: print("Greetings!")
4 space indentation is preferred in python. From Python 3 onwards, the use of spaces and tabs together is not allowed. The number of spaces or tabs is not required to be consistent across blocks. The code below is perfectly valid but you should not do this since it confuses the reader.
number = 10
if number < 20:
print("Smaller than 20") # 4 spaces indentation
if number > 5:
print("Greater than 5") # 2 spaces indentation
Using inconsistent indentation levels in the same block will result in an error. The following code will not work.
greet = True
if greet:
print("Spam")
print("Eggs")
if…else Statements
The if
statement can have an optional else
clause. The else block takes no conditional expression.
number = 25
if number % 2 == 0:
print("Number is even")
else:
print("Number is odd")
if…elif…else Statements
if
statements can have any number of elif
blocks. Like the if
clause, the elif
clause requires a conditional expression.
score = 75
if score > 80:
print("Outstanding")
elif score > 60:
print("Exceeds expectations")
elif score > 40:
print("Acceptable")
else:
print("Dreadful")
Ternary Expression
Python does not have the traditional ternary operator but has a ternary expression. This takes the following form.
value1 if condition else value2
Here is how you replace an if statement with ternary expression.
score = 60
if score > 50:
result = "pass"
else:
result = "fail"
The equivalent ternary expression is as follows.
score = 60
result = "pass" if score > 50 else "fail"
The is
Operator
So far we have used the ==
operator for checking equality. There also an is
operator for checking equality. ==
checks objects by its value while is
checks the objects by their identity. The following example illustrates the difference.
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # Prints True
print(a is b) # Prints False
a == b
returns true because both a
and b
has the same value. a is b
returns false because a
and b
are two different objects.
Loops
Python has while
loops and for
loops. There is no do...while
loop.
while Loop
Python while loops are similar to the while loops in other languages. It takes a condition and runs the loop body until the condition becomes false. Here is a count down example using while loops.
counter = 10
while counter > 0:
print(counter)
counter = counter - 1
print("Lift Off!")
You will get the following output if you run this.
10
9
8
7
6
5
4
3
2
1
Lift Off!
Rules about blocks and indentation are similar to the rules of if statements.
You might be tempted to use the decrement operator, --
, for decrementing the count. You will get an error if you try counter--
instead of counter = counter - 1
. There is no increment or decrement operator in python. You can, however, write it as counter -= 1
.
When the body contains just one statement, the line break and indentation are optional. Here is one tiny infinite loop for you.
while True: print("You are in an infinite loop.")
for Loop
Python for
loops are different from the traditional C-style for loops. for
loop takes an iterable and run the loop body with each element in that iterable. Here is how you iterate over a list using the for loop.
houses = ["Arryn", "Baratheon", "Lannister", "Stark", "Targaryen"]
for house in houses:
print(house)
Arryn
Baratheon
Lannister
Stark
Targaryen
You can iterate over any python sequence such as list, tuple, string etc. You might not get what you expect if you try to iterate over a dictionary.
person = {
"name": "Arya Stark",
"house": "Stark",
"home_land": "Winterfell",
"organisation": "Faceless men",
}
for item in person:
print(item)
name
house
home_land
organisation
You will get the keys in the dictionary. This is similar to iterating over person.keys()
. For more control, you can iterate over person.values()
or person.items()
. Refer back to the dictionaries section if you do not remember these dictionary methods.
The range Function
Iterating over a range of numbers is a common task in programming. Python has a built-in range()
function for this. Here is a straight forward example.
for number in range(5):
print(number)
0
1
2
3
4
Note that the iteration starts at 0 and 5 is not included. You can also specify a start index.
for number in range(5, 10):
print(number)
5
6
7
8
9
The range function can accept a step parameter as its third argument. Here is how you generate multiples of 3.
for number in range(3, 15, 3):
print(number)
3
6
9
12
You can use step argument to make range count backwards.
for number in range(5, 0, -1):
print(number)
5
4
3
2
1
break and continue
Python loops support the C-Style break and continue statements. There working is exactly the same as in other languages.
Here is an example of the continue statement.
for number in range(5):
if number == 2:
continue
print(number)
0
1
3
4
And here is an example with a break.
for number in range(5):
if number == 2:
break
print(number)
0
1
Other Looping Techniques
Python has a ton of facilities to assist looping. There is a looping techniques section in python documentation which explains some of those.
The for and while loops can have an optional else
clause. I have omitted this to keep things simple. Do your research if you want to know more.
Functions
Functions are first-class citizens in python. You can assign them to variables, pass them around between functions and return functions from functions. The def
keyword is used to define a new function and a pair of parenthesis is used to invoke a function.
def hello():
print("Hello, World!")
hello()
Hello, World!
Functions can accept parameters.
def hello(name):
print(f"Hello, {name}!")
hello("Harry")
Hello, Harry!
You can provide a default value to make the parameter optional.
def hello(name="World"):
print(f"Hello, {name}!")
hello()
hello("Harry")
Hello, World!
Hello, Harry!
The return
statement is used to return a value from a function.
def add(num1, num2):
return num1 + num2
sum = add(2, 3)
print(sum)
5
Keyword Arguments
Until now, we were passing arguments as positional arguments. You can also use pass them as keyword arguments. Instead of hello("harry")
, you can do hello(name="harry")
. When you use keyword and positional arguments together, positional arguments should come before keyword arguments.
def add(num1, num2, num3):
return num1 + num2 + num3
# Correct ways to invoke add
add(1, 2)
add(num1=1, num2=2, num3=3)
add(1, num2=2, num3=3)
add(1, 2, num3=3)
# Wrong!
add(num1=1, 2, 3)
add(1, num2=3, 3)
add(num1=1, num2=2, 3)
Arbitrary Number Of Arguments
Some functions take a variable number of arguments. For example, an average function can take any number of integers and return the average of all the integers passed. You could use a list for this.
def average(numbers):
return sum(numbers) / len(numbers)
average([1, 2, 3, 4])
average([10, 20])
average([100])
(sum is a built-in function for finding the sum of a sequence of numbers.)
Since these types of functions are very common, Python has a special syntax for this.
def average(*args):
return sum(args) / len(args)
average(1, 2, 3, 4)
average(10, 20)
average(100)
You do not need to create a list of numbers now. This makes your code clean and readable. Using args
as the parameter name is just a convention. You could use any other name if that makes more sense.
There is also a special syntax for passing an arbitrary number of keyword arguments. For this, you have to use the **
syntax.
def show_profile(**profile):
print(profile)
show_profile(first_name="Harry", last_name="Potter", species="Wizard")
show_profile(name="Dobby", species="Elf", job="Free Elf")
{'first_name': 'Harry', 'last_name': 'Potter', 'species': 'Wizard'}
{'name': 'Dobby', 'species': 'Elf', 'job': 'Free Elf'}
Classes And Custom Objects
Like many other languages, classes form the basis of object oriented programming in Python. The class
keyword is used to define a new class. You do not have to use the new
keyword to instantiate an object. The .
notation is used to access attributes and invoke methods.
class Greet:
name = "Harry"
greeting = Greet()
print(greeting.name)
Harry
You need an additional level of indentation when defining methods. Instance methods should take the current object as their first parameter.
class Greet:
def say_hello(self):
return "Hello, World!"
greeting = Greet()
greeting.say_hello()
Hello, World!
self
is not a python keyword. Naming the current instance parameter as self
is a convention. You can name it as this or that or whatever you want but it is strongly discouraged.
The self
object is used to access attributes and methods in the same class.
class Greet:
greeting = "Hello, World!"
def say_hello(self)
print(self.greeting)
greeting = Greet()
greeting.say_hello()
Hello, World!
You can also pass arguments to functions.
class Greet:
greeting = "Welcome"
def say_hello(self, name, house):
print(f"{self.greeting}, {name} of house {house}!")
greeting = Greet()
greeting.say_hello("Arya", "Stark")
Welcome, Arya of House Stark!
When you call a method, you do not have to pass the self
parameter. It is implied.
You can use positional arguments, keyword arguments, default values and arbitrary number of arguments just like any other normal function.
The Constructor
In python, the special name __init__
is used to indicate a constructor function. Constructors can accept arguments just like any other method. You should not return anything from a constructor.
class Person:
def __init__(self, name, house):
self.name = name
self.house = house
def say_hello(self):
print(f"Hello, {self.name} of house {self.house}")
bran = Person("Brandon", "Stark")
bran.say_hello()
Hello, Brandon of House Stark
From our constructor function, we have assigned the name and the house to self
. You can later access these values from other methods using self
. This is similar to this
object in many other languages.
Inheritance
Python supports single and multiple inheritance. There are no interfaces in python. To inherit a class from another class, put the base class name in parenthesis when you define the child class.
class BaseGreeting:
def base_hello(self):
print("Hello from base")
class Greeting(BaseGreeting):
def child_hello(self):
print("Hello from child")
hello = Greeting()
hello.base_hello()
hello.child_hello()
Hello from base
Hello from child
You can put multiple base classes by separating them using a comma. Python uses left-to-right ordering for method and attribute resolution. If the same method or attribute is defined in multiple base classes, python will take the one defined in the left-most base class.
class BaseOne:
def hello(self):
print("Hello from BaseOne")
class BaseTwo:
def hello(self):
print("Hello from BaseTwo")
class Hello(BaseOne, BaseTwo):
pass # Indicates empty body
greet = Hello()
greet.hello()
Hello from BaseOne
The pass
statement is used to indicate an empty block. You can use pass
with functions, loops etc.
Modules and Packages
All the programs we wrote till now were on a single file. When you have a large application, you might want to split them into multiple files. Modules and packages are there for your rescue.
Modules
Modules are just python files. You can write a bunch of python in one file and import them into another file.
For understanding modules, let us create one file with our greeter code and another file which uses code in our greeter file. When you try this out, make sure you put them in the same folder.
greeter.py
HELLO_WORLD = "Hello, World!"
class Greeter:
def say_hello(self):
print("Hello!")
def say_greetings():
print("Greetings!")
We have defined a variable, a class and a function in our module. Using an all upper-case name is a convention when defining module level variables.
Now, let us create our second file which uses greeter.py
.
hello.py
import greeter
# Uses the variable
print(greeter.HELLO_WORLD)
# Uses the class
greet = greeter.Greeter()
greet.say_hello()
# Uses the function
greeter.say_greetings()
Hello, World!
Hello!
Greetings!
Instead of importing the entire module, you can import each item one by one. If you do so, you can skip the module.
prefix. Here is how it looks in hello.py
.
from greeter import HELLO_WORLD, Greeter, say_greetings
# Uses the variable
print(HELLO_WORLD)
# Uses the class
greet = Greeter()
greet.say_hello()
# Uses the function
say_greetings()
Instead of from greeter import HELLO_WORLD, Greeter, say_greetings
, you could also write from greeter import *
. This will import everything in greeter.py
into hello.py
. This is considered unpythonic and strongly discouraged.
Packages
If modules are python files, then packages are folders containing those files. This folder often contains an __init__.py
file. __init__.py
is optional but it is recommended to put one inside your package. You can add an empty __init__.py
if you have nothing to put in there.
Let us reorganise our module from the previous section to create a package. Here is how your folder structure should look like.
greetings/
__init__.py
greeter.py
hello.py
Create a new greetings
folder and move our greeter.py
file into it. Optionally, create an empty __init__.py
file inside it. Your hello.py
should be outside the greetings
folder.
Now, let us rewrite hello.py
to use our package.
from greetings.greeter import HELLO_WORLD, Greeter, say_greetings
# Uses the variable
print(HELLO_WORLD)
# Uses the class
greet = Greeter()
greet.say_hello()
# Uses the function
say_greetings()
You can also use the import greetings.greeter
syntax. You have to prefix the variables with greetings.greeter.
.
import greetings.greeter
# Uses the variable
print(greetings.greeter.HELLO_WORLD)
# Uses the class
greet = greetings.greeter.Greeter()
greet.say_hello()
# Uses the function
greetings.greeter.say_greetings()
That is it. You are initiated! Go ahead and build something fun.