2CompSci 101 - Principles of Programming
Naming conventionsPython typesVariables StringsOperatorsAlgebraic expressionsThe math module, the random moduleGetting input from the user FunctionsBoolean expressions, selection statements Loops – while and for…in Lists
Test topics
3CompSci 101 - Principles of Programming
Variable namesMust begin with a letter or underscore, e.g., number1 is OK, but
1number is notMay contain letters, digits, and underscores, e.g.,
this_is_an_identifier_123May be of any lengthUpper and lower case letters are different, e.g., Rope_Length
is not the same variable as rope_lengthThe standard way for most things named in python is lower case
with separate words joined by an underline, e.g., my_list
xageage_of_childbox1box_2_ageage_
3
age of child
age-child
1st
2_box
valid variable names:
NOT valid variable names:
4CompSci 101 - Principles of Programming
Python types encountered this semester Information in a program is categorised into different types. A type
in Python defines two things:the internal structure of the type (the information being stored)the kinds of operations you can perform with this type of object
intfloatstring booleanlist
5CompSci 101 - Principles of Programming
Converting between types Some types can be converted into different types:
result1 = int("2.1")result2 = float("2.1 ")input = "2.1"result3 = "$" + float(input)
result1 = float("2.1")result2 = int("24")result3 = float("24")input = "2.1"result4 = "$" + str(float(input) * 2)
NO!
YES!
6CompSci 101 - Principles of Programming
Doing CalculationsThe following mathematical operators can be used with integers
and with floating point numbers: Addition + Subtraction - Multiplication * Division / and // Exponentiation ** Modulus %
result1 = 25 / 4 + 4 * (10 % 3)
result2 = 25 - 7 * (3 + 12) / 3
result3 = 17 % 5 ** 2 - 12 + 15
result4 = 4 ** 2 // 5 / 2
print(result1, result2, result3, result4)
B - Brackets
Exponents (**)
Multiplication, Division, Modulus, Integer division
Addition, Subtraction
7CompSci 101 - Principles of Programming
Assignment operatorVariables can only store one value. Any value assigned to a
variable replaces the value previously stored in the variable.
a = 3
b = 12
c = 6
d = 1
d = d * a
c = c + 2 * a
d = d - b // c
c = c * b % c
b = b // 2
print (a, b, c, d)
8CompSci 101 - Principles of Programming
math moduleThe math module contains lots of useful functions:
import math
def main():
area = 221.67
radius = math.sqrt(area / math.pi)
print("Radius of circle", radius)
main()
9CompSci 101 - Principles of Programming
Manipulating string objects
strings: the len() function, string slicing, string indices, repeating a string
words = "Cheeky one"
letter1 = words[0]
position = len(words) - 2
letter2 = words[position]print(letter1, letter2)
first_part = words[0:4]
second_part = words[5:8]print(second_part, first_part)
first_part = words[:3]
second_part = words[7:]print(second_part, first_part)
encouragement = "Go! "
encouragement = encouragement * 4print(encouragement)
10CompSci 101 - Principles of Programming
Dot notation with string objects
String instances have many methods which can be applied to them such as upper(), lower(), find(), strip(), rfind()
words = "Bim Bam"
words_lower = words.lower()
words_upper = words.upper()print(words, words_lower, words_upper)
words = "Sweety pie"
postion1 = words.find("e")
postion2 = words.rfind("e")
postion3 = words.rfind("ty")
position4 = words.rfind("typ")print(postion1, postion2, postion3,
position4)
letters1 = " Sugar pie "
letters2 = letters1.strip()print(len(letters2))
11CompSci 101 - Principles of Programming
Common Python inbuilt functionsInbuilt:
len(), min(), max(), round(), abs()
number = min(32.7, max(16.4, 3, -1.1),
min(56.99, 32.2))print(number)
num1 = 32.657123
num2 = -16.48926
print(round(num1))
print(round(num2))
print(round(num1, 2))
print(round(num2, 3))
num1 = 10
num2 = 20
num3 = abs(num1 – num2)print(num3)
12CompSci 101 - Principles of Programming
Getting input from the userThe input() function is used to get input from the user. The input()
function returns a string.
age = input("Enter age: ")print(age * 2, age * 3, age * 4)
number = input("Enter number: ")number = int(number)print(number * 2, number * 3, number * 4)
Enter age: 5
Enter number: 5
13CompSci 101 - Principles of Programming
Random numbersWhat is the biggest value which can be printed?What is the smallest value which can be printed?
import random
def main(): num1 = random.randrange(2, 15, 3) num2 = random.randrange(24, 27, 2) num3 = num1 + num2
print(num3)
main()
14CompSci 101 - Principles of Programming
Syntax of a Python function Format of a function
def function_name(comma_separated_parameters):
statements in the function
return value_to_be_returned
Function name Function parameterscolon'def'
Indentation (either 1 tab or 4 spaces)
Return value'return'Statements in
the body of the function.
15CompSci 101 - Principles of Programming
Python functions
def display_welcome(name): message = "Welcome **" + name + " **" print(message)
def main(): display_welcome("Sam")
def display_welcome(name):message = "Welcome **" + name + " **"print(message)
return
def main(): display_welcome("Sam")
Both functions do the same thing. The return is optional.
16CompSci 101 - Principles of Programming
Defining functionsComplete the definition of the check_sum() function, which
returns True if the sum of the first three parameter values is equal to the fourth parameter value, otherwise the method returns False. def check_sum( ):
def main(): print(check_sum(15, 2, 7, 24)) print(check_sum(10, 2, 3, 24))
main()True
False
17CompSci 101 - Principles of Programming
Defining functionsComplete the definition of the get_next_even() function which
returns the first even number greater than the parameter number.
def get_next_even( ):
def main(): print(get_next_even(15)) print(get_next_even(10))
main()
16
12
18CompSci 101 - Principles of Programming
Code traceShow the code trace and the output
for the program
def main():
years = 5
result = test1(years)
print("A", result)
result = test2(years + 5)
print("B", years)
def test1(num):
print("C", num)
num = test2(num) + 4
return num
def test2(num1):
num1 = max(num1 + 1, 10)
print("D", num1)
return num1
main()years 5
main() function
19COMPSCI 101 - Principles of Programming
Booleans represent "truth" values, i.e., True or FalseRelational operators compare two different things, which
evaluates to Boolean values
Boolean Operators are: and, or and not, e.g., (age=24, gender='F') (age > 18) and (gender == 'F') is True (age > 34) or (gender == 'M') is Falsenot (age > 18) is False
Boolean expression
Description Operator Example
Equals == age == 10
Less than < age < 10
Less than or equal <= age <= 10
Greater than > age > 10
Greater than or equal >= age >= 10
20CompSci 101 - Principles of Programming
If statements x = 10y = 5
if x < 10: if y != 5: print("A") else: print("B")elif y > 10: print("C")else: if y != 5: print("D") else: print("E")
a = 4b = 12c = 37d = 51
if a < b: print("A")if a > b: print("B")if d <= c: print("C")if c != d: print("D")
Give the output
21CompSci 101 - Principles of Programming
Repetition – while loops
Give the possible output:
import randomdef main(): sum = 0
while sum < 10: number = random.randrange(1, 7) sum += number print(sum, number)
final_sum = sum – number print("Finally", final_sum)main()
while boolean_expression:
indented_code_block
22CompSci 101 - Principles of Programming
range(start, stop, step) functionThe range() function defines a sequence of values within the
boundaries (exludes the last value). The step parameter is optional. A for...in loop can be used to repeat code for each element in the specified range. Give the output.
number = 50for num in range(10, 1, -4):number = number – num
print("number:", number)
sum = 0for number in range(10, 16, 2):sum += number
print("sum:", sum) number:
sum:
23CompSci 101 - Principles of Programming
Repetition – for loops
Give the possible output:
def count_vowels(words): vowels = "aeiouAEIOU" length = len(words) count = 0 for i in range(length): if vowels.find(words[i]) != -1: count = count + 1 return count
def main(): word = input("Enter the word(s): ") print("Output: " + str(count_vowels(word)) + ".")
main()
for var_name in range(start, stop, step):
indented_code_block
24CompSci 101 - Principles of Programming
ListsA list is a sequence of comma separated elements within square
brackets.Elements of a list can be accessed using the index.The '+' operator can be used to add a new element to the end of a
list
my_list = [1, 2, 3]
my_list[1] = my_list[0] + my_list[2]
my_list[0] = my_list[1] + my_list[2]
my_list[2] = my_list[0] + my_list[1]
print(my_list)
Give the output
25CompSci 101 - Principles of Programming
ListsA list is a sequence of comma separated elements within square
brackets. The elements of a list can be traversed using a for…in loop. The elements of a list can be changed using the index value.my_list = [2, 6, 3]b = 0print("NOT changing list elements")for element in my_list: element = element + 2 b += elementprint("b:", b)print("my_list:", my_list)
print("Changing list elements")for index in range(len(my_list)): my_list[index] = my_list[index] + indexprint("my_list:", my_list)
NOT changing list elements
b:17
my_list:[2,6,3]
Changing list elements
my_list:[2,7,5]
Give the output
26CompSci 101 - Principles of Programming
Sequences and for loopsA string is a sequence. Each element of the string sequence (i.e.,
each character) can be accessed using a for loop:
phrase = "Give it a go"count = 0
for letter in phrase:if letter in "aeiouAEIOU":
count += 1
print("count", count)
for item in sequence:
indented_code_block
27CompSci 101 - Principles of Programming
Split a string into a list of wordsThe split() method splits a string into its parts. Default split (the
delimiter) is white space (e.g., words.split())Can use any other delimiters (e.g., words.split(", "), lines.split("\
n"))lots_of_words = "Whether you think you can or you think you
can't, you are right"my_list = lots_of_words.split()count = 0
for word in my_list:if len(word) == 3:
count += 1print("count: ", count)
Count: 7
28CompSci 101 - Principles of Programming
The test is worth 15% of your final mark, which covers the topics up to Lecture 15 (included).
Date and Time: Tuesday 5th May 6:30pm - 7:45pm.Please bring your Student Id card, a pencil and an eraser.The test is a closed book test, so you cannot refer to any
material during the test. Calculators are not permitted.Please arrive by 6:15pm as you will be given 5 minutes'
reading time.The first part of the test is Multi-Choice Questions (2/3)
and the second part of test is written questions (1/3).Please notify Angela Chang if you have a test clash.
Test Next Week - Tuesday (5th May)