0% found this document useful (0 votes)
132 views40 pages

Learn Python - Step-by-Step

The document provides an introduction to learning Python through examples. It discusses setting up a development environment with Visual Studio Code and downloading Python. It then covers basic Python concepts like variables, operators, built-in functions, and writing a simple addition program. The program initially fails because the input is treated as a string, so it is refactored to use int() and float() functions to convert the input to numbers and allow adding integers and decimals.

Uploaded by

harish400
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
132 views40 pages

Learn Python - Step-by-Step

The document provides an introduction to learning Python through examples. It discusses setting up a development environment with Visual Studio Code and downloading Python. It then covers basic Python concepts like variables, operators, built-in functions, and writing a simple addition program. The program initially fails because the input is treated as a string, so it is refactored to use int() and float() functions to convert the input to numbers and allow adding integers and decimals.

Uploaded by

harish400
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 40

Learn Python

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:

Web / GUI apps


Scientific & numeric apps
Automation
This book is best suited for beginners with programming basics. All required
concepts will be introduced as & when needed so that we can quickly learn &
try stuff out.
Let’s get started by setting up our development environment so that we have
the best tools to help us out.
Setting up our development environment
We will need a tool to help write & edit our code. The best in the market is
Visual Studio. We can use Visual Studio Code (VS code) as it’s best suited
for our workload & is free.
To download & install VS code, visit https://code.visualstudio.com/ &
download the Stable release for your OS (this book covers Windows but
since this tool is cross platform, it should be OK):

Ensure VS code is installed before continuing. Once installed, run it to see


the welcome screen:
Notice the Tools and languages section under Customize. Let’s add support
for Python by clicking on it:

Click OK on the prompt that comes up:

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.

Running the downloaded installer, we see:


Ensure Add Python to PATH is checked & click on Install Now to start
installation:

Once it’s done, we see the final screen:

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:

We see a screen like:

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 use brackets to enforce priority:


New Concept: In the above e.g. Python first evaluates 5+5,
multiplies its result with 10 as ‘*’ operator has higher
precedence or priority than ‘/’. This is called operator
precedence.

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.

New Concept: a keyword is a Python reserved word. It has a


predetermined special meaning & we can’t use it for any other
purpose.
Some common keywords are:
True, False, None, and, or, not, def, if, else, for, while, try,
except

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.

New Concept: Any values (anything in between the brackets) we pass to a


function are called as parameters or params. Here ‘hello python’ is a param.

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 see a notification asking us to select our Python interpreter:


Click on Select Python Interpreter & select the highlighted from the drop
down list that now appears at the top of the window:

We now see a new notification asking us to install the Python linter, let’s do
so by clicking on Install:

New Concept: Linters help with checking our code as we type.


Helping us avoid common programming errors.

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:

Hit Tab to auto complete.


Typing in the ‘(‘ brings up more help:
In this case, we only need to use the first parameter. Notice the -> None on
the third line. This indicates what the function returns. print() returns nothing.

New Concept: functions can take in values as params. They


can also return us results or others values.

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.

Completing the program, we have:


print('Addition program')
firstNo = input('Enter first no.:')
secondNo = input('Enter second no.:')
print(firstNo+secondNo)

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:

Type in any number & hit Enter:


Type in another number & hit Enter:

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:

To do so, we can use another built-in function called format(). We call


format() on a string pattern that has placeholders for actual values. The actual
variables are passed, in order, to format as params:
'{} + {} = {}'.format(firstNo, secondNo, float(firstNo)+float(secondNo))
Notice the string pattern is a string with the output pattern we wish to see.
Placeholders are indicated with a ‘{}’ whose value will be filled-in by the
param, in the same order or sequence.
Refactoring line 4 to get:
print('{} + {} = {}'.format(firstNo, secondNo,
float(firstNo)+float(secondNo)))
And executing the program we see:

New concept: notice that we called the format() on a string i.e.


‘some string’.format(). In other words, format is defined for
string objects (things). This is an e.g. of object oriented
programming where the string is an object & format is a
function defined in that object.

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:

Display app header


Get user inputs / data i.e. get the 2 nos.
Process data i.e. add the nos.
Display result
Let’s refactor our program to instead call 4 functions that would do the above
steps. Starting with this level helps identify what functions are required. For
instance:
display_app_header('Addition program')
userInput = get_user_inputs()
result = add(userInput)
display_result(result)
The entire program is now readable. A new programmer can easily
understand the flow by looking at such higher level functions.

New Concept: Each programming language has its own


coding styles. Python function & variable names must be lower
case with underscores between words.

To create these new functions we use the following syntax or grammar:


def function_name(param_name):
# code
def, a keyword, indicates that we are defining our new function named
‘function_name’ that takes in a parameter named param_name. VS code will
automatically indent your code. Indented code belongs to the function so
indenting is critical. Also, note the use of comments. We can write such notes
to self or other programmers to convey extra information. To do so simply
start the comment line with a ‘#’
Writing the display app header function, we have:
def display_app_header(header_text):
print(header_text)

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]

def display_result(inputs, result):


print('{} + {} = {}'.format(inputs[0], inputs[1], result))

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:

Next, let’s look at some conditional processing.


Evens & odds
Say, we need to display a list of all even nos. between a given range. Writing
the high level functions for this we have:
range = get_range()
display_even_nos(range)
So, we need to get the range & then display the even nos. in that range.
Writing the code for get_range() we have:
def get_range():
start = input('Enter starting no: ')
stop = input('Enter final no: ')
range_value = []
range_value.append(start)
range_value.append(stop)
return range_value
Here we store the start & stop values that we get from the user. We also
leverage lists to help group both these & return as one.
We now need to loop through each range value, check to see if that value is
even & display only if it’s even. To do so we need to use conditions. The if
condition syntax is:
if expression:
# code
So putting the condition & loop together we have:
def display_even_nos(rangeValue):
for i in range(rangeValue[0], rangeValue[1]+1):
if i%2==0:
print(i)
We use the range() to iterate through the given start & stop values. Notice we
have added 1 to the stop value as learnt from our previous e.g.
The if condition has the expression:
i%2==0
the ‘%’ operator gives us the remainder after division & if this is 0 we know
‘i’ is even.
The entire program is:
def get_range():
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

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():

We can again add another try in this function to catch TypeError:


def display_even_nos(range_value):
try:
for i in range(range_value[0], range_value[1]+1):
if i%2==0:
print(i)
except TypeError:
print('The entered range is not valid or missing.')
Running the program, we now see the expected messages being displayed to
the user without crashing:
Bulk processing files
Working on user input via console is fine for limited set of data. Often user
will have a file with all values to process in bulk. Bulk processing is faster &
truly utilizes the power of computers to quickly compute or process large
amounts of data.
We will now add all the nos. specified in a file instead of asking the user to
enter nos. one-by-one via the console.
We first need to get the file path from the user, read all the nos. in that file,
add the nos. & finally display the result. At the high level our program looks
like:
filePath = get_input_file()
nos = read_file(filePath)
result = add(nos)
display_result(result)
Writing the code for get_input_file() should be simple:
def get_input_file():
filePath = input('Enter full path to input file: ')
return filePath
Now that we have the file path, we need to open that file to read all values &
store each value in a list. To open a file we can use the built-in open().
Writing the code for the read_file(), we have:
def read_file(filePath):
file = open(filePath)
The open() takes in the file path as a param & returns a file object that
represents that file. This file object has various data or properties & also
functions that we can use, in our case we need to read all lines from this file.
We use the readlines() function on this file object like so:
lines = file.readlines()
Now, we only need to transform each line to a number & store each of them
in a list so that we can return the resulting list. To do so we have:
nos = []
for line in lines:
nos.append(float(line))
The completed function is:
def read_file(filePath):
file = open(filePath)
lines = file.readlines()
nos = []
for line in lines:
nos.append(float(line))
return nos
Next we need to add each no. The add() is simple:
def add(nos):
result = 0
for n in nos:
result += n
return result
We again loop through each no. in nos. & go on adding the no. to the result
variable using the shorthand ‘+=’ operator. Both these are same:
result = result + n
result += n
The entire program is:
def get_input_file():
filePath = input('Enter full path to input file: ')
return filePath

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.

New Concept: a module is nothing but a Python file. We were


actually writing modules till-now. The single .py file is a
module & we also know that it contains functions & other
global statements i.e. code. We can import & use other
modules i.e. .py files.

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))

Running this we see:

So sin 90 is not 1 as we learn in school. Anyways, lets round up this no. by


using ceil():
print(math.ceil(math.sin(90)))
We now get the output as 1, OK school made sense. Writing the entire
program using this we have:
import math

degree = float(input('Enter degrees in radians: '))

print('sin({}) = {}'.format(degree, math.ceil(math.sin(degree))))


print('cos({}) = {}'.format(degree, math.ceil(math.cos(degree))))
print('tan({}) = {}'.format(degree, math.ceil(math.tan(degree))))
Running the program we see:
Next steps
We have covered a lot in this example-driven study of the Python language.
We are now ready to continue learning more advanced language constructs
but that’s beyond the scope of this book.
The official Python docs is the best place to continue learning:
https://docs.python.org/

You might also like