Learn Python - Step-by-Step
Learn Python - Step-by-Step
Step-By-Step
Introduction
Quickly jumpstart your Python learning. This is example-driven, short, to-
the-point and is designed to get you started with Python.
Value developer productivity over anything else? Want to get more done in
fewer lines of code? Python is our best bet. It’s a high-level object oriented
programming language similar to Perl or Java. We can use Python for a
variety of usages, like:
We now see a notification at the bottom left, requesting for a VS code restart:
Click on Restart to Update (1) to restart VS code & finish adding Python
support to VS code. Once it restarts automatically, close any new tabs to see
the welcome tab. Python is now supported:
Let’s now download Python itself so that we can write our code & execute it
using Python. Only Python interpreter understands Python code. To do so
visit: https://www.python.org/ & download it for your OS:
New Concept: Interpreters are computer programs that
interpret input text & directly execute it without first
converting the input to other formats like binary.
Click on Disable path length limit & finally click on Close. Our development
environment is now setup. Let’s start learning & writing some code.
First impressions & expressions
Run Python by searching for it on the Windows start menu:
This is the interpreter, ready & waiting to execute Python code. Let’s try out
basic math to see how this works & learn more.
Type 5+5 at the >>> (prompt) & hit Enter to see the result:
New Concept: Such inputs like 5+5 are expressions. Expressions are first
evaluated by Python & its results returned to us.
New Concept: we use various characters like ‘+’ to help perform operations.
Such characters are called as operators.
Following are common math operators:
+ for addition
- for subtraction
* for multiplication
/ for division
% for mod i.e. remainder after division
Following are common comparison operators:
> for greater than
>= for greater than or equal to
< for lesser than
<= for lesser than or equal to
== for equals
!= for not equals
We can also use comparison operators ‘>’, ‘<’, ‘>=’, ‘<=’, ‘==’, ‘!=’’ to
compare two numbers:
5==5 checks if both numbers are the same. 10!=5 checks if both are not
equal.
We can combine any operators to help us calculate complex expressions, like
so:
Here, the expression inside the brackets is first evaluated & its result
compared to 500.
We can also combine multiple sub-expressions to form more complex
expression using ‘and’ & ‘or’ keywords:
Here, we have two expressions comparing 5 with 0 & 10. We can combine
both these using ‘and’ so that both these comparisons happen in one go.
This is all well & good but what if we need to perform such operations but on
numbers entered by the user? We need to be able to accept inputs & display
results. We need to leverage built-in functions next.
Introducing built-in functions
Python comes with several built-in functions that we can use to get our job
done. We now need to accept user inputs, operate on these inputs & display
results.
To display something to the user we can use the print() built-in function.
Let’s try it out by printing ‘Hello Python’:
New Concept: Ensure that the text to print or display is within ‘quotes’. Such
quoted text are called strings.
Next, let’s try out the function that we can use to accept data or input from
the user. Let’s ask the user to enter a number by using input():
Note that the supplied string ‘Enter a number:’ was used to prompt the user
with appropriate instructions so that the user knows what needs to be done.
Now let’s build up on this concept to add any 2 given numbers. We need to
write multiple lines of code to get the job done & such activity is better done
using VS code instead of the interpreter console.
Our first true program
Switching back to VS code (open it if closed), click on New file under Start
or via the menu File > New File:
Let’s save this file as a Python file to get all the support that we previously
installed. To do so save the file with a .py extension (choose the Save as type
as Python from the drop down):
We now see a new notification asking us to install the Python linter, let’s do
so by clicking on Install:
The Terminal will show the current install progress. We need to wait until we
see the prompt:
Warnings can be ignored.
Let’s start to code our addition program. Start by typing the print function &
we start to see the true value of VS code as it helps us with intellisense – it
tries to auto complete what we are about to type, thereby helping our
productivity:
Similarly start typing input & we see that it returns a ‘str’ (notice the -> str on
the first line):
We need to store the number that the user enters. To do so we capture the
return value from the input function by using a variable:
firstNo = input('Enter first no.:')
New Concept: Here the left hand side i.e. firstNo is called as a
variable. Variables help us hold some value so that we can use
them later in our program.
Hit F5 key or via the menu Run > Start Debugging to run the program:
Choose Python File as the debug configuration which now popups up:
VS code now switches to debug mode to help you run your program & debug
it. Looking at the Terminal, we see our code being executed:
The output is not as expected. We hoped using the ‘+’ operator would add the
two numbers but Python has instead joined both nos. This is because when
we use the input() function it returns a str i.e. a string. So, the actual type of
both our variables is string. The ‘+’ operator joins if it sees strings.
We need to convert the string to a number format. To do so we can use
another build-in function called int(), like so:
int(firstNo)
Re-writing (or refactoring as it’s normally referred to as) the last line of our
program to:
print(int(firstNo)+int(secondNo))
& re-running our program, we see:
Now let’s try some more numbers to ensure our program is correct with all
possible kinds of inputs, let’s try to add 5.5 & 1.1:
Python has stopped executing our program. We see that an exception has
occurred at line 4. Reading further we see that the value 5.5 in invalid for
int().
To stop debugging, click on the stop icon:
We need our program to add any two numbers not just integers. To do so we
need to use float() instead of int(), refactoring line 4 to:
print(float(firstNo)+float(secondNo))
We now see the expected output:
The program now works for both integers & real nos. but the final output is
not user friendly, let’s add some text to convey that this is the output or
result. We would like to show the result like so:
Although this gets the job done, line 4 is too long & difficult to read. Also,
we need to convey what the program does at a glance. We need to create &
use our own functions to help us split up our program into smaller parts. We
will refactor to a more readable & manageable code next.
Refactoring to functions & introducing lists
Looking back at our example program to add 2 nos. we see following high
level steps or tasks:
When we call this function by passing ‘Addition Program’, Python will set
the value of header_text to ‘Addition Program’. We further pass down the
same to the in-built print() to get the job done. Finishing writing all our
functions, we have the entire program:
def display_app_header(header_text):
print(header_text)
def get_user_inputs():
first_no = input('Enter first no.:')
second_no = input('Enter second no.:')
result = []
result.append(float(first_no))
result.append(float(second_no))
return result
def add(user_input):
return user_input[0] + user_input[1]
display_app_header('Addition program')
user_input = get_user_inputs()
result = add(user_input)
display_result(user_input, result)
Notice get_user_inputs(). We need to get the user inputs properly converted
to numbers & both the nos. returned so that the next function can use the
inputs. To do so, we have used a list. A list is a structure used to store
multiple data items. In this case, we are storing 2 different nos.
We first let Python know that the variable result is a list by using this syntax:
result = []
We can now add data to this list by calling append(), like so:
result.append(float(firstNo))
Finally, we return the list so that other functions can use the same for further
processing:
return result
add() uses this list to add the supplied nos. & returns the result:
return userInput[0] + userInput[1]
It does this by using an index. Index basically lets us point to a particular
item in a list & it starts with 0. So to point to the first number we use:
userInput[0]
The resulting program is a little longer but is more readable. If there are any
issues or bugs (wrong code), we can easily go to that particular function & fix
without reading the entire program to search.
The e.g. problem of adding two numbers has got us thus far. To learn more
we need to switch our problem to a more complex one so that we can
leverage other language features. We will next build a program to display the
multiplication table for a given no.
Building a multiplication table
We will now write a program to display the multiplication table for any given
no. Continuing our practice of writing high level functions to help form our
programs, we can come up with:
n = get_user_input()
display_mul_table(n)
The function names are self-explanatory & readable i.e. any new programmer
can easily understand the overall flow & intent of the code.
get_user_input() needs to return the user entered no.:
def get_user_input():
return int(input('Enter a no: '))
The input() prompts the user to enter a no. & returns the entered no as a string
which we then pass it on to the int() so that it gets converted to an int. The
final converted no. is returned by the function to be used by the next function.
The display_mul_table(n) needs to take in the passed param & display the
multiplication table for the same. To understand how to code this, we need to
see patterns in outputs for a sample multiplication table for e.g. 5:
5x1=5
5 x 2 = 10
5 x 3 = 15
…
…
5 x 10 = 50
We see that the value of ‘n’ is 5 & it’s being multiplied by another value that
ranges from 1 to 10, let’s call this as ‘i’. We can thus generalize the line of
code to display the output as:
print('{} x {} = {}'.format(n, i, n*i))
Now that we have the line of code that would output each line, we need to
execute this line of code repeatedly for each ‘i’ in the range 1 to 10. This
concept of repeatedly executing lines of code is called as looping.
Let’s use the for loop. It’s syntax is:
for individual_item in items:
# code
In our case the individual item is ‘i’. Items is a range() with start = 1 & stop =
10. Thus giving us:
for i in range(1, 10):
print('{} x {} = {}'.format(n, i, n*i))
The entire function looks like:
def display_mul_table(n):
for i in range(1, 10):
print('{} x {} = {}'.format(n, i, n*i))
Notice the indented for & also the indented print. Each indent level indicates
where the code belongs to. for belongs to the function. print belongs to the
for loop.
This is the full program we have:
def get_user_input():
return int(input('Enter a no: '))
def display_mul_table(n):
for i in range(1, 10):
print('{} x {} = {}'.format(n, i, n*i))
n = get_user_input()
display_mul_table(n)
Running the program we see:
We have a small bug, we expected the value of i to range from 1 to 10 but
range excludes the stop value itself. Fixing this to:
for i in range(1, 11):
We now see our intended output:
def display_even_nos(range_value):
for i in range(range_value[0], range_value[1]+1):
if i%2==0:
print(i)
range_value = get_range()
display_even_nos(range_value)
Running it, we see the expected output:
Try to modify this program to display odd nos. We will need to change only
the if condition to:
i%2!=0
The programs we have written thus far work. But we have a big issue. What
if the user doesn’t follow instructions or if the user enters a typo for e.g.
enters a ‘o’ instead of ‘0’, we will see Python stopped executing our code &
throws an exception in this case:
We need to handle such invalid user inputs. We will take a look at the same
next.
Handling exceptions
Note the exception type in the previous section. It’s a ValueError. We will
handle this type of exception so that our program doesn’t crash.
To do so we need to use the try…except. Its syntax is:
try:
# code that’s bound to fail due to user input
except ExceptionType:
# code to run when ExceptionType exception occurs
Refactoring get_range() we have:
def get_range():
try:
start = int(input('Enter starting no: '))
stop = int(input('Enter final no: '))
range_value = []
range_value.append(start)
range_value.append(stop)
return range_value
except ValueError:
print('The entered values are not numbers.')
Running the program now doesn’t break our code in get_range, it does
display our exception message but we now have another exception in
display_even_nos():
def read_file(filePath):
file = open(filePath)
lines = file.readlines()
nos = []
for line in lines:
nos.append(float(line))
return nos
def add(nos):
result = 0
for n in nos:
result += n
return result
def display_result(result):
print('Sum of all nos is {}'.format(result))
filePath = get_input_file()
nos = read_file(filePath)
result = add(nos)
display_result(result)
Running the program, we see:
Here the nos.txt is a notepad text file with the following content, located at
the same location as that of our Python file:
Adding more math & introducing modules
Let’s add more math instead of just working on additions. Let’s write a
program to help our scientific friends with sin, cos, & tan processing.
Fortunately, we don’t need to write the code for each of these. In fact, we
have an existing module i.e. math that features these functions that we can
simply use.
At the high level we need to first ask the user to enter a degree in radians,
next call each of the functions to get results & finally display them. Because
we are using pre-built functions, we don’t need to create our own & can write
this program simply.
The syntax to use an existing module is:
import module_name
We can access the defined functions in that module by the syntax:
module_name.function_name()
Importing the math module & using sin() by passing 90:
import math
print(math.sin(90))