0% found this document useful (0 votes)
33 views

Lecture 1 - NOTE

Uploaded by

Benji Coker
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Lecture 1 - NOTE

Uploaded by

Benji Coker
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Limkokwing_University

Limkokwing University of Creative Technology

Strutural Programming
Prepared by Mr Alpha Omar Leigh (Msc) and Mr Amandus Benjamin Coker

Lecture 1: Basics of Python Programming


Learning Outcomes: Basics of Python Programming
By the end of this course, students should be able to:
1. Understand the fundamentals of Python programming, including its syntax, data types, and basic
operations.
2. Describe the key characteristics of Python as an interpreted language and explain its advantages and use
cases.
3. Differentiate between Python 2 and Python 3, recognizing the importance of using Python 3 for modern
development.
4. Demonstrate proficiency in writing Python code by applying basic syntax rules, including variable
Page 1 of 17
Limkokwing_University
declaration, assignment, and usage.
5. Utilize various data types available in Python, such as integers, floats, strings, lists, tuples, and
dictionaries, for storing and manipulating data.
6. Apply arithmetic, comparison, and logical operators effectively to perform mathematical calculations and
make decisions in Python programs.
7. Understand the significance of comments and indentation in Python code for enhancing readability and
maintainability.
8. Explore mathematical capabilities in Python, including built-in functions and modules for performing
complex mathematical operations and solving equations.
9. Implement input() statements to accept user input dynamically and interactively in Python programs.
10. Utilize format strings (f-strings) to create formatted output dynamically by embedding variables and
expressions within strings.

Introduction to Programming Languages:


Imagine you're learning a new language—a language that allows you to communicate with computers. This
language isn't like English or Spanish; it's a programming language. Just like humans use different languages to
convey ideas and instructions to each other, programmers use programming languages to communicate with
computers.Programming languages serve as a bridge between human thought and machine action. They
provide a set of rules and symbols that programmers use to write instructions, known as code, which the
computer can understand and execute.
Think of programming languages as tools in a toolbox. Each language has its unique features and strengths,
suited for different tasks and applications. Some languages are specialized for web development, others for data
analysis, and some for building mobile apps or even controlling robots.Learning a programming language is akin
to learning a new skill or mastering a new instrument. It requires practice, patience, and perseverance. However,
once you grasp the fundamentals, you'll unlock the ability to create software, solve problems, and bring your
ideas to life.
In this course, we'll delve into one of the most popular and versatile programming languages—Python. Python is
renowned for its simplicity, readability, and wide range of applications. Whether you're interested in building
websites, analyzing data, or developing artificial intelligence, Python has something to offer.Python, often
dubbed as a "high-level" programming language, is renowned for its simplicity and versatility. But why Python?
Well, imagine a language that emphasizes readability and simplicity, enabling you to express concepts in fewer
lines of code compared to other languages. Python fits the bill perfectly.

Exploring Python: Your Gateway to the Tech World**


Welcome to the world of Python programming! In this module, we will embark on a journey to explore the
fundamentals of Python programming and discover why it is one of the most sought-after skills in the tech
industry today.

Python in the Real World:


So, is learning Python worth the time and effort?
1. Popularity and Usage: Python has been around since 1991, making it older than Java but younger than C.
Despite its age, Python consistently ranks among the top five most popular programming languages. Many
Page 2 of 17
Limkokwing_University
renowned companies, including Google, YouTube, Instagram, Netflix, and Hulu, rely on Python for their everyday
operations. Professionals are hired and paid handsomely to write Python programs that power critical services
and applications.
2. Versatility and Practicality: Python's versatility makes it suitable for a wide range of applications. Whether
you're working on the command line in a monitor or terminal window, building graphical user interfaces (GUIs)
for desktop or web applications, developing backend servers for large-scale websites, managing servers in the
cloud, or even programming for mobile or embedded devices, Python has you covered. Its adaptability to
various computing environments makes it an indispensable tool for developers across industries.
3. Productivity and Efficiency: One of Python's standout features is its reputation for enhancing productivity.
Its clean and concise syntax allows developers to write code that is both readable and maintainable, resulting in
faster development cycles and reduced time-to-market for projects. This productivity boost is particularly
attractive to fast-moving organizations that value agility and efficiency in their development processes.
4. Real-world Applications: Python isn't just a language for academic exercises or small-scale projects—it's the
real deal in the tech industry. From building web applications to conducting data analysis, from automating
repetitive tasks to developing artificial intelligence and machine learning solutions, Python is a powerhouse that
drives innovation and solves real-world problems.

