A crash course on Python

Installing Python

Click here for the guide on downloading and installing Python

Starting Python

Open terminal on Linux or Command Prompt on Windows
You can start Python by entering

python

Python lets you write code directly on the command prompt (or terminal), or you can save your Python programme in a text file with extention .py (example: hello.py). In order to run a Python program in file hello.py, enter in command prompt (terminal)

python hello.py
Example programs
Hello World

The print statement simply prints out a line.

print("Hello World!!!")

Indentation

In python, instead of curly braces, indentation is used to differentiate a block of statements.

x = 1
if x == 1:
    # indented four spaces
    print("x is 1.")

Variables and data types

In Python, every variable is an object. Hence, we do not need to declare the variables nor the variable type before using it. It supports integers and floating point numbers which can be used in either way as shown below. Strings can be defined using either a single quote or a double quote. However, double quote is useful in including apostrophes within the string.

myint = 6
print(myint)
myfloat = 7.0
print(myfloat)
myfloat = float(8)
print(myfloat)
mystring = 'hello'
print(mystring)
mystring = "hello"
print(mystring)

Adding two numbers

The following code shows the addition of two numbers. The procedure can be carried out on multiple numbers also.

one = 1
two = 2
three = one + two
print(three)

Concatenating two strings

In python, strings can be concatenated using the addition operator as shown below.

hello = "hello"
world = "world"
helloworld = hello + " " + world
print(helloworld)

TRY: What will happen if we concatenate an int and a string?
We cannot use operators between integers and strings. The following code results in an error as it is not supported by python.

one = 1
two = float(2)
hello = "hello"
print(one + two + hello)

Lists (arrays)

Lists are similar to arrays except that lists can contain elements of different types. We can create a list and then later add elements to the list by a method called ‘append’ as shown in the below code. Printing the individual elements of the list requires the index of the list along with the name of the list.

mylist = []
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist[0]) # prints 1
print(mylist[1]) # prints 2
print(mylist[2]) # prints 3
 
# prints out 1,2,3
for x in mylist:
    print(x)

Another way of creating lists

Lists can also be created in python as shown below. But accessing an index which does not exists causes an error.

mylist = [1,2,3]
print(mylist[10])

Join two lists

We can also join two or more lists using the addition operator.

even_numbers = [2,4,6,8]
odd_numbers = [1,3,5,7]
all_numbers = odd_numbers + even_numbers

Arithmetic Operations

All the basic operators can be used with numbers in Python. The modulo (%) operator returns the remainder from the resulting division. A number followed by two multiplication (**) symbols denote the power relationship between the numbers as shown below.

number = 1 + 2 * 3 / 4.0
print(number)
remainder = 11 % 3
print(remainder)
squared = 7 ** 2
cubed = 2 ** 3

Formatting String

Python uses the operator ‘%’ to format a set of variables. The special symbols like ‘%s’ and ‘%d’ are replaced by the argument specifiers when the code runs. Parentheses is used when we want to include two or more argument specifiers. The following code provides a better insight on string formatting.

name = "Dave"
print("Hello, %s!" % name)
age = 23
print("%s is %d years old." % (name, age))

Conditions

Python returns Boolean values True and False when a conditional statement is evaluated. The conditional operators used in Python are ‘==’ (equals to ), ‘<‘ (less than), ‘>’ (greater than), ‘<=’ (less than or equals to), ‘>=’ (greater than or equals to) and ‘!=’ (not equals to).

x = 2
print(x == 2) # prints out True
print(x == 3) # prints out False
print(x < 3) # prints out True

Using Conditions

Further, the conditions can be used to execute a statement based on that given condition as follows.

x = 2
if x == 2:
    print("x equals two!")
else:
    print("x does not equal to two.")

Boolean operators

Boolean operators like ‘and’ and ‘or’ can be used to make decisions based on more than one condition.

name = "John"
age = 23
if name == "John" and age == 23:
    print("Your name is John, and you are also 23 years old.")
 
if name == "John" or name == "Rick":
    print("Your name is either John or Rick.")

not operator

The ‘not’ operator before a Boolean expression negates the value of the expression.

print(not False) # Prints out True
print((not False) == (False)) # Prints out False

for loop

The for loop iterates in sequence for the given range. In the given example, the first for loop prints all the values present in the list. The second for loop with only one argument within the parentheses prints all the numbers from 0 till the value of the argument. The third for loop specifies the range between two numbers which prints all the numbers between the given range including the first argument and excluding the second argument. In the next for loop, the third argument denotes the value to be incremented in every iteration within the given range.

primes = [2, 3, 5, 7]
for prime in primes:
    print(prime)

# Prints out the numbers 0,1,2,3,4
for x in range(5):
    print(x)
 
# Prints out 3,5,7
for x in range(3, 8, 2):
    print(x)
while loop

The while repeatedly iterates until the condition is met.

# Prints out 0,1,2,3,4 
count = 0
while count < 5:
    print(count)
    count += 1  # This is the same as count = count + 1

Functions

Functions are the block of statements with specific tasks. In python, there can be many ways in which a function can be used according to our requirements. A function can have no arguments. Also, it can have arguments which can be used in carrying out the specific task performed by the function. The arguments can be both numbers or strings as shown in the code below. While calling the function we simply use the function name and give the required arguments within parentheses.

# Define our 3 functions
def my_function():
    print("Hello From My Function!")

def my_function_with_args(username, greeting):
    print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))

def sum_two_numbers(a, b):
    return a + b

# print(a simple greeting)
my_function()

#prints - "Hello, John Doe, From My Function!, I wish you a great year!"
my_function_with_args("John Doe", "a great year!")

# after this line x will hold the value 3!
x = sum_two_numbers(1,2)

[A crash course on Python II – Read and analyse a csv file using Python classes]