Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

Practical Lab:Introduction to Python

Programming
ECT200: Introduction to Computing

In this lab1, we will use the online python interpreter available in the address below:
https://repl.it

Type and execute all the below example programs. DO NOT COPY/PASTE.

First program:
print("Hello, World!")
Hello, World!
Comments: start with a #
#This is a comment.
print("Hello, World!")
Or
print("Hello, World!") #This is a comment
Or multiline comments as follow using triple quotes
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

Python Variables: Variables are containers for storing data values.


x = 4 # x is of type int
x = "Sally" # x is now of type str (string)
print(x)

Note: “Jose” is the same as ‘Jose’


A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for
Python variables:
 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 underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three different variables)

ECT200: Introduction to Computing (Winter) 1


Assign the same value to multiple variables in one line:
x = y = z = "Orange"
print(x)
print(y)
print(z)
Output Variables

x = "awesome"
print("Python is " + x)

x = "Python is "
y = "awesome"
z =  x + y
print(z)

x=5
y = 10
print(x + y)

x=5
y = "John"
print(x + y)

Python Numbers: There are three numeric types in Python:


• int
• float
• complex

x = 20    # int
y = 3.14   # float
z = 1j   # complex

Int or integer is a whole number without decimals, of unlimited length.

x = 10
y = 2333444555
z = -88888999000

print(type(x))
print(type(y))
print(type(z))

Float, or "floating point number" is a number, containing one or more decimals.

x = 1.10
y = 1.0
z = -35.59

ECT200: Introduction to Computing (Winter) 2


print(type(x))
print(type(y))
print(type(z))

Float can also be scientific numbers with an "e" to indicate the power of 10.

x = 15e2
y = 12E5
z = -67.7e300

print(type(x))
print(type(y))
print(type(z))

student_age = 19 # snake case


R = 12 #Constant in upper case
diameter = 2 * R #constant in upper case
print(diameter)

math_operation = 1 + 3 * 12 / 2 - 2
print(math_operation)

float_division = 8 / 3 # division result in float type


print(float_division)

integer_division = 8 // 3 # gives result in int type


print(integer_division)

remainder = 10 % 3
print(remainder)

Find Output?
Price = 9
Expenditure = 3
Profit = Price – Expenditure

String in Python: String literals in python are surrounded by either single quotation marks, or double
quotation marks.

my_string = """ Hello # multiline output


it is a great day
indeed"""
print(my_string)

ECT200: Introduction to Computing (Winter) 3


name = 'Jose'
my_name = name + ' Jose' # appending strings
print(my_name)

Find Output?
x=5
y = "John"
print(x + y)

age1 = 20
bb = str(age1) #convert type int to type str
try_name = name + bb
print(try_name)

number=30
a= f"I got {number} marks."
print(a)
number = 10
print(a)

marks="I got {number} marks in test"


print(marks.format(number = 10)) # to display dynamic value

or
marks= " I got {} marks in test."
print(marks.format(number))

my_name=input("Enter your name: ") # Entering user Input


name_info=print(my_name, "will go Europe today.")
print(name_info)

Local Variables: If you create a variable with the same name inside a function, this variable will
be local, and can only be used inside the function. The global variable with the
same name will remain as it was, global and with the original value

x = "awesome"

def myfunc():
  x = "fantastic"
  print("Python is " + x)

myfunc()

print("Python is " + x)

ECT200: Introduction to Computing (Winter) 4


The global Keyword: Normally, when you create a variable inside a function, that variable is
local, and can only be used inside that function . To create a global variable
inside a function, you can use the global keyword.

x = "awesome"
def myfunc():
  global x
  x = "fantastic"
myfunc()

print("Python is " + x)

Python Data Types: Variables can store data of different types. Python has the following data types built-
in by default, in these categories:

Text Type: str


Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview

Example Data Type


x = "Hello World" str
x = 20 int
x = 20.5 float
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = True bool

x = "Hello World"
print("x=" + x)
x = 20.5
x = ["apple", "banana", "cherry"]
print("x=" + x[0])
x = True
print("x="+ str(x))

ECT200: Introduction to Computing (Winter) 5


Python Strings: String literals in python are surrounded by either single quotation marks, or double
quotation marks. ‘hello' is the same as "hello".
print("Hello")
print('Hello')

Assign String to a Variable


a = "Hello"
print(a)

Strings are Arrays: Like many other popular programming languages, strings in Python are
arrays of bytes representing unicode characters.
# Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])

Slicing: You can return a range of characters by using the slice syntax. Specify the start index and
the end index, separated by a colon, to return a part of the string..
# Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])

Negative Indexing: Use negative indexes to start the slice from the end of the string:

# Get the characters from position 5 to position 1, starting the count from end of string:
b = "Hello, World!"
print(b[-5:-2])

