🐍Python Master Class — Day 1 of ’n’ Days

Introduction, Numbers, and Variables

Rajesh Pillai
Full Stack Engineering
8 min readNov 14, 2019

--

Python is a general-purpose programming language suitable for building web applications, data science, desktop applications, mobile applications, IoT, etc.

Photo by Chris Ried on Unsplash

Table of Contents

  1. Day 1 — Introduction and Numbers (This article)
  2. Day 2 — Strings (work in progress)

This is a new series on programming with Python. The series goes into detail of using python as a fundamental programming language for data science, machine learning, web development, etc.

This first set of series deals with the absolute fundamentals of Python programming language to set the stage of building Python-based applications.

We will be taking every aspect of Python programming 1 day at a time.

Prerequisites

  • A well-oiled installation of Python (recommended 3 and above) or an online environment with access to Python runtime
  • Passion and perseverance to put in a lot of hard and smart work

You can install python from

Or use Jupyter notebook

First Python Program

Your first Python Program (You an also fire up the python terminal/console window and type in the commands.

print (365)

And unsurprisingly the output will be

365

The above code as shown in the python interpreter on windows (Linux and Mac will have similar terminals/consoles)

So, print is an instruction/command to the python runtime to print the contents to the standard output device (mostly your monitor).

Comments

Commenting or documenting your code is very critical for future maintenance work. Comments are not executed by the python runtime/interpreter. Comments are for humans/programmers

Comments in python start with a hash # character

E.g.

# This is a comment
# Some more comment
# The below code will not be executed as it is commented.
# print ("hello")

NOTE: Get into the habit of commenting your code. But please make sure that your code and comment are in sync.

Python Operators

[+] Addition
[ — ] Subtraction
[ *] Multiplication
[ / ] Division
[%] Percent
[<] less-than
[>] greater-than
[ <=] less-than-equal
[>=] greater-than-equal

So, now guess the output of the below print statements.

print (100-10)
print(10 * 5)
print (49 / 7)

To perform exponential calculation, i.e. say if you want to raise a number to a power, e.g. 2 to the power of 2, we type in

print (2 ** 2)  # output => 4

Try out the above exercises and observe the output.

Greater than and Less than Operators

Greater than, Less than, Greater than equal and less than equal operators are used for comparison. It returns a boolean, true or false depending on the result of the condition.

print (5 > 7) # outputs False# NOTE: == (double equals) means equality checking
print (2 == 2) # outputs True
print (2 < -5) # outputs Falseage = 10
print (age <= 11) # outputs True

Order of Operations

Parentheses are meaningful in Python, just like any other language. When it comes to computation, Python always computes what is in parentheses first.

The Python language follows the same order of operations as in the math world. You may recollect the acronym PEMDAS: parentheses first, exponentiation second, multiplication/division third, and addition/subtraction fourth.

Consider the following expression: 6+ 2 * -4

Python executes the above expression as shown below

  • Python first multiples 2 and -4 and then adds 6
6 -8  => output should be -2

You can change the order of execution by putting parentheses around the expressions

(6 + 2) * -4

Here the output will be

-32

One more example

((10 + 30) * 20) / 10  # Output 80.0

Number Types

Numbers come in various flavors according to the value they represent.

There are primarily three representation for number types — int, float, complex. Also, Booleans are a subtype of integers.

Integers can be as long as required, positive or negative without decimals. Floating-point contains decimal places. And complex type is <real part> + <imaginary part>j.

NOTE: The type() function returns class type of the argument (object) passed as parameter.

type(10) # outputs <class 'int'>
type(10.2) # outputs <class 'float'>
type(2+3j) # outputs <class 'complex'>

Convert from one type to another

You can convert from one type fo another using the int, float functions.

For example

5 + 1.2 # Gives you 6.2

The output of adding int and float gives us float type back. However, if we only need the integer part from the above you can use the below function

int (5 + 1.2)  # Gives you 6

Now, why would you do that? Well, you shouldn’t unless the program you are writing needs that specific feature.

int (value, base)

NOTE: int(value, base) function returns the integer part of the number. By default, the base is the decimal system, but it can be binary, hexadecimal also. More on that later.

Parameter Values

value — A number or a string that can be converted into an integer number
base — A number representing the number format. Default value: 10

The int() function can also be used to convert text input into numbers. E.g.

int ("11") # outputs 11 (the numeric 11)

NOTE: We will cover more about strings/text in later part of the course.

float(value)

Converts a number into a floating-point number.

Parameter Values

value — A number or a string that can be converted into a floating-point number

E.g.

float("3.14")  # outputs 3.14float(5)  # outputs 5.0

Variables

Variable in programming describes a place to store information such as numbers, text, lists of numbers and text, and soon.

Another way of looking at a variable is that it’s like a label for
something.

In Python, the variables are created the first time you use them and their type does not need to be predeclared. Python is a dynamic language, meaning, the types can be changed at runtime.

For example, let’s create a variable to store age information as shown below

age = 30

To print this information to the screen execute the below command

print (name)  # The output will be 30

You can visualize the variable in the memory (RAM) as below

Variables are accessed by their name that you assign while you create it.

Variables can be changed as well. Let’s change the age to say 40.

age = 40print (age)  # prints 40 on the output window

Let’s get a bit more advanced. Let’s create a variable to store the age of three people and sum their total age.

You can write the below program in a file called ‘age.py’ or you could run it in the python shell as well.

age1 = 30
age2 = 20
age3 = 15
total_age = age1 + age2 + age3print (total_age) # outputs 65

Now, numbers are good, but random numbers are better as they are unpredictable and add dynamics to programs, specifically when you are developing some games or visualization applications.

More Variables and Exercises

Refer variables.py in the source code folder (refer end of the article)

# Exercices to practice basic skillsspace_in_a_bike = 2.0  # one bike, two people
no_of_people = 30 # total no of people
# calculate no. of bikes needed
bikes_needed = no_of_people / space_in_a_bike
print("There are", bikes_needed,"bikes needed for",no_of_people, "people")
# change the no of bikes to 100
no_of_bikes = 100
# how many people can it take?
no_of_people = no_of_bikes * 2
print (no_of_bikes, "bike can take", no_of_people, "people")
# count the number of tires
total_tires = no_of_bikes * 2
print(no_of_bikes, "bikes have", total_tires, "tires.")
# change no of people to 10
no_of_people = 10
# amount of cash each person carries
amount_of_cash = 50
# what is the average amount?
avg_amount = (amount_of_cash * no_of_people) / no_of_people
print ("Average amount carried by ",no_of_people, " people is", avg_amount)

And verify your output and understanding

Random Number

To generate a random number first you have to import the random module it as shown below.

import random

Once we import it we can use it to generate random numbers.

NOTE: A module/package is a collection of utility functions

Assume you are coding a game where you need to assign powers to your actor based on a range of 1 to 20 (randomly)

import randomstrength = random.randomint(1,20)print (strength)

The output well, of course, be a random integer between 1 and 20.

The syntax of randint() is

random.randint(a, b)

Return a random integer N such that a <= N <= b.

Fun exercise

Let’s create a file called randomizer.py and put the following code in it.

import randomstrength = random.randint(1,5)x_position = random.randint(0,600);y_position = random.randint(0,800);print ("The actor with %d strength is located on the grid at {%d,%d}" % (strength, x_position, y_position))

Execute the code from the terminal/ command prompt by typing

▶️ python randomizer.py

The output is shown below.

TIP: We can pass multiple parameters to the print function.

Exercises

Try out the following exercises in your code editor of choice and observe and understand the output.

print("Actors", 25 + 30 / 6)print("Weapons", 100 - 25 * 3 % 4)# Some calculations
print(4 + 1 - 5 + 4 % 2 - 1 / 4 + 8)
# What do you think?print("Is it true that 3 + 1 < 5 - 7?")print(3 + 2 < 5 - 7)print("What is 3 + 2?", 3 + 2)print("What is 5 - 8?", 5 - 8)#Get comfortable with > and less than opeatorsprint("Guess, Is it greater?", 5 > -3)print("Is it greater or equal?", 5 >= -2)print("Is it less or equal?", 5 <= -2)

NOTE: I am publishing these day based chapters for early access. So, all content will be updated.

Source code is hosted here

Shoutout: A huge thanks to Team Algorisys for the support.

History

  • 13-Nov-2019 Created the first draft

--

--

Rajesh Pillai
Full Stack Engineering

Founder and Director of Algorisys Technologies. Passionate about nodejs, deliberate practice, .net, databases, data science and all things javascript.