CSX3001 Class02 1 2023
CSX3001 Class02 1 2023
PYTHON
1
HELLO PYTHON!
The line str = "Hello Python" in the above code creates a variable named
str and assigns it the value of "Hello Python". Basically, the assignment
operator (=) assigns a value to a variable. A variable is like a container; you can
use it to hold almost anything – a simple number, a string of letters, or Boolean.
The variable name is a named location used to store data in the memory.
You can think variable as a box to store toys in and those toys can be replaced at
any time. Let’s see an example below.
number = 10
print(number)
Initially, the value of the number was 10. Later it changed to 15.5. So, when
you run the program, the output will be:
10
15.5
I think you might have a question about why I give a red color on the third line.
The # symbol is used for writing a comment. The comments are notes that are
ignored by the computer and are there to help you read the code and understand
what’s going on. You just put hashtag (#) in front of the text you want to comment.
You can name a variable almost anything you want, with a few exceptions.
You can’t name them something that is already a word in python. These are pre-
defined keywords in Python which are not allowed to be used as variable names.
2
False, class, finally, is, return, None, continue, for,
lambda, try, True, def, from, nonlocal, while, and, del,
global, not, with, as, elif, if, or, yield, assert, else,
import, pass, break, except, in, raise
You also can’t have two variables with the same name in the same block of code.
You can have the same name for two variables in Python, but the value will be
based on the latest assignment.
There are various data types in Python. These are the basic types that you must
know... just for now.
Numeric – Integer and floating-point numbers. They are defined as int and float
respectively. For instance,
NUMBERIC EXERCISE
1. Create a new Python file and name it “Class02-ex1.py”. Try the following
code and answer the following question.
x = 21
print(x)
y = 1.25
print(y)
1.1 What is the data type of variable x? ............... and variable y ...............
3
EXPRESSION EVALUATION EXERCISE
2. Create a new Python file and name it “Class02-ex2.py”. Try the following
code and answer the following question.
x = 5 + 2 * 3
y = 100 * 20 - 5 / 100 + 0.05
2.1 What is the data type of variable x? ............... and its value .................
2.2 What is the data type of variable y? ............... and its value .................
2.3 Rewrite the first line and second-line expression with proper order of
operations using parentheses.
x = .............................................................................................
y = .............................................................................................
3. From question 2, you learned how the mathematical operators work and
their orders (operator precedence). High precedence means that operator
will be calculated first. Specify the precedence order for the following
operators with given numbers. Note that one or more operators can have
the same precedence order.
Operator ÷ - x + ()
Precedence Order 0
When two operators share the same precedence order. For instance, plus and
minus. We will calculate the expression with left-to-right calculation. Consider
the following expression.
3 - 5 + 7
The expression will be calculated from 3 - 5, then + 7. The rule which applied to
control this kind of calculation when two operators have the same precedence
4
order is called “operator associativity” Most of the operator associativity of
mathematic operator is left-to-right associativity.
4. There is one more basic mathematical operator that you must know.
Create a new Python file and name it “Class02-expression2.py”. Try the
following code and answer the following questions.
w = 12 % 4
print(w)
x = 10 % 7
print(x)
y = x % (w + 1)
print(y)
z = z % 2
print(z)
4.1 What is the data type of variable w? ............... and its value ................
4.2 What is the data type of variable x? ............... and its value .................
4.3 What is the data type of variable y? ............... and its value .................
4.4 What is the data type of variable z? ............... and its value .................
The % operator is called modulo operator, which might not be as familiar to you.
The modulo operator (also called modulus) gives the remainder after division.
You will get more used to it from the assignment.
a = a + b
becomes
a += b
5
These operators will update the value of a variable by performing an operation
on it. In plain English, an expression like a += b says “add b to a and store the new
value in a.” Let’s see examples for other mathematical operations.
5. Let’s see the += operator in action. Imagine that we’re trying to write a
program to calculate the number of animals on an ark.
animalsOnArk = 0
numberOfGiraffes = 4
animalsOnArk += numberOfGiraffes
numberOfElephants = 2
animalsOnArk += numberOfElephants
numberOfAntelope = 8
animalsOnArk += numberOfAntelope
5.1 After four giraffes, two elephants, and eight antelope board the ark,
the final value of animalsOnArk is............................................................
6
BASIC STRING EXERCISES
You can also connect one String and another String together using + symbol. This
process is called String concatenation. See the examples,
message = "Hello"
name = "Ada"
result = message + " " + name
The third line shows how the String concatenation works. The value of result
variable will be as follows.
"Hello Ada"
message = "Hello"
name = "Ada"
result = f"{message} {name}"
Python provides you with an easier way to format your String called f-String. In
general, this way is called (instead of String concatenation) String interpolation.
The f-String works either start with lowercase “f” or uppercase “F”. To interpolate
any variable values, you must refer to the variable inside { }.
7
7. Create a new Python file and name it “Class02-ex7.py”. Try the following
code and answer the following questions.
name = "Ada"
surname = "Lovelace"
position = "Programmer"
country = "UK"
8. Create a new Python file and name it “Class02-ex8.py”. Try the following
code and answer the following questions.
print("Name:\t\tAda")
print("Surname:\t\tLovelace")
print("Programmer\nin UK")
8
\t and \n are two of the Escape Sequences (there are more) which are predefined
for String decoration.
INPUT/OUTPUT EXERCISES
or
The default type of the input will always be String. If you want it to be other type,
you can cast the type as shown below.
Be reminded that the input x must be only number. If x is English words, the
program will crash. Let’s try the above code in Python and enter Hello as an input.
We can also specify the guideline message for the user. For instance,
will run as
9
For the Python file name, use the same naming format as specified in earlier
exercises.
9. Write a code to take two inputs (your age and your name) and store in two
variables namely, myAge and myName. Variables myAge and myName
must be integer and string, respectively. Print the entered age and name
on the screen using f-string format. Expected output is as follows if the
entered age is 65 and name is Ada.
10. Write a code to take two inputs and store them in two string variables,
namely firstName and lastName, respectively. Connect the two strings
with an empty String (" ") in between and store them in a variable fullName.
Then print fullName’s string value on the screen (using f-string format). The
expected input/output is as follows.
10
Boolean in Python is more like a two-constant value; True and False. They are
used to represent truth values. For instance,
isOpen = True
isPossible = False
The common type of Boolean expression is one that compares two values using
a comparison operator. There are six comparison operators.
Considering the following code and each line’s value on the right column.
3 + 2 == 5 True
4 + 5 == 8 False
3 != 5 True
4 + 5 != 8 True
9 > 7 True
9 < 11 True
3 + 4 >= 7 True
3 + 4 > 7 False
11
5 + 6 <= 11 True
5 + 6 < 11 False
Considering the following code and each line’s value on the right column.
age = 12 12
age > 10 and age < 15 True
age = 18 18
age > 10 and age < 15 False
12
BOOLEAN EXERCISES
12. What is the Boolean value of the following expression if A = True, B = False,
C = True, and D = True?
x = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
You can also use the parentheses ( ) for line continuation as follow:
x = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9)
If you want to write multiple statements in one-line, you can use semicolons for
separated each statement as follow:
x = 1; y = 2; z = 3
13
WEEKLY ASSIGNMENT
ID_Name_Sec#_Class#_AS#.py
For example,
6619999_JamesBond_541_Class02_AS1.py
1. Write a Python code to take three integer inputs (month, week and day)
and store them in three variables namely, month, week and day,
respectively. Variables month and week are a total number of months and
weeks in the project, respectively, and a variable day is a total number of
past working days. Print the remaining working days and the output must
follow the outputting format given in the sample runs. (Hint: len() and f-
string format) For example, myStr = ‘hello’, len(myStr) is equal to 5.
Assume that one is month has 30 days and 1 week has 7 days.
print(‘$’*5) will give you $$$$$ (five dollar signs) in Python.
Sample Run 1
Sample Run 2
14
2. Write a Python code to take one 4-digit integer input and store it in a
variable namely, myNum. Print the output which is a summation of digits
in tens and thousands places. Note that the output digit is placed between
* on both sides where the total number of * is equal to an output digit
value. (Hint, you need modulo and floor division operators to get a digit in
each place)
Sample 1
Sample 2
15