Practical Lab:Introduction To Python Programming
Practical Lab:Introduction To Python Programming
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!")
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)
x = 20 # int
y = 3.14 # float
z = 1j # complex
x = 10
y = 2333444555
z = -88888999000
print(type(x))
print(type(y))
print(type(z))
x = 1.10
y = 1.0
z = -35.59
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))
math_operation = 1 + 3 * 12 / 2 - 2
print(math_operation)
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.
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)
or
marks= " I got {} marks in test."
print(marks.format(number))
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)
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:
x = "Hello World"
print("x=" + x)
x = 20.5
x = ["apple", "banana", "cherry"]
print("x=" + x[0])
x = True
print("x="+ str(x))
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])
split() method splits the string into substrings if it finds instances of the separator
a = "Hello, World!"
print(a.split(",")) # returns …………………………….
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)
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.
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")
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")
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 = ['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:
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 ………………………………..
pop() method: removes the specified index, (or the last item if index is not specified):
thislist = ["apple", "banana", "cherry"]
thislist.pop()
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]
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)
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.
Open a file: To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
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 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()
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