An Absolute Beginner’s Guide to Python

When I need to build a web app, I reach for the Python programming language. When I need to automate some small task on my system, I reach for Python. When I want to find the most common colors in an image, I reach for Python. When I… OK, I think you get the picture. Basically, when I need to code something and the language doesn’t matter, I use Python.

What’s Python?

Python is a general purpose programming language created in the late 1980s, and named after Monty Python, that’s used by thousands of people to do things from testing microchips at Intel, to powering Instagram, to building video games with the PyGame library. It’s small, very closely resembles the English language, and has hundreds of existing third-party libraries.

Using Python?

To use Python you’ll need two things: Python and a text editor to write code. To install Python use this best and short tutorial from thenewboston. (Check out his Python tutorials they are cool). I will recommend to use Sublime Text as your text editor and not (Notepad or Notepad++). Install Sublime Text from here .

Python Basics

Variables

To create a variable in Python we don’t have to use any keyword.

greeting = 'Hello World!'

This code tells the computer to create a new variable named ‘greeting’ which will store the text ‘Hello World!’.

Once you’ve created a variable you can easily modify it by setting it equal to something else:

greeting = 'Hello World!'
greeting = 'Hello Python!'

If you have a previous programming experience, you have seen there are two type of variables: mutable and immutable. Mutable means that the variable CAN be changed , and immutable means that it CANNOT be changed.In Python variables are always mutable in fact everything in Python is Object .

Strings

In our example above we’ve been making use of the String type. Let’s see how we can combine two Strings together by using the + operator.

language = 'Python'
creator = 'Monty Python'
description = language + " is created by " + creator
#description = "Python is created by Monty Python"

Combining Strings together like this is known as concatenation.

If you are wondering how Python handles data types so note that Python is dynamically typed language it also implies that Python is “loosely-typed” and predicts the type of the data during run time.

Numbers

Along with String Python offers several numeric types. The most important of these are Int , Float , Boolean. Int is used for whole numbers , whereas Float is used for decimal values.

num1 = 11 #Int
num2 = 12.34 #Float

Until your data is integer all the basic arithmetic expressions return an int but divide(/) operation returns Float.

add = 2 + 4 #6
sub = 2 - 4 #-2
mul = 2 * 4 #8
div = 4/2 #2.0