ECT200: Introduction to Computing (Winter) 6


String Methods: Python has a set of built-in methods that you can use on strings. Write down what
each method is doing:

Strip( ) method: …………………………………………………………………………………


a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

lower( ) method: …………………………………………………………………………………


a = "HELLO, World!"
print(a.lower()) # returns "hello, world!"

Upper () method: returns the string in upper case


a = " Hello, World! "
print(……………………………..) # returns "HELLO, WORLD!"

replace() method replaces a string with another string


a = "Hello, World!"
print(a.replace("H", "J")) # returns ………………………….

split() method splits the string into substrings if it finds instances of the separator
a = "Hello, World!"
print(a.split(",")) # returns …………………………….

Upper () method: returns the string in upper case


a = " Hello, World! "
print(……………………………..) # returns "HELLO, WORLD!"

Check String: To check if a certain phrase or character is present in a string, we can use the
keywords in or not in.
Example: Check if the phrase "ain" is present in the following text:
txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x)

String Concatenation: To concatenate, or combine, two strings you can use the + operator.

a = "Hello"
b = "World"
c=a+b
print(c)

ECT200: Introduction to Computing (Winter) 7


String Format: we cannot combine strings and numbers. The format() method takes the
passed arguments, formats them, and places them in the string where
the placeholders {} are.

Example1:
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

Example2:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

Type and execute all the below example programs. DO NOT COPY/PASTE.

Python Command Line Input: Python allows for command line input. That means we are able to ask the
user for input.

print("Enter your name:")


x = input() # type your name
print("Hello ", x) #Displays ……………………………………

Python 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 result. .
Creating and Calling a Function: In Python a function is defined using the def keyword. To call
a function, use the function name followed by parenthesis:
def my_function():
  print("Hello from a function")

my_function() #Displays ……………………………………

Parameters: Information can be passed to functions as parameter. Parameters are specified after
the function name, inside the parentheses. You can add as many parameters as you want, just
separate them with a comma.
The following example has a function with one parameter (fname). When the function is called, we
pass along a first name, which is used inside the function to print the full name:
def my_function(fname):
  print(fname + " Refsnes")

my_function("Emil") #Displays ……………………………………

ECT200: Introduction to Computing (Winter) 8


my_function("Tobias") #Displays ……………………………………
my_function("Linus") #Displays ……………………………………

ECT200: Introduction to Computing (Winter) 9


Return Values: To let a function return a value, use the return statement:
def my_function(x):
  return 5 * x

print(my_function(3)) #Displays ……………………………………


print(my_function(5)) #Displays ……………………………………
print(my_function(9)) #Displays ……………………………………

Python Collections (Arrays): here are four collection data types in the Python programming language:
 List is a collection which is ordered and changeable. Allows duplicate members.
 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
 Set is a collection which is unordered and unindexed. No duplicate members.
 Dictionary is a collection which is unordered, changeable and indexed. No duplicate
members.
When choosing a collection type, it is useful to understand the properties of that type.
Choosing the right type for a particular data set could mean retention of meaning, and, it
could mean an increase in efficiency or security. In this lab, we will only concentrate on lists.

thislist = ["apple", "banana", "cherry"] # replace cherry with your name


print(thislist)
Access Items: You access the list items by referring to the index number:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Negative Indexing: Negative indexing means beginning from the end, -1 refers to the last item, -
2 refers to the second last item etc.
thislist = ["apple", "banana", "cherry"] # replace cherry with your name
print(thislist[-1]) #displays …………………………………………
Range of Indexes: You can specify a range of indexes by specifying where to start and where to
end the range. When specifying a range, the return value will be a new list with the
specified items.
thislist = [10, 20, 30, 40, 50, 60, 70] # replace the value 40 with your student ID
print(thislist[2:5]) #displays …………………………………………
Range of Negative Indexes: Specify negative indexes to start the search from the end of the list:

thislist = ['a','b','c','d','e','f','g']
print(thislist[-4:-1]) #displays …………………………………………

Change Item Value: To change the value of a specific item, refer to the index number:

thislist = ["apple", "banana", "cherry"]


thislist[1] = "blackcurrant" # replace blackcurrant with your name
print(thislist) # displays……………………………………………

ECT200: Introduction to Computing (Winter) 10


Check if Item Exists: To determine if a specified item is present in a list use the in keyword:
thislist = ["apple", "banana", "cherry"]
if "aple" in thislist: # displays ………………………………..
  print("Yes, 'apple' is in the fruits list")
else:   print("No, 'apple' is NOT in the fruits list")

List Methods: Python has a set of built-in methods that you can use on lists. Write down what each
method is doing:
len() method: to determine how many items a list
thislist = ["apple", "banana", "cherry"] # replace banana with your name
print(len(thislist)) # displays ………………………………..

