0% found this document useful (0 votes)
4 views21 pages

Programming Tutorial 2020

Uploaded by

Kasun Madusanka
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)
4 views21 pages

Programming Tutorial 2020

Uploaded by

Kasun Madusanka
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/ 21

Introduction to Programming using Python

Development Program 2020

Dr. Rajitha Udawalpola


Mr. Anuradha Mudalige
June 22, 2020

1 Introduction
1.1 What is Computer Programming?
Computer Programming means teaching a computer to do something. Com-
puters are not intelligent at all and can not think. They can not do anything by
themselves. But if you can teach them, they can perform amazing things.
Computers can only understand electrical signals. Therefore we have to
write our programs using binary numbers where 1 stands for ON and 0 stands
for OFF. We call this machine language. Programs written in the machine lan-
guage are not very human readable. Therefore we write programs in high-level
languages and use a translator (compiler/interpreter) to convert it to machine
code.

1.2 Why we should learn programming


• Programming is a basic literacy (For Engineers it is a compulsory skill).
Programming can be very interesting and rewarding, as a hobby or a pro-
fession. Programming isn’t that hard to learn
• It’s a way to create change. Software can change our lives. (Facebook,
google search, gmail, google maps, Microsoft office, Android)
• Maybe you can’t find a program that does exactly what you want or need
it to do, so you want to write your own.
• You have an idea for then next big tech innovation? Great. Can you bring
it to life?

1
1.3 Why Python?

Figure 1: Python logo

With all the programming languages to choose from (and there are a lot!),
why did we pick Python for a programming? Here are few reasons.

• Python was created from the start to be easy to learn. Python programs are
about the easiest to read, write, and understand of any computer language
I have seen.

• Python is free. You can download Python-and many, many fun and useful
programs written in Python-for free.

• Python is open source software. Part of what open source means is that
any user can extend Python Many people have done this, and there is a
large collection of free Python stuff that you can download.

• Python isn’t a toy. Although it’s very good for learning programming,
it’s also used by thousands of professionals around the world every day,
including programmers at institutions like NASA and Google. So once
you learn Python, you don’t have to switch to a “real” language to make
“real” programs. You can do a lot with Python.

• Python runs on different kinds of computers. Python is available for Win-


dows PCs, Macs, and computers running Linux. Most of the time, the
same Python program that works on your Windows PC at home will work
on the Mac at your school. You can use this book with virtually any com-
puter that has Python.

• I like Python. I enjoy learning it and using it, and I think you will, too.

2
2 Setting Up Python Development Environment
2.1 Installing Python
There are a many ways to start using Python. One is using standard Python
distribution found in python.org, and that’s the one we will use for now.

Computers in Engineering Faculty Computer Center have Python already


installed in them. However, since you will be following this course from home,
I have explained how to install Python in your home PC in a separate guide that
you can find in the LMS.

2.2 Opening IDLE


In the Start menu, you can find the option to open IDLE (Python 3.8 32-bit) (as
shown in Figure 2)

Figure 2: Opening IDLE

Click this option, and you will see the IDLE window open up. It should look
something like the window in Figure 3
IDLE is a Python shell. A shell is basically a way of interacting with a pro-
gram by typing text, and this shell lets you interact with Python. program is a

3
Figure 3: Python IDLE Interactive Shell

number of instructions collected together. So let’s make our first Python pro-
gram.
First, you need a way to type in our program. If you just type it in the
interactive window, Python won’t “remember” it. You need to use a text editor
(like Notepad for Windows) that can save the program to the hard drive. IDLE
comes with a text editor that is much better for what you need than Notepad.
To find it, select File : New Window from IDLE’s menus as in Figure 4

Figure 4: Opening a Program Editor

You will see a window like in the Figure The title bar says “Untitled” because
you haven’t given it a name yet. When you are done, save the program using
the File : Save or File : Save As menu option. Call the file hello.py. You can
save it wherever you like (as long as you remember where it is, so you can find it

4
later). You might want to create a new folder for saving your Python programs.
The .py part at the end is important, because it tells your computer that this is
a Python program, and not just any old text file.
You might have noticed that the editor used some different colors in the
program. Some words are in orange and others are in green. This is because
the IDLE editor assumed that you would be typing in a Python program. For
Python programs, the IDLE editor shows Python keywords in orange and any-
thing in quotation marks in green. This is meant to help you read your Python
code more easily.
Once you have saved your program, go to the Run menu (still in the IDLE
editor), and pick Run Module as shown in the Figure 5. This will run your
program.

Figure 5: Running your programme

5
3 Programming in Python: PART I
Let us start to learn the basics of programming using Python. The concepts that
you will learn during this course are common to any programming language;
only the syntax will differ.

3.1 Printing output


The print() function is used to print data in a human-readable form. The input
to the function should be what you want to print on the screen. The Listing
shows how the function print() can be used to print different entities.
# printing a string
print ( " hello python " )