Untill Python 2 the divide operation on integer returned an Int , but they changed it in Python 3. You have to use (//) operator to get back Int part from the result.

div = 4//2 #2
div = 4//3 #1

Booleans

Python also contains a Boolean type. Boolean types are used to represent either a true or false value. To set a Boolean variable use the True or False keywords:

isGoodDay = True
isBadDay = False

Numerically True means 1 and False means 0.

Nullabilty

In most languages, when you create a variable but don’t set it equal to something, it gets a value of NULL, which can be thought of as not being equal to anything. NULL values cause issues in many programs when the program tries to do something with a NULL value. For example:

//java code
String address;
println(address);

The above code creates a String variable named ‘address’ and then tries to print out the address before it has been set. This results in a NullPointerException and crashes the program.

Python does not have anything called NULL but it has None.

In Python we handle None a bit differently. Instead of variables being defaulted to None, it’s actually an error to not initialize a variable:

my_name = None
print(my_name) # None
my_name
print(my_name) #my_name is not defined ==> NameError

In Python we have two types of handy errors.One is called Name Error and other is called Type Error.

Name Error is caused when we not define the name and use it in our program.

Type Error is caused when we perform such a operation which can only be performed on same data types. For e.g.

my_name = 'Name'
my_age = 20
print(my_name + my_age) #Type Error is generated.

We cannot add String and Int and it seems genuine , we never add text and numbers in real world.

Collections

A collection contains multiple items that can be accessed through subscripting. Python offers three main types of collections: Lists, Dictionaries and Set.

Lists

An list is an indexed collection of items that can have the same or different type as required. Let’s learn how to create list

# Creating a list , we use [] inside square brackets we write our data seperated by commas 
my_list = [12,13,1,11,111]
print(my_list) # [12, 13, 1, 11, 111]
my_hybrid_list = ['Python' , 12 , 'Pythonists']
print(my_hybrid_list) # ['Python' , 12 , 'Pythonists']

To access an item from the list we use the index (starting at 0) of the item we’d like to access. So to access the first item in the array we would use:

first = my_list[0] #12

To replace an existing item in the list, just subscript that item and set it equal to a different value:

my_hybrid_list[0] = 'Java'
print(my_hybrid_list) # ['Java' , 12 , 'Pythonists']

Lists are flexible in size;we can add or remove items from an List.

my_list = [12,13,1,11,111]
my_list = my_list + [121 , 120]
print(my_list) # [12, 13, 1, 11, 111, 121 , 120]

Also we can replicate items in list using ‘*’ operator

my_language = ['Python']
my_language = ['Python'] * 3
print(my_language) #['Python', 'Python', 'Python']

Removing items from the list using ‘del’ operator

del my_language[0]
print(my_language) # ['Python', 'Python']

Some more features of list:

#Some functions that are offered with list
#Creating a list
my_list = [1,2,2,3,3,3,3,4,4,4,6,7,8,9,10,10]
#Length of the list
print(len(my_list)) #16
#Max Element of the List
print(max(my_list)) #10
#Min Element of the List
print(min(my_list)) #1
#Count returns number of occurences of a element in the list
print(my_list.count(3)) #4
#index function returns the index of the element being searched
print(my_list.index(10)) #14

Dictionary

Dictionary in Python is same as Maps in Java. Dictionary let us store key-value pairs and access the values by providing the keys.

For example, if we wanted to store numeric information along with our card data we could create a map like this:

my_dict = {'Jack' : 11 , 'Queen' : 12 , 'King' : 13}

Above we have specified the card names as the keys and have mapped them to their corresponding values. Here we’re using String keys and Int values, but we’re not restricted to just Strings and Ints; you can use any types in a Map

To access a specific card, just use the key to retrieve the value:

result = my_dict.get('Jack')
print(result) #11

Set

Set in Python is same as Set in Java.

Set does not have any duplicate items in it lets learn set:

my_set = {'Python' , 'Java' , 'Kotlin' , 'Kotlin'}
print(my_set) # {1, 'Java', 'Python', 'Kotlin'}

Set is also heterogeneous data structure as List.

my_set = {'Python' , 'Java' , 'Kotlin' , 'Kotlin' , 1, 2, 3, 4, 5}
print(my_set) # {1, 2, 'Java', 3, 4, 5, 'Python', 'Kotlin'}

Set is unordered collection of data that’s why in the above example the order was changed.

Adding elements in Set.

#Adding elements in Set
types_of_cheese = {'Gouda', 'Brie', 'Cheddar', 'Manchego'}
types_of_cheese.add('Mozzarela')
print(types_of_cheese)
# {'Gouda', 'Brie', 'Cheddar', 'Manchego', 'Mozzarela'}

Control Flow

Looping

In Python there are two types of loops: for loops and while loops. You can use a for loop to iterate through a collection like this:

my_cards = ['Jack' , 'Queen' , 'King']
for cards in my_cards:
print(cards)

The print function will print out the value of whatever is between the parentheses. So this code prints each card on a new line:

Jack
Queen
King

A for loop can also be used to loop over a range of numbers. To print the numbers 1 through 10 you could use the following for loop.

for i in range(1,11):
print(i)
1
2
3
4
5
6
7
8
9
10

You can also use a for loop to loop through a Map. This code loops through the cards Map and prints out the name and value of each card:

my_dict = {'Jack' : 11 , 'Queen' : 12 , 'King' : 13}
for k,v in my_dict.items():
print("{}-->{}".format(k,v))
Jack-->11
Queen-->12
King-->13

In addition to for loops, Python also offers a while loop. While loops are used to loop until a certain condition is met:

We can us ‘is not’ instead of ‘!=’ in Python:

i = 1
while i is not 5:
print('You will get there')
i += 1
You will get there
You will get there
You will get there
You will get there

If Statement

Most languages have an if statement, and Python too .So in addition to using if statements the normal way:

#Using if-else in Python
a = 5
b = 3;
a_is_bigger = False
if a > b:
a_is_bigger = True
else:
a_is_bigger = False

Using if-else statements always take care of the proper indentation as I have did in above example.

Also we have elif statement short for( else-if).

#Using if-elif-else:
my_number = 20;
if my_number < 0:
print('Number is negative')
elif my_number == 0:
print('Number is zero')
elif my_number == 1:
print('Number is single')
else:
print('Number is more')

is vs ==

‘==’ (equals-to) is in many programming languages.

We have two operators to check the equality in Python. ‘==’ and ‘is’ but they are not exactly similar

== checks whether the value is same or not:

#Using == in Python
i_speak = 'Python'
u_speak = 'Java'
if i_speak == u_speak:
print('We are friends')
else:
print('We cannot be friends')

While , is operator checks the instances are same or not:

#is vs == in Python
my_list = [1,2,3]
my_new_list = [1,2,3]
if my_list is my_new_list:
print('Same')
else:
print('Not same')
Not same

Functions

Functions are blocks of code that you can use to simplify your programs. For example, print is a function that takes in a variable and prints its value to the screen.

In Python we can create our own functions by using the ‘def’ keyword and then providing a name for the function:

#Function in Python
def hello_world():
print('Hello world')

We can also add parameters to our function:

#Another Function in Python
def print_cards(key , value):
print('{} = {}'.format(key,value))

If we’d like, instead of printing out the card, we could return it as a String object:

def print_cards(key , value):
return('{} = {}'.format(key,value))

We can call the function in Python as:

hello_world()
print_cards(11 , 'Jack')

Conclusion

If you’ve made it this far, then congratulations! You’ve now got a good base to start building some serious Python knowledge. It’s a lot to take in, but we’ve really only scratched the surface of Python. Stay tuned for more!.If you like this article then give a thumbs-up also feel free to use the comment section as you want :).