Lecture 1 - NOTE
Lecture 1 - NOTE
Strutural Programming
Prepared by Mr Alpha Omar Leigh (Msc) and Mr Amandus Benjamin Coker
print("Hello, World!")
python hello_world.py
Output:
After running the program, you should see the following output:
Hello, World!
Basic Syntax:
Let's dive into the syntax of Python. It's crucial to understand the structure of Python code to write effective
programs.
In this example:
message is the variable name, chosen to represent the greeting message.
Page 5 of 17
Limkokwing_University
= is the assignment operator, which assigns the value on the right to the variable on the left.
"Hello, Python world!" is the value assigned to the variable message . It is enclosed in double
quotes to indicate that it is a string.
Scenario Continues:
Now, let's relate this back to our road trip scenario. Suppose you decide to change your destination from the
beach to the mountains. Similarly, you can change the value of the message variable to reflect a different
greeting:
Output:
Tr y It Yourself: Now, it's your turn to practice using variables in Python. Write separate programs to accomplish
the following exercises:
1. Simple Message: Assign a message to a variable and print it.
2. Simple Messages: Assign a message to a variable, print it, then change the value of the variable and
print the new message.
"This is a string."
'This is also a string.'
'I told my friend, "Python is my favorite language!"'
"The language 'Python' is named after Monty Python, not the snake."
These methods allow us to manipulate strings conveniently, facilitating tasks like standardizing input data or
formatting output.
Using Variables in Strings:
Often, we need to incorporate variable values into strings to create dynamic messages. Python's f-strings provide
a concise and expressive way to achieve this:
Page 7 of 17
Limkokwing_University
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(full_name) # Outputs: ada lovelace
# Combining with methods
print(f"Hello, {full_name.title()}!") # Outputs: Hello, Ada Lovelace!
Adding Whitespace:
Whitespace characters like tabs and newlines are crucial for formatting output. Python allows us to include them
in strings using escape sequences:
Stripping Whitespace:
Extra whitespace can lead to inconsistencies in data processing. Python provides methods like rstrip() ,
lstrip() , and strip() to remove leading, trailing, or both leading and trailing whitespace:
Page 9 of 17
Limkokwing_University
# Addition
result = 5 + 3 # Result: 8
# Subtraction
difference = 10 - 3 # Result: 7
# Multiplication
product = 4 * 2 # Result: 8
# Division
quotient = 15 / 3 # Result: 5.0 (Always returns a float)
Floats:
Floats are numbers with decimal points, allowing for more precision in calculations.
They are used for tasks involving measurements, scientific calculations, or financial data.
Python handles float operations similarly to integers but with added flexibility for decimal points.
Example operations:
# Addition
total = 0.1 + 0.2 # Result: 0.30000000000000004 (Due to floating-point precision)
# Subtraction
difference = 5.5 - 2.3 # Result: 3.2
# Multiplication
area = 3.14 * 2.5**2 # Result: 19.625
# Division
ratio = 10 / 3 # Result: 3.3333333333333335
Multiple Assignment:
Python allows assigning values to multiple variables in a single line, facilitating concise and readable
code.
Example:
x, y, z = 1, 2, 3
Constants:
Constants are variables whose values remain unchanged throughout the program.
Page 10 of 17
Limkokwing_University
Python doesn't have built-in constant types, but programmers use naming conventions (all capital
letters) to denote constants.
Example:
MAX_CONNECTIONS = 5000
In the exercises below, you'll practice using numbers in Python and reinforce your understanding of these
concepts. Let's dive in:
Exercises:
1. Number Eight:
Write addition, subtraction, multiplication, and division operations that each result in the
number 8.
Enclose your operations in print() calls to see the results.
2. Favorite Number :
Use a variable to represent your favorite number.
Create a message that reveals your favorite number using that variable, and then print the
message.
3. Adding Comments:
Choose two of your existing programs and add at least one comment to each.
If your programs are too simple, add your name and the current date at the top of each
program file.
Write one sentence describing what each program does.
# Given data
principal_amount = 1000 # in dollars
interest_rate = 0.05 # 5%
time_period = 2 # in years
# Calculate simple interest
simple_interest = (principal_amount * interest_rate * time_period) / 100
# Display the result
print("Simple Interest:", simple_interest, "dollars")
Page 11 of 17
Limkokwing_University
2. Compound Interest:
Problem: Calculate the compound interest earned on a principal amount over a given period of time, given the
principal amount, the rate of interest, the number of times interest is compounded per unit time, and the time
in years.
Formula: Compound Interest = Principal Amount × [(1 + (Interest Rate / Compounding
Frequency))^(Compounding Frequency × Time)] - Principal Amount
Example:
# Given data
principal_amount = 1500 # in dollars
interest_rate = 0.05 # 5%
compounding_frequency = 4 # quarterly
time_period = 2 # in years
# Calculate compound interest
compound_interest = principal_amount * ((1 + (interest_rate / compounding_frequency)) **
(compounding_frequency * time_period)) - principal_amount
# Display the result
print("Compound Interest:", compound_interest, "dollars")
# Given data
initial_velocity = 10 # in m/s
acceleration = 2 # in m/s^2
time_taken = 5 # in seconds
# Calculate distance travelled
distance_travelled = initial_velocity * time_taken + 0.5 * acceleration * (time_taken ** 2)
# Display the result
print("Distance Travelled:", distance_travelled, "meters")
Page 12 of 17
Limkokwing_University
# Given data
initial_velocity = 10 # in m/s
acceleration = 2 # in m/s^2
time_taken = 5 # in seconds
# Calculate final velocity
final_velocity = initial_velocity + acceleration * time_taken
# Display the result
print("Final Velocity:", final_velocity, "m/s")
5. Work Done:
Problem: Calculate the work done by a force on an object, given the magnitude of the force and the
displacement of the object in the direction of the force.
Formula: Work Done = Force × Displacement
Example:
# Given data
force = 50 # in Newtons
displacement = 10 # in meters
# Calculate work done
work_done = force * displacement
# Display the result
print("Work Done:", work_done, "Joules")
Explanation:
The input() function prompts the user to enter their name.
The entered name is stored in the variable name .
The print() function displays a greeting message with the entered name.
2. Integer Input:
Explanation:
The input() function accepts the user's age as input.
The int() function converts the input string to an integer.
The converted integer is stored in the variable age .
The print() function displays the entered age.
3. Multiple Inputs:
Explanation:
The input() function accepts two numbers separated by a space.
The split() method splits the input string into a list of strings.
The map() function applies the int() function to each element of the list to convert them into
integers.
The converted integers are assigned to variables num1 and num2 .
Page 14 of 17
Limkokwing_University
The print() function displays the sum of the two numbers.
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
Explanation:
The f prefix before the string indicates an f-string.
Inside the f-string, variables name and age are enclosed within curly braces {} .
The values of name and age are inserted into the string when it is printed.
2. Formatting Numerical Data:
pi = 3.14159265359
print(f"Value of pi: {pi:.2f}")
Explanation:
The .2f format specifier specifies that pi should be formatted as a floating-point number with 2
decimal places.
The value of pi is inserted into the string with the specified format.
Assignment: Basics of Python Programming
Objective: The objective of this assignment is to reinforce the learning outcomes related to the basics of Python
programming, including syntax, data types, operators, comments, indentation, mathematics in Python, input
statements, and format strings.
Instructions:
1. Complete the following tasks by writing Python code for each question.
2. Save your code in a file named basics_assignment.py .
3. Ensure that your code adheres to Python 3 syntax.
4. Include comments in your code to explain the purpose of each section or any important details.
5. Submit your completed basics_assignment.py file for evaluation.
Assignment Tasks:
1. Variables and Data Types:
Declare and assign values to variables representing:
Page 15 of 17
Limkokwing_University
Your age (integer)
Your name (string)
Your height in meters (float)
Whether you are a student (boolean)
Print each variable along with its data type.
2. Operators:
Perform the following operations and print the results:
Addition of two numbers (e.g., 7 + 3)
Multiplication of two numbers (e.g., 5 * 4)
Division of two numbers (e.g., 10 / 2)
Exponentiation (e.g., 2 ** 3)
Comparison of two numbers using comparison operators (e.g.,
7 > 3)
Page 17 of 17