This page contains documentation adapted from the online book A Byte of Python by Swaroop C H, licensed under Creative Commons Attribution-ShareAlike 4.0 International License . The original text is available at https://python.swaroopch.com .

Introduction to Python

Python is an easy to learn programming language that has efficient high-level data structures but an extremely simple syntax. Python is an example of a Free/Libre and Open Source Software (FLOSS), which means that you can freely distribute copies of this software, read its source code, make changes to it, and use pieces of it in new free programs. Due to its open-source nature, Python has been ported to (i.e. changed to make it work on) many platforms. All your Python programs can work on any platforms without requiring much of any changes at all.

A program written in a compiled language like C or C++ is converted from the source language i.e. C or C++ into a language that is spoken by your computer (binary code i.e. 0s and 1s) using a compiler with various flags and options. When you run the program, the linker/loader software copies the program from hard disk to memory and starts running it. Python, on the other hand, does not need compilation to binary. You just run the program directly from the source code. Internally, Python converts the source code into an intermediate form called bytecodes and then translates this into the native language of your computer and then runs it. All this, actually, makes using Python much easier since you don't have to worry about compiling the program, making sure that the proper libraries are linked and loaded, etc. This also makes your Python programs much more portable, since you can just copy your Python program onto another computer and it just works!

Python supports procedure-oriented programming as well as object-oriented programming (OOP). In procdedure-oriented languages, the program is built around procedures or functions which are nothing but reusable pieces of programs. In object-oriented languages, the program is built around objects with combine data and functionality. Python has a very powerful but simplistic way of doing OOP, especially when compared to big languages like C++ or Java.

The Python Standard Library is huge indeed. It can help you do various things involving regular expressions, documentation, generation, unit testing, threading, databases, web browsers, CGI, FTP, email, XML, XML-RPC, HTML, WAV files, cryptography, GUI (graphical user interfaces), and other system-dependent stuff.

All in all Python is a very powerful programming language that has the right combination of performance and features that make writing programs in Python both fun and easy. (Note: Python version 3 is discussed in this page.)

Hello World

Open your python interpreter prompt and type the following: print('Hello World'), then hit enter to see the words Hello World printed on the screen. It should look like the example: print('Hello World')

Output:

$ python hello.py hello world

Basics of Python

Comments

Comments are written with the following format in which # is placed before the comment as seen below.

# Note that print is a function print('hello world')

or:

print('Hello World') # Note that print is a function

Comments are used to explain assumptions, important decisions, important details, problems you're trying to solve, problems you're trying to overcome in your program, notes for the reader of the program so that they can easily understand the functions and features of the program, etc.

Literal Constants

An example of a literal constant is a number like 5 , 1.23 , or a string like 'This is a string' or "It's a string!" .

It is called a literal because it is literal - you use its value literally. The number 2 always represents itself and nothing else - it is a constant because its value cannot be changed. Hence, all these are referred to as literal constants.

There are mainly two types of numbers, either integers (which are whole numbers like the integer 2 ) or floating point numbers/floats (which are numbers with decimal place values or with an E notation) like 3.23 and 52.3E-4 . The E notation indicates powers of 10. In this case, 52.3E-4 means 52.3 * 10^-4 .

Strings

Strings are a sequence of characters. There are three ways to specify strings, by using single quotes, double quotes, or triple quotes.

Strings are immutable, meaning that once made, they cannot be changed.

Variables

Using just literal constants can soon become boring - we need some way of storing any information and manipulate them as well. This is where variables come into the picture. Variables are exactly what the name implies - their value can vary, i.e., you can store anything using a variable. Variables are just parts of your computer's memory where you store some information. Unlike literal constants, you need some method of accessing these variables and hence you give them names.

Identifier Naming

Variables are examples of identifiers. Identifiers are names given to identify something. There are some rules you have to follow for naming identifiers:

Variables can hold values of different types called data types & the basic types are numbers & strings. You can create your own types using classes. Variables are used by just assigning them a value. No declaration or data type definition is needed or used.

Example:

i = 5 print(i) i = i + 1 print(i) s = '''This is a multi-line string. This is the second line.''' print(s)

Output:

5 6 This is a multi-line string. This is the second line.

Here's how this program works. First, we assign the literal constant value 5 to the variable i using the assignment operator ( = ). This line is called a statement because it states that something should be done and in this case, we connect the variable name i to the value 5 . Next, we print the value of i using the print statement which, unsurprisingly, just prints the value of the variable to the screen. Then we add 1 to the value stored in i and store it back. We then print it and expectedly, we get the value 6 . Similarly, we assign the literal string to the variable s and then print it.

Control Flow

In the examples above, all the series of statements have been executed by Python in exact top-down order. Control flow is used when you want to change the flow of how statements work. For example, you want the program to take some decisions and do different things depending on different situations, such as printing 'Good Morning' or 'Good Evening' depending on the time of the day.