Python as an Interpreted Language:


Unlike compiled languages such as C or C++, Python code is executed line by line by an interpreter. This means
that you can directly run Python code without the need for compilation, making it incredibly user-friendly and
efficient for rapid prototyping and development.

Python 2 vs Python 3 (Brief Comparison):


Python 2 and Python 3 are two major versions of Python that coexisted for several years. However, Python 2 has
reached the end of its life and is no longer being maintained. Therefore, we will focus solely on Python 3 in this
course.

Your Moment of Zen: The Zen of Python


In the world of programming, each language has its own unique style—a distinctive way of expressing ideas and
solving problems. Python, in particular, embraces a philosophy that values simplicity, clarity, and elegance in
code.Embedded within Python is a piece of wisdom known as "The Zen of Python," penned by Tim Peters. This
poetic manifesto encapsulates the guiding principles of Python programming, offering insights and reflections
that inspire programmers to write better code.To immerse yourself in this moment of Zen, simply type import
this into your Python interactive interpreter and press Enter. Allow these words to resonate as you navigate
the world of Python programming:

>>> import this

The Zen of Python, by Tim Peters:


Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Page 3 of 17
Limkokwing_University
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one--and preferably only one--obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea—let's do more of those!
Let these words guide your journey as you embrace the art and craft of Python programming. May they inspire
you to write code that is not only functional but also elegant and expressive.

Getting Started with Python: Hello World!


Welcome to the world of Python programming! In this lecture note , we'll take our first steps into the Python
language by exploring the iconic "Hello World" program. This simple yet essential program serves as our
introduction to Python syntax and execution.

The "Hello World" Program:


In programming tradition, the "Hello World" program is often the first program written by beginners to
demonstrate the basic syntax of a programming language. In Python, creating a "Hello World" program is as
straightforward as it gets.
Writing the Code:
To create a "Hello World" program in Python, follow these steps:
1. Open your preferred text editor or integrated development environment (IDE).
2. Create a new Python file and name it hello_world.py .
3. Type the following code into your file:

print("Hello, World!")

Understanding the Code:


Let's break down the code:
print() : This is a built-in Python function used to display output. Inside the parentheses, we provide
the message we want to print.
Page 4 of 17
Limkokwing_University
"Hello, World!" : This is the message we want to display. It is enclosed in double quotes to indicate
that it is a string.
Running the Program:
Once you've written the code, save the file and run it using a Python interpreter. You can do this by navigating to
the directory where your hello_world.py file is located and executing the following command in your
terminal or command prompt:

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.

Variables and Data Types:


Understanding Variables in Python**
In the world of programming, variables play a crucial role in storing and manipulating data. In this note, we'll
delve into the concept of variables in Python, exploring their syntax, usage, and common pitfalls.
Scenario:
Imagine you're preparing for a road trip. You need to pack your essentials—clothes, snacks, and gadgets. Each
item you pack represents a piece of data, and your suitcase acts as a variable—a container that holds these
items. Just as you can change what you pack in your suitcase, you can also modify the contents of a variable in a
program.
Syntax and Usage:
In Python, creating and using variables is straightforward. Let's break down the syntax and usage using the
example of a simple greeting message:

# Syntax: variable_name = value


# Example:
message = "Hello, Python world!"
print(message)

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:

# Modify the value of the variable


message = "Hello, Python Crash Course world!"
print(message)

Output:

Hello, Python Crash Course world!

Naming and Using Variables:


When naming variables in Python, adhere to the following rules and guidelines:
1. Avoid Special Characters: Variable names can contain only letters, numbers, and underscores. For
example:
Valid: my_variable , user_input , data_1
Invalid: my-variable , user$input , data!1
2. Star t with Letter or Underscore: Variable names can start with a letter or an underscore, but not with
a number. For example:
Valid: my_variable , _count , name
Invalid: 1_value , %discount , &total
3. No Spaces Allowed: Spaces are not allowed in variable names. Use underscores to separate words in
variable names. For example:
Valid: first_name , total_amount , student_score
Invalid: first name , total amount , studentScore
4. Avoid Python Keywords: Avoid using Python keywords and function names as variable names. For
example, do not use print or if as variable names.
5. Descriptive but Concise: Choose variable names that are descriptive yet concise. For example:
Good: student_name , total_score , num_students
Better: student_name , score_total , student_count
Avoiding Name Errors:
Be mindful of spelling errors when using variables. Python is case-sensitive, so a misspelled variable name will
result in a NameError . For example:
Page 6 of 17
Limkokwing_University

# Incorrect variable name


mesage = "Hello, Python Crash Course reader!"
print(mesage) # This will raise a NameError

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.

Understanding Strings in Python**


Introduction:
In the realm of programming, data comes in various forms, each serving its unique purpose. Among these,
strings hold a fundamental place. In this note, we'll explore the concept of strings in Python, understanding their
characteristics, manipulation methods, and common usage scenarios.
Strings Defined:
Strings, at their core, are sequences of characters. In Python, anything enclosed within quotes—single or double
—is considered a string. This flexibility allows us to include quotes and apostrophes within strings seamlessly:

"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."

Changing Case with String Methods:


One of the basic operations with strings involves changing the case of the text. Python provides methods like
title() , upper() , and lower() for this purpose. Consider the following example:

name = "ada lovelace"


print(name.title()) # Outputs: Ada Lovelace
print(name.upper()) # Outputs: ADA LOVELACE
print(name.lower()) # Outputs: ada lovelace

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:

print("\tPython") # Outputs: Python


print("Languages:\nPython\nC\nJavaScript") # Outputs:
# Languages:
# Python
# C
# JavaScript

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:

favorite_language = ' python '


print(favorite_language.rstrip()) # Outputs: ' python'
print(favorite_language.lstrip()) # Outputs: 'python '
print(favorite_language.strip()) # Outputs: 'python'

Avoiding Syntax Errors:


Correct string handling is crucial to avoid syntax errors. Pay attention to quoting conventions, especially when
including apostrophes within single-quoted strings:

message = "One of Python's strengths is its diverse community."


print(message)

Class Exercises: Understanding Strings in Python


1. Personal Message:
Create a variable to represent a person's name.
Print a message to that person, such as "Hello [Name], would you like to learn some Python
today?"
2. Name Cases:
Use a variable to represent a person's name.
Print the person's name in lowercase, uppercase, and title case.
3. Famous Quote:
Page 8 of 17
Limkokwing_University
Find a quote from a famous person you admire.
Print the quote and the name of its author.
The output should look like: "Albert Einstein once said, 'A person who never made a mistake
never tried anything new.'"
4. Famous Quote 2:
Repeat Exercise 3, but represent the famous person's name using a variable called
famous_person .
Compose your message and represent it with a new variable called message .
Print your message.
5. Stripping Names:
Use a variable to represent a person's name.
Include some whitespace characters at the beginning and end of the name.
Print the name once, so the whitespace around the name is displayed.
Then print the name using each of the three stripping functions: lstrip() , rstrip() , and
strip() .
6. File Extensions:
Python has a removesuffix() method that works like removeprefix() .
Assign the value 'python_notes.txt' to a variable called filename .
Use the removesuffix() method to display the filename without the file extension.

Understanding Numbers in Python


In programming, numbers play a fundamental role in various tasks, from simple calculations to complex
mathematical operations. Python, being a versatile language, handles numbers in different ways, offering
flexibility and precision. Let's break down the concepts of integers, floats, and operations in a way that's easy for
students to grasp:
Integers:
Integers are whole numbers without any decimal point.
They are used for tasks like counting items, representing scores, or indexing elements in a list.
Python allows basic arithmetic operations such as addition (+), subtraction (-), multiplication (*), and
division (/) with integers.
For example:

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

Operations and Order of Operations:


Python follows the standard order of operations (PEMDAS/BODMAS) when evaluating expressions,
allowing the use of parentheses to control the order of evaluation.
Example:
# Order of operations
result = 2 + 3 * 4 # Result: 14
adjusted_result = (2 + 3) * 4 # Result: 20

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.

Basic Mathematical Calculations Using Python


1. Simple Interest:
Problem: Calculate the simple interest earned on a principal amount over a given period of time, given the
principal amount, the rate of interest, and the time in years.
Formula: Simple Interest = (Principal Amount × Interest Rate × Time) / 100
Example:

# 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")

3. Kinematic Equation (Distance):


Problem: Calculate the distance travelled by an object given its initial velocity, acceleration, and time.
Formula: Distance = Initial Velocity × Time + (0.5 × Acceleration × Time^2)
Example:

# 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")

4. Kinematic Equation (Final Velocity):


Problem: Calculate the final velocity of an object given its initial velocity, acceleration, and time.
Formula: Final Velocity = Initial Velocity + (Acceleration × Time)
Example:

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")

Class Work ( 20 munites)


6. Speed Calculation:
Problem: Calculate the speed of an object given the distance travelled and the time taken.
Formula: Speed = Distance / Time
7. Density Calculation:
Problem: Calculate the density of a substance given its mass and volume.
Formula: Density = Mass / Volume
8. Acceleration Calculation:
Problem: Calculate the acceleration of an object given the change in velocity and the time taken.
Formula: Acceleration = (Final Velocity - Initial Velocity) / Time
9. Power Calculation:
Problem: Calculate the power generated or consumed by a system given the work done and the time taken.
Formula: Power = Work Done / Time
Page 13 of 17
Limkokwing_University
10. Projectile Motion (Range):
Problem: Calculate the horizontal distance travelled by a projectile launched at an angle given its initial velocity
and the angle of launch.
Formula: Range = (Initial Velocity^2 * sin(2 * Launch Angle)) / Gravity Acceleration

Input() Statements in Python:


In Python, the input() function is used to accept user input from the keyboard. It displays a prompt (optional)
to the user and waits for them to enter data, which is then returned as a string. Let's explore how to use the
input() function with examples.
1. Basic Input:

name = input("Enter your name: ")


print("Hello,", name)

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:

age = int(input("Enter your age: "))


print("Age entered:", age)

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:

values = input("Enter two numbers separated by space: ").split()


num1, num2 = map(int, values)
print("Sum:", num1 + num2)

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.

Format Strings in Python:


Format strings allow you to create dynamic strings by inserting variables or expressions into a string template.
This is achieved using curly braces {} within the string, which are replaced by the corresponding values when
the string is formatted. Let's see how to use format strings with examples.
1. Basic Format String:

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)

3. Comments and Indentation:


Write a Python program that calculates the area of a rectangle.
Include comments to explain the purpose of each section of your code.
Use proper indentation to structure your code.
4. Mathematics in Python:
Write Python code to solve the following mathematical problems:
Calculate the circumference of a circle with radius 5 units (πr^2).
Calculate the square root of 144.
Find the remainder when 15 is divided by 4.
Calculate the area of a triangle with base 6 units and height 8 units (1/2 * base * height).
Convert 80 degrees Fahrenheit to Celsius using the formula: Celsius = (Fahrenheit - 32) *
5/9.
Calculate the volume of a sphere with radius 3 units (4/3 * π * r^3).
5. Input Statements:
Write a Python program that prompts the user to enter their name and age.
Use input() statements to accept user input.
Print a personalized greeting message including the user's name and age.
6. Format Strings:
Declare variables to represent your favorite color, food, and number.
Use format strings (f-strings) to print a sentence describing your favorites, incorporating the
values of your variables.
Submission Guidelines:
Page 16 of 17
Limkokwing_University
Ensure that your Python code is well-documented with appropriate comments.
Verify that your code runs without errors and produces the expected output.
Submit your completed basics_assignment.py file before the deadline specified by your instructor.
Note: If you encounter any difficulties or have questions about the assignment, feel free to seek assistance from
your instructor or peers.

created with the evaluation version of Markdown Monster

Page 17 of 17

You might also like