append() method: To add an item to the end of the list


thislist = ["apple", "banana", "cherry"]
thislist.append("orange") # replace orange with your name
print(thislist) # displays ………………………….

insert() method: to add an item at the specified index


thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange") # replace orange with your name
print(thislist) # displays …………………………….

remove() method: removes the specified item


thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(…………………….) # displays ['apple', 'cherry']

pop() method: removes the specified index, (or the last item if index is not specified):
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist) # displays …………………………………….

ECT200: Introduction to Computing (Winter) 11


Write the instruction using pop to delete the third item on the list [10, 20, 30, 40, 50]
…………………………………………………………………………………..
…………………………………………………………………………………..
…………………………………………………………………………………..

clear() method: empties the list


thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist) # displays ……………………………………

Copy a List: You cannot copy a list simply by typing list2 = list1, because: list2 will only be a
reference to list1, and changes made in list1 will automatically also be made in list2.
copy() method: makes a copy of a list
thislist = ["apple", "banana", "cherry"] # replace banana with your name
mylist = thislist.copy()
print(mylist) # displays ……………………………………..

Join Two Lists: There are several ways to join, or concatenate, two or more lists in Python. One of
the easiest ways are by using the + operator..
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list3 = list1 + list2


print(list3) # displays ………………………………………..

extend() method: adds elements from one list to another list


thislist = ["apple", "banana", "cherry"] # replace banana with your name
mylist = thislist.copy()
print(mylist) # displays ……………………………………..

Passing a List as a Parameter to a Function: You can send any data types of parameter to a
function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the
function. E.g. if you send a List as a parameter, it will still be a List when it reaches the function:
def my_function(food):
  for x in food:
    print(x)

fruits = ["apple", "banana", "cherry"] # replace banana with your name

my_function(fruits) #Displays ……………………………………

ECT200: Introduction to Computing (Winter) 12


Type and execute all the below example programs. DO NOT COPY/PASTE.

Python While Loop: With the while loop we can execute a set of statements as long as a condition is
true.
i=1
while i < 6:
  print(i)
  i += 1 #Displays ……………………………………

The break Statement: With the break statement we can stop the loop even if the while condition
is true:
i=1
while i < 6:
  print(i)
  if i == 3:
    break
  i += 1 #Displays …………………………………

The continue Statement: With the continue statement we can stop the current iteration, and
continue with the next:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i) #Displays …………………………………

The else Statement With the else statement we can run a block of code once when the condition
no longer is true.
i=1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6") #Displays …………………………………
To do: Write the loops that will do the following. For each one, insert the code and a screenshot of the
execution.

- A While loop to print number between 100 and 200 that are multiple of 3 and 4
- A While loop that prints the letters of the word “Computing” separated by a space “C o m p u t i n g”
- A While loop that prints the sum of all odd numbers between 10 and 1000

Python File Handling: Python has several functions for creating, reading, updating, and deleting files.

The key function for working with files in Python is the open() function.

ECT200: Introduction to Computing (Winter) 13


The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition, you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)

Create a test file:


Create a text file named demofile.txt including the below text. Click on the icon “Add File”
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!

Open a file: To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")

The code above is the same as:


f = open("demofile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.

The open() function returns a file object, which has a read() method for reading the content
of the file:
f = open("demofile.txt", "r")
print(f.read()) #Displays …………………………………

Read Lines: You can return one line by using the readline() method:


f = open("demofile.txt", "r")
print(f.readline()) #Displays …………………………………
By looping through the lines of the file, you can read the whole file, line by line:
f = open("demofile.txt", "r")
for x in f:
  print(x)

Read Only Parts of the File: By default the read() method returns the whole text, but you can
also specify how many characters you want to return:
f = open("demofile.txt", "r")
print(f.read(5))

Close Files: It is a good practice to always close the file when you are done with it.
f = open("demofile.txt", "r")
print(f.readline())
f.close()

ECT200: Introduction to Computing (Winter) 14


Write to an Existing File: To write to an existing file, you must add a parameter to
the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read()) #Displays …………………………………

Open the file "demofile3.txt" and overwrite the content:


f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the appending:


f = open("demofile3.txt", "r")
print(f.read()) #Displays …………………………………

Create a New File: To create a new file in Python, use the open() method, with one of the
following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist

Create a file called "myfile.txt":


f = open("myfile.txt", "x")
Result: a new empty file is created!

Create a new file if it does not exist:


f = open("myfile.txt", "w")
Delete a File: To delete a file, you must import the OS module, and run its os.remove() function:

Remove the file "demofile.txt":


import os
os.remove("demofile.txt")

ECT200: Introduction to Computing (Winter) 15

You might also like