This is achieved using control flow statments. There are three control flow statements in Python - if , for and while .

Functions

Functions are reusable pieces of programs. They allow you to give a name to a block of statements, allowing you to run that block using the specified name anywhere in your program and any number of times. This is known as calling the function. Functions are defined using the def keyword. After this keyword comes an identifier name for the function, followed by a pair of parentheses which may enclose some names of variables, and by the final colon that ends the line. Next follows the block of statements that are part of this function.

Example:

def say_hello(): # block belonging to the function print('hello world') # End of function say_hello() # call the function say_hello() # call the function again

Output:

$ python function_global.py x is 50 Changed global x to 2 Value of x is 2

We define a function called say_hello using the syntax as explained above. This function takes no parameters and hence there are no variables declared in the parentheses. Parameters to functions are just input to the function so that we can pass in different values to it and get back corresponding results. Notice that we can call the same function twice which means we do not have to write the same code again.

Data Structures

Data structures are basically just that - they are structures which can hold some data together. In other words, they are used to store a collection of related data. There are four built-in data structures in Python - list , tuple , dictionary and set .

List

A list is a data structure that holds an ordered collection of items i.e. you can store a sequence of items in a list. This is easy to imagine if you can think of a shopping list where you have a list of items to buy, except that you probably have each item on a separate line in your shopping list whereas in Python you put commas in between them. The list of items should be enclosed in square brackets so that Python understands that you are specifying a list. Once you have created a list, you can add, remove or search for items in the list. Since we can add and remove items, we say that a list is a mutable data type i.e. this type can be altered.

A list is an example of usage of objects and classes. When we use a variable i and assign a value to it, say integer 5 to it, you can think of it as creating an object (i.e. instance) i of class (i.e. type) int .

A class can also have methods i.e. functions defined for use with respect to that class only. You can use these pieces of functionality only when you have an object of that class. For example, Python provides an append method for the list class which allows you to add an item to the end of the list. For example, mylist.append('an item') will add that string to the list mylist . Note the use of dotted notation for accessing methods of the objects. A class can also have fields which are nothing but variables defined for use with respect to that class only. You can use these variables/names only when you have an object of that class. Fields are also accessed by the dotted notation, for example, mylist.field .

Example:

# This is my shopping list shoplist = ['apple', 'mango', 'carrot', 'banana'] print('I have', len(shoplist), 'items to purchase.') print('These items are:', end=' ') for item in shoplist: print(item, end=' ') print('\nI also have to buy rice.') shoplist.append('rice') print('My shopping list is now', shoplist) print('I will sort my list now') shoplist.sort() print('Sorted shopping list is', shoplist) print('The first item I will buy is', shoplist[0]) olditem = shoplist[0] del shoplist[0] print('I bought the', olditem) print('My shopping list is now', shoplist)

Output:

$ python ds_using_list.py I have 4 items to purchase. These items are: apple mango carrot banana I also have to buy rice. My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice'] I will sort my list now Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice'] The first item I will buy is apple I bought the apple My shopping list is now ['banana', 'carrot', 'mango', 'rice']

The variable shoplist is a shopping list for someone who is going to the market. In shoplist , we only store strings of the names of the items to buy but you can add any kind of object to a list including numbers and even other lists. We have also used the for..in loop to iterate through the items of the list. (Note: Lists are also sequences.) Notice the use of the end parameter in the call to print function to indicate that we want to end the output with a space instead of the usual line break.

Next, we add an item to the list using the append method of the list object. Then, we check that the item has been indeed added to the list by printing the contents of the list by simply passing the list to the print function which prints it neatly. Then, we sort the list by using the sort method of the list. It is important to understand that this method affects the list itself and does not return a modified list - this is different from the way strings work. This is what we mean by saying that lists are mutable and that strings are immutable.

Next, when we finish buying an item in the market, we want to remove it from the list. We achieve this by using the del statement. Here, we mention which item of the list we want to remove and the del statement removes it from the list for us. We specify that we want to remove the first item from the list and hence we use del shoplist[0] (remember that Python starts counting from 0).

Tuple

Tuples are used to hold together multiple objects. Think of them as similar to lists, but without the extensive functionality that the list class gives you. One major feature of tuples is that they are immutable like strings i.e. you cannot modify tuples. Tuples are defined by specifying items separated by commas within an optional pair of parentheses. Tuples are usually used in cases where a statement or a user-defined function can safely assume that the collection of values (i.e. the tuple of values used) will not change.

Example:

# I would recommend always using parentheses # to indicate start and end of tuple # even though parentheses are optional. # Explicit is better than implicit. zoo = ('python', 'elephant', 'penguin') print('Number of animals in the zoo is', len(zoo)) new_zoo = 'monkey', 'camel', zoo # parentheses not required but are a good idea print('Number of cages in the new zoo is', len(new_zoo)) print('All animals in new zoo are', new_zoo) print('Animals brought from old zoo are', new_zoo[2]) print('Last animal brought from old zoo is', new_zoo[2][2]) print('Number of animals in the new zoo is', len(new_zoo)-1+len(new_zoo[2]))

Output:

$ python ds_using_tuple.py Number of animals in the zoo is 3 Number of cages in the new zoo is 3 All animals in new zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin')) Animals brought from old zoo are ('python', 'elephant', 'penguin') Last animal brought from old zoo is penguin Number of animals in the new zoo is 5

The variable zoo refers to a tuple of items. We see that the len function can be used to get the length of the tuple. This also indicates that a tuple is a sequence as well. We are now shifting these animals to a new zoo since the old zoo is being closed. Therefore, the new_zoo tuple contains some animals which are already there along with the animals brought over from the old zoo. Back to reality, note that a tuple within a tuple does not lose its identity. We can access the items in the tuple by specifying the item's position within a pair of square brackets just like we did for lists. This is called the indexing operator. We access the third item in new_zoo by specifying new_zoo[2] and we access the third item within the third item in the new_zoo tuple by specifying new_zoo[2][2] .

Dictionary

A dictionary is like an address-book where you can find the address or contact details of a person by knowing only his/her name i.e. we associate keys (name) with values (details). Note that the key must be unique just like you cannot find out the correct information if you have two persons with the exact same name. Note that you can use only immutable objects (like strings) for the keys of a dictionary but you can use either immutable or mutable objects for the values of the dictionary. This basically translates to say that you should use only simple objects for keys. Pairs of keys and values are specified in a dictionary by using the notation d = {key1 : value1, key2 : value2 } . Notice that the key-value pairs are separated by a colon and the pairs are separated themselves by commas and all this is enclosed in a pair of curly braces. Remember that key-value pairs in a dictionary are not ordered in any manner. If you want a particular order, then you will have to sort them yourself before using it. The dictionaries that you will be using are instances/objects of the dict class

Example:

# 'ab' is short for 'a'ddress'b'ook ab = { 'Swaroop': 'swaroop@swaroopch.com', 'Larry': 'larry@wall.org', 'Matsumoto': 'matz@ruby-lang.org', 'Spammer': 'spammer@hotmail.com' } print("Swaroop's address is", ab['Swaroop']) # Deleting a key-value pair del ab['Spammer'] print('\nThere are {} contacts in the address-book\n'.format(len(ab))) for name, address in ab.items(): print('Contact {} at {}'.format(name, address)) # Adding a key-value pair ab['Guido'] = 'guido@python.org' if 'Guido' in ab: print("\nGuido's address is", ab['Guido'])

Output:

$ python ds_using_dict.py Swaroop's address is swaroop@swaroopch.com There are 3 contacts in the address-book Contact Swaroop at swaroop@swaroopch.com Contact Matsumoto at matz@ruby-lang.org Contact Larry at larry@wall.org Guido's address is guido@python.org

We create the dictionary ab using the notation already discussed. We then access key-value pairs by specifying the key using the indexing operator as discussed in the context of lists and tuples. Observe the simple syntax. We can delete key-value pairs using our old friend - the del statement. We simply specify the dictionary and the indexing operator for the key to be removed and pass it to the del statement. There is no need to know the value corresponding to the key for this operation. Next, we access each key-value pair of the dictionary using the items method of the dictionary which returns a list of tuples where each tuple contains a pair of items - the key followed by the value. We retrieve this pair and assign it to the variables name and address correspondingly for each pair using the for..in loop and then print these values in the for-block.

Set

Sets are unordered collections of simple objects. These are used when the existence of an object in a collection is more important than the order or how many times it occurs. Using sets, you can test for membership, whether it is a subset of another set, find the intersection between two sets, and so on.

Example:

>>> bri = set(['brazil', 'russia', 'india']) >>> 'india' in bri True >>> 'usa' in bri False >>> bric = bri.copy() >>> bric.add('china') >>> bric.issuperset(bri) True >>> bri.remove('russia') >>> bri & bric # OR bri.intersection(bric) {'brazil', 'india'}

If you remember basic set theory mathematics from school, then this example is fairly self-explanatory. But if not, you can google "set theory" and "Venn diagram" to better understand our use of sets in Python.

Next Steps

In this page, only a portion of Python has been shown. However, now that you have learnt the basics of Python, you can continue to dive deeper as well as attempt to create Python projects of your own.

Here are some resources to continue your journey into learning Python:

Here are some resources that provide Python project ideas & example code:

References

All the documentation from this page is taken from the online book A Byte of Python .