# printing an expression
print (34*2 + 4)

x = 5 y = 4
# printing a variable
print ( x )

# printing a combination of strings and variables


print ( " Value of X is " ,x , " and value of y is " , y )

3.2 Comments
Adding comments is a good habit in programming. It improves readability of
the code. In Python, comments start with a #
Python will ignore the comments and will not execute them.

3.3 Variables
What Exactly is a Variable?: A variable is the name for a place in the computer’s
memory where you store some data. They way we can declare variables in
Python is shown below. A variable is created the moment you first assign a
value to it.
x = 1 # integer variable
first_name = " Tom " # string variable
y = 34.56 # floating - point ( decimal ) number variable
z = 4 + 3 j # complex variable

6
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, volume). Following rules must be followed when naming a vari-
able in Python.

• A variable name must start with a letter or the underscore character

• A variable name cannot start with a number

• A variable name can only contain alpha-numeric characters and under-


scores (A − z ,0 − 9, and _ )

• Variable names are case-sensitive (age, Age and AGE are three different
variables)

You can use these variables for calculation in your program. You can also
display the value of a variable using print() function.
print ( x )
dy = y * 0.1
print ( " First Name " , first_name )
z2 = z + x

3.4 Reading Inputs from Keyboard


The function input() can be used to read input from the keyboard. The input
value is always a string.
f_name = input ( " Enter first name : " )
print ( " Hello " , f_name )
If we need numbers we need to convert strings to numbers. We can do that
as following.
num1 = int ( input ( " Enter an integer : " ))
print ( num1 + 3)
num2 = float ( input ( " Enter a floating point number : " ))
print ( num2 * 2)

3.5 Mathematical operations


Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common math-
ematical operations:

7
Figure 6: Python Arithmetic Operators

Python Comparison Operators


Comparison operators are used to compare two values.

Figure 7: Python Comparison Operators

Using math module


The module math can be imported to your program to perform various math-
ematical operations. For example the sin and cos functions can be used as in
following listing.

8
import math

x = math . pi /6
y = math . sin ( x )

print ( " y = " ,y )

z = math . sin ( x )**2 + math . cos ( x )**2

print ( " z = " ,z )

\ label { list : sin_cos }


There are many mathematical function available in math module. Please re-
fer the math documentation to learn more about them.

Using cmath module


We have to import cmath module to perform mathematical functions for com-
plex numbers.
Following listing shows the Python code for solving a quadratic equation of
form
ax2 + bx + c = 0,
where a, b and c are real numbers. The solution for this equation can be given
as √
−b ± b2 − 4ac
x= .
2a
Depending on values a, b and c the solution x can be real or imaginary number.
Therefore we have to use complex mathematics library. More information on
this can be found in cmath documentation

import cmath # for complex arithmetics


print ( " Solving equation of type aX ^2 + bX + c = 0 " )

# reading inputs print (" Input a ,b , c :")


a = float ( input ())
b = float ( input ())
c = float ( input ())

9
# solving equation
r1 = ( - b + cmath . sqrt ( b * b - 4* a * c ))/(2* a )
r2 = ( - b - cmath . sqrt ( b * b - 4* a * c ))/(2* a )

# displaying output
print ( " solutions are " , r1 , " and " , r2 )

10
4 Python Turtle
Turtle graphics is a popular way for introducing programming to total begin-
ners. It was part of the original Logo programming language developed by
Wally Feurzig and Seymour Papert in 1966.
Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an import tur-
tle, give it the command turtle.forward(100), and it moves (on-screen!) 100
pixels in the direction it is facing, drawing a line as it moves. Give it the com-
mand turtle.left(120), and it rotates in-place 120 degrees anti-clockwise. By
combining together these and similar commands, intricate shapes and pictures
can easily be drawn.
We can setup turtle environment as given in the following listing.

iimport turtle

# ##### Setting up Turtle #########


wn = turtle . Screen ()

wn . bgcolor ( " lightgreen " ) # Set the window background color


wn . title ( " Hello , Turtle ! " ) # Set the window title

tom = turtle . Turtle ()


tom . color ( " blue " ) # Tell Tom to change his color
tom . pensize (3) # Tell Tom to set his pen width
tom . shape ( " turtle " ) # We can change Tom ’s appearance here

# #### Our commands go here #####

tom . forward (100)


tom . left (120)
tom . forward (100)

# ##########################

wn . mainloop ()
Every turtle can have its own shape. The ones available “out of the box” are
arrow, blank, circle, classic, square, triangle and turtle.
You can find all the tutle commands in turtle documentation

11
Figure 8: Turtle graphics

Let’s play with the turtle


Let’s try to draw a square using turtle. Let’s change the background colour to
light-blue and colour of the turtle to red this time.
import turtle

wn = turtle . Screen ()
wn . bgcolor ( " lightblue " ) # Set the window background color
wn . title ( " Hello , Turtle ! " ) # Set the window title
tom = turtle . Turtle ()
tom . color ( " red " )
tom . pensize (3)
tom . shape ( " turtle " )

# drawing a square
tom . forward (100)
tom . left (90)
tom . forward (100)

12
tom . left (90)
tom . forward (100)
tom . left (90)
tom . forward (100)
tom . left (90)
wn . mainloop ()

Figure 9: Turtle graphics

13
5 Programming in Python: PART II
5.1 Loops
Let’s suppose you have a task to do which is to be repeatedly executed a thou-
sand times. Programming languages provide us with the concept of loops
which helps us execute some task n number of times where n can be any whole
number.

Python relies on indentation (whitespace at the beginning of a line) to define


scope in the code. Other programming languages often use curly-brackets for
this purpose.

for loop in Python


For loop in Python is used to iterate over a sequence of items. Flow chart of
Python for loop is shown in Figure 10

Figure 10: Flowchart of for loop in Python

I our previous task with Python turtle, we had been repeatedly executing
the same commands for several times. Let’s see how we can use the power of

14
looping to make our lives easier.

The same task can be implemented using a for loop as given in the following
listing.
import turtle

wn = turtle . Screen ()
wn . bgcolor ( " lightblue " ) # Set the window background color
wn . title ( " Hello , Turtle ! " ) # Set the window title
tom = turtle . Turtle ()
tom . color ( " red " )
tom . pensize (3)
tom . shape ( " turtle " )

# drawing a square with for loop

for i in [1 ,2 ,3 ,4]:
tom . forward (100)
tom . left (90)

wn . mainloop ()

Nested for loop in Python


We can have a loop inside a loop! Let’s discover how we can do it.

adjective = [ " Red " , " Green " , " White " ]
vehicle = [ " car " , " van " , " bus " ]

# Loop1
print ( " Loop1 " )

for x in adjective :
print ( x )

print ( " =============== " )

15
# Loop2
print ( " Loop2 " )

for y in vehicle :
print ( y )

print ( " =============== " )

# Now let ’s try a nested loop


print ( " Nested loop " )

for x in adjective :
for y in vehicle :
print (x , y )

Figure 11: Nested for loop example result

Python supports another type of looping command called while loop. How-

16
ever, during this short course we will work with only for loops

5.2 Functions
A function is a block of code which only runs when it is called. You can pass
data, known as parameters, into a function. A function can return data as a re-
sult. We can use functions in our program to reduce repetitive codes.

In Python a function is defined using the def keyword. To call a function, we


can use the function name followed by parenthesis. Information can be passed
into functions as arguments.

Let’s develop a function that calculates volume of a cuboid.

Figure 12: Cuboid and its algebraic relationships

# function definition
def calc_volume ( length , width , height ):
volume = length * width * height
print ( " Volume of the cuboid is : " , volume )

# Now let ’s use this function in our code


# Assume we have a cuboid with length , width and height of ...
# 2 ,3 and 4 meters respectively

l = 2.0
w = 3.0
h = 4.0

17
# Let ’s call our function

calc_volume (l ,w , h )

Figure 13: Function example result

5.3 Making Decisions and Python Lists


An "if statement" is written by using the if keyword. The elif keyword is
pythons way of saying "if the previous conditions were not true, then try this
condition". The else keyword catches anything which isn’t caught by the pre-
ceding conditions.

Figure 14: Operation of if statement

18
Figure 15: Operation of if..else statement

Figure 16: Operation of if..elif..else statement

19
Let’s look into a simple program that involves python lists and if statements.

import random

B = [2 , 4 , 1 , 3 , 45 , 3 , ]
A = []

for i in range (10):


x = random . randint (0 ,20) # generate a random integer
A . append ( x ) # append the generated random integer to A

# Let ’s print A and B


print ( " A = " , A )
print ( " B = " , B )

for num in A :
if ( num > 10):
print ( " number " , num , " is greater than " , 10)
elif ( num < 10):
print ( " number " , num , " is less than " , 10)
else : print ( " number " , num , " is equal to " , 10)

print ( " Maximum of A is " , max ( A ))


print ( " Minimum of B is : " , min ( A ))

B . reverse () # Reverse the order of the list


print ( " B = " , B )
Output of this program will be something similar to this.

A = [19 , 12 , 11 , 17 , 14 , 12 , 18 , 7 , 8 , 15]
B = [2 , 4 , 1 , 3 , 45 , 3]
number 19 is greater than 10
number 12 is greater than 10
number 11 is greater than 10
number 17 is greater than 10
number 14 is greater than 10
number 12 is greater than 10

20
number 18 is greater than 10
number 7 is less than 10
number 8 is less than 10
number 15 is greater than 10
Maximum of A is 19
Minimum of B is : 7
B = [3 , 45 , 3 , 1 , 4 , 2]
>>>

21

You might also like