0% found this document useful (0 votes)
17 views65 pages

Unit 8.1 - Slides

The document provides an introduction to variables, constants, and data types in programming, explaining their definitions and uses. It covers key concepts such as identifiers, input/output management, and control structures, including sequence and selection. Additionally, it includes practice exercises and a challenge to apply the learned concepts in a shopping calculator program.

Uploaded by

m.wix322
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)
17 views65 pages

Unit 8.1 - Slides

The document provides an introduction to variables, constants, and data types in programming, explaining their definitions and uses. It covers key concepts such as identifiers, input/output management, and control structures, including sequence and selection. Additionally, it includes practice exercises and a challenge to apply the learned concepts in a shopping calculator program.

Uploaded by

m.wix322
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/ 65

Introduction to Variables and

Constants
By the end of the lesson, I will understand the
types and uses of variables and constants in
programming.
Computer Science - Unit 8.1 (Lesson 1)
Key Vocabulary
Variable: A storage location in a program that can hold data that may change
during execution.
Constant: A storage location with a fixed value that cannot be changed during
program execution.
Identifier: A name given to a variable or constant to identify it in the code.
Data Type: A classification that specifies what kind of data a variable can hold.
Boolean: A data type that can only hold one of two values: true or false.
What do we already know?

• What is the purpose of using data in a computer program?


• Can you name a programming language you are familiar with?
• What do you think a program needs to do with information?
What are Variables?

Variables are essential in programming as they are used to store


data that can change over time. They act like containers holding
values that can be updated during program execution. For
example, a variable can store a user’s age, and that age can be
adjusted as the user grows older.
Practice

>>Goto CodeSkulpter3

Enter:

name = input('What is your name?\n')


print(f'Hi, {name}.')

>>Now test you code


What are Constants?

Constants are similar to variables, but their values cannot change


during program execution. They are used for fixed values that
should remain the same throughout the program. For example,
the mathematical constant pi is always 3.14, regardless of any
circumstances in the program.

Constants are usually shown as all capitals


Practice
>>Goto CodeSkulpter3
Enter:
name = input('What is your name?\n')
MYNAME = "Adam"
print(f'Hi, {name}, my name is {MYNAME}.')

>>Now test you code


Understanding Identifiers
# Integers
Identifiers are names given to age = 25
quantity = 10
variables and constants. They # Floats
should be meaningful so that price = 9.99
temperature = 25.5
anyone reading the code can
understand its purpose. For # Strings
name = "John Doe"
instance, using 'studentAge' as an message = "Hello, world!"

identifier makes it clear that this # Lists


fruits = ["Apple", "Banana", "Cherry"]
variable stores a student's age, numbers = [1-5]
promoting better code readability.
Data Types Explained

Data types specify what kind of data a variable can hold. Common
types include Integer for whole numbers, Real for decimal values,
Character for single letters or symbols, String for sequences of
characters, and Boolean for true or false values. Knowing these
types is essential when programming.
Integer Data Type

An Integer is a data type used to represent whole numbers, both


positive and negative, including zero. For instance, -5, 0, and 42
are all examples of integers. They are used in programming for
counting, indexing, and other calculations that do not require
fractions.
Practice
Enter:
# Define two integers This code provides a clear
a, b = 10, 3 demonstration of integer usage and
arithmetic in Python.
# Perform and print basic operations
print(f"{a} + {b} = {a + b}")
print(f"{a} - {b} = {a - b}")
print(f"{a} * {b} = {a * b}")
print(f"{a} // {b} = {a // b} (floor division)")
print(f"{a} % {b} = {a % b} (remainder)")
# Check and print the type
print(f"The type of a is: {type(a)}")
>>Now test you code
Real Data Type

Real data represents numbers that can have decimal points or


fractions. For example, values like 3.14 and -2.5 fall under this
category. Real numbers are vital when precision is needed in
calculations, such as measurements and financial applications, in
programming tasks.
Practice
Enter: This code defines two real numbers,
performs arithmetic operations on them,
# Define two real numbers (floats) and checks their type. The output will
x, y = 5.7, 2.3 confirm that they are floats.

# Perform and print basic operations


print(f"{x} + {y} = {x + y}")
print(f"{x} - {y} = {x - y}")
print(f"{x} * {y} = {x * y}")
print(f"{x} / {y} = {x / y}") # Standard division returns a float

# Check and print the type


print(f"The type of x is: {type(x)}")
Character Data Type

The Character data type represents a single letter, digit, or symbol.


Examples include 'A', '3', or '%'. Characters are crucial in
programming when you need to work with individual elements,
such as handling letters or special characters within strings of text.
Practice
Enter: This code defines two characters (strings of
length 1 in Python), performs
# Define two characters concatenation, and checks the type. The
output will show they are strings.
char1, char2 = 'A', 'B'
# Print the characters and their concatenation
print(f"Character 1: {char1}")
print(f"Character 2: {char2}")
print(f"Concatenation: {char1 + char2}")
# Check and print the type
print(f"The type of char1 is: {type(char1)}")
String Data Type

A String is a sequence of characters, which can include letters,


numbers, and symbols. For instance, "Hello, World!" is a string.
Strings are widely used in programming to handle text and allow
for the display of messages and user inputs in applications.
Practice
Enter: This code defines two characters (strings of
length 1 in Python), performs
concatenation, and checks the type. The
# Define two characters output will show they are strings.
char1, char2 = 'A', 'B'
# Print the characters and their concatenation
print(f"Character 1: {char1}")
print(f"Character 2: {char2}")
print(f"Concatenation: {char1 + char2}")
# Check and print the type
print(f"The type of char1 is: {type(char1)}")
Boolean Data Type

The Boolean data type holds one of two values: true or false. This
data type is essential in programming for conditional statements,
which help in making decisions. For example, a condition can
check if a user is logged in (true) or logged out (false).
Practice
Enter: This code defines two boolean values,
performs logical operations (AND and OR),
# Define two boolean values and checks their type. The output will
is_true, is_false = True, False confirm they are booleans.

# Print the boolean values and a logical operation


print(f"is_true: {is_true}")
print(f"is_false: {is_false}")
print(f"is_true AND is_false: {is_true and is_false}")
print(f"is_true OR is_false: {is_true or is_false}")
# Check and print the type
print(f"The type of is_true is: {type(is_true)}")
Why Variables and Constants Matter

Variables and constants form the foundation of programming


logic. They allow programmers to create dynamic applications
that can respond to changes and user inputs. Understanding how
to use them effectively is essential for proper coding and
developing efficient software solutions.
Challenge
Challenge: Shopping Calculator
Write a Python program that:

1. Asks for the user's name (string).


2. Asks how much money they have (float).
3. Asks for the cost of an item they want to buy (float).
4. Asks how many of that item they want to buy (integer).
5. Calculates the total cost and determines if they have enough money to buy the
items.
6. Displays the result in a clear message.

Requirements:
● Use float for money-related inputs.
● Use integer for the quantity of items.
● Use a boolean to check if the user has enough money.
Starter Code
# Step 1: Get user's name # Step 5: Determine if they have enough
money (boolean)
name = input("What is your name? ")
can_afford = money >= total_cost

# Step 2: Get user's available money (float)


# Step 6: Display result
money = float(input("How much money do you have? "))
if can_afford:

print(f"Hi {name}, you can afford to buy


# Step 3: Get item cost and quantity (float and integer) {quantity} items. Your total is ${total_cost}.")
item_cost = float(input("Enter the cost of a single item: ")) else:
quantity = int(input("How many items do you want to buy? ")) print(f"Hi {name}, you do not have enough
money. You need ${total_cost - money}
more.")
# Step 4: Calculate total cost

total_cost = item_cost * quantity


Extension Task: Advanced Shopping Calculator

Modify your program to add the following features:

1. Apply a Discount:
○ If the user’s total cost (before applying discounts and tax) is above a certain threshold (e.g.,
$100), apply a 10% discount.
○ Calculate the discounted total if applicable.
2. Add Sales Tax:
○ Apply a sales tax of 5% to the final amount after the discount (if any).
3. Ask if They Want to Buy Another Item:
○ After displaying the result, ask if the user wants to add another item to their shopping list.
○ If the user says yes, repeat the process, updating the total cost each time.
○ If they say no, display the final total, including discounts and tax.
4. Final Output:
○ Display the subtotal, discount (if applied), tax, and the final total cost.
○ Confirm if they can afford the purchase based on the final total.
Questions
1. What is a variable in programming?
2. Why are constants used in programming?
3. What are the different data types mentioned in the lesson?
4. How does an identifier help in programming?
5. Can you explain what a Boolean data type is used for?
Answers
1. A variable is a storage location in a program that can hold data that may
change during execution.
2. Constants are used for fixed values that should remain the same throughout
the program.
3. The different data types include Integer, Real, Character, String, and Boolean.
4. An identifier helps in programming by giving meaningful names to variables
and constants, improving code readability.
5. The Boolean data type is used for conditions in programming, allowing for
true or false values in decision-making.
Understanding Input, Output, and
Control Structures in Programming
By the end of the lesson I will know how to
implement and manage input and output in
programmes, and understand control structures
in programming.
Computer Science - Unit 8.1 (Lesson 1)
Key Vocabulary
Algorithm: A step-by-step procedure or formula for solving a problem.
Input: Data or commands that are entered into a computer system for
processing.
Output: Information that is produced by a computer after processing data.
Control Structure: A programming construct that determines the flow of
control in a program.
Iteration: The process of repeating a set of instructions until a condition is met.
What do we already know?

• What do you think a computer program does?


• Can you name any devices you use to interact with a computer?
• Have you ever written or read code? What was your
experience?
Introduction to Input and Output

Input and output devices play a crucial role in how we interact


with computers. Input devices, like keyboards and mice, allow us
to enter data, while output devices, like monitors and printers,
present that data in a readable format. Understanding these
devices is essential for effective programming.
What Are Input Devices?

Input devices are peripherals that send data to a computer for


processing. Common examples include keyboards, which allow
you to type, and mice, used to navigate on-screen. Each device
serves a unique purpose, capturing different data types to be
processed by the computer.
What Are Output Devices?

Output devices receive processed data from a computer and


convert it into a human-readable form. For example, monitors
display visual information, and printers produce physical copies.
Understanding these devices helps ensure that software presents
information clearly to users.
Control Structures Explained

Control structures are programming elements that determine the


order in which instructions are executed. They include sequence,
selection, and iteration. Understanding how to use these
structures is vital for creating efficient and effective algorithms in
your programs.
Using Sequence in Programming

Sequence refers to the order in which instructions are executed in


a program. In a simple program, each line of code runs one after
the other, creating a linear flow. Mastering sequence is
fundamental for developing logical and coherent algorithms.
Practice
Enter: ● Each step is executed in sequence,
# Step 1: Greet the user starting from greeting the user to
print("Hello! Welcome to the age calculator.") displaying their birth year.
● There are no loops or conditional
# Step 2: Ask for the user's name statements; the code runs each line
name = input("What is your name? ") one by one.

# Step 3: Ask for the user's age


age = int(input("How old are you? "))
# Step 4: Calculate the year they were born
current_year = 2024
birth_year = current_year - age
# Step 5: Display the result
print(f"Nice to meet you, {name}!")
print(f"You were born in the year {birth_year}.")
Introduction to Selection Structures

Selection structures allow programs to make decisions based on


certain conditions. The IF statement is a common example,
enabling the program to execute different actions depending on
whether a condition is true or false. This adds flexibility to your
algorithms.
Practice
Enter:
# Step 1: Ask the user for their age
age = int(input("Please enter your age: "))
# Step 2: Use selection (if-else) to determine if the user is
an adult or a minor
if age >= 18: ● This code uses an if-else statement, which is
print("You are an adult.") a common selection structure.
● If the condition age >= 18 is true, it prints
else: "You are an adult."
print("You are a minor.") ● If the condition is false, it executes the code
under else, printing "You are a minor."
Understanding CASE Statements

CASE statements are a powerful tool in programming which allows


multiple conditions to be evaluated. Instead of using several IF
statements, a CASE statement checks for different values and
executes the corresponding code, making your programs cleaner
and easier to read.
Python doesn’t have a direct CASE or switch statement like some
other programming languages. However, similar functionality can be
achieved using if-elif-else or, in Python 3.10 and above, using
match-case.

<suggested search for images: "case statement in programming">


Practice
Enter:
# Step 1: Ask the user to enter a day of the week
day = input("Enter a day of the week: ").lower()
# Step 2: Use match-case (Python 3.10+) to handle each day
match day:
case "monday":
print("Start of the workweek!") ● match day: checks the value of day.
case "tuesday":
print("Second day, let's keep going!") ● Each case handles a specific day,
case "wednesday": running the corresponding code if it
print("Midweek, halfway there!") matches.
case "thursday":
print("Almost Friday!") ● | allows multiple matches in one case
case "friday": (e.g., "saturday" | "sunday" for the
print("Last day of the workweek!") weekend).
case "saturday" | "sunday":
print("It’s the weekend! Enjoy!") ● case _: acts as a default for
case _: unmatched cases.
print("That's not a valid day.")
https://www.jdoodle.com/python3-programming-online
Combining Input Management with Control Structures

When designing a program, it's essential to manage input


effectively with control structures. For example, you can use an IF
statement to decide how to handle data received from an input
device, making your program more responsive and interactive.
Practice
Enter: ● The program takes
# Get user input and convert to an integer
number = int(input("Enter a number: "))
a number as input.
● It uses
# Control structure to check the number if-elif-else to
if number > 0: check if the
print("The number is positive.") number is positive,
elif number < 0:
print("The number is negative.") negative, or zero
else: and prints the
print("The number is zero.") result accordingly.
Practical Application: Worked Example

Task: Vending Machine Simulation.


1. Input: The user enters a code for a snack (A1 for chips,
B2 for chocolate, C3 for soda).
2. Process: The algorithm checks if the code is valid and if
the item is available.
3. Output: If valid, dispense the item; if not, display an
error.
Practical Application: Worked Example
# Input: User enters item code
code = input("Enter item code (e.g., A1, B2, C3): ").upper()

# Process: Check code and respond with selection


if code == "A1": This example uses
sequence (the order of
print("Dispensing Chips.")
steps) and selection
elif code == "B2": (conditions with
print("Dispensing Chocolate.")
if-elif-else) to respond
based on user input. It’s a
elif code == "C3": collaborative way to practice
print("Dispensing Soda.") building algorithms based on
real-world interactions with
else: input devices.
print("Invalid selection. Please try again.")
Practical Application: Developing Algorithms

In groups, you will develop a simple algorithm


using sequence and selection. Take an input
device's function and create an algorithm that
responds to user actions. This will help solidify
your understanding of how to apply control
structures collaboratively.
Review and Reflection

To conclude, reflect on what you've learned about input, output,


and control structures. Consider how these concepts interact to
create effective programs. Share one new thing you learned today
about either input/output devices or control structures with your
classmates.
Questions
1. What is the main function of input devices?
2. Explain what a control structure does in programming.
3. What does the IF statement do?
4. How does a CASE statement improve code readability?
5. Give an example of how input and control structures can work together in a
program.
Answers
1. To send data to a computer for processing.
2. It determines the order in which instructions are executed.
3. It allows the program to make decisions based on certain conditions.
4. It evaluates multiple conditions in a cleaner way compared to using several IF
statements.
5. Using an IF statement to decide how to process data received from an input
device.
Mastering Iteration and
Maintainability in Programming
By the end of the lesson I will know how to use
different types of loops and create maintainable
code.
Computer Science - Unit 8.1 (Lesson 3)
Key Vocabulary
Iteration: The process of repeating a set of instructions in programming until a
specific condition is met.
Loop: A programming construct that repeats a group of commands for a set
number of times or until a condition is met.
Code Maintainability: The ease with which code can be understood, modified,
and extended by others or by the original developer.
Function: A block of code that performs a specific task and can be reused
throughout a program.
Commenting: Adding notes in the code to explain what certain parts do,
helping others (or your future self) understand it.
What do we already know?

• What do you understand by the term 'loop' in programming?


• Can you name any programming languages you have used and
describe a feature of one?
• Why do you think commenting code is important when writing
programs?
Understanding Iteration

Iteration is a fundamental concept in


programming where a set of
instructions is repeated until a certain
condition is met. It allows for
automating repetitive tasks, making
programs efficient. Understanding how
and when to use iteration can enhance
your coding skills and streamline
software development.
Why Use Loops?

Loops are crucial in programming because they enable developers


to run the same code multiple times without rewriting it. This not
only reduces code duplication but also simplifies modifications
and debugging. Learning different loop types allows for flexible
and powerful programming solutions.
For Loops Explained

A for loop is designed to execute a specific number of times. It


consists of initialization, condition, and increment statements. For
example, in Python, 'for i in range(5):' repeats actions within it five
times. This structure is useful for tasks where the number of
iterations is known beforehand.
Practice
Enter: ● Initialize the Loop: The
# Define the correct password
correct_password = "MrRicketts" program starts by asking
the user for a password.
# Ask the user to enter the password ● Condition Check: If the
password = input("Enter the password: ") entered password is
incorrect, the while loop
# While loop to keep asking until the password is correct
while password != correct_password: continues, asking the
print("Incorrect password. Try again.") user to try again.
password = input("Enter the password: ") ● Exit Condition: When
the user enters the
# Print success message when the password is correct
correct password, the
print("Access granted!")
loop stops, and the
program prints "Access
granted!"
While Loops in Depth

A while loop continues to execute a block of code as long as a


defined condition is true. For instance, 'while x
Practice
Enter:
# Initialize a counter ● Initialize Counter:
count = 1 count starts at 1.
# While loop to print numbers from 1 to 5 ● Condition Check: The
while count <= 5: while loop runs as long
print(f"Count is: {count}") as count is 5 or less.
count += 1 # Increment the counter by 1
● Increment: Each loop
# After the loop ends iteration increases count
print("Loop finished!") by 1.
● Exit: When count
exceeds 5, the loop
stops, and "Loop
finished!" is printed.
Understanding Do-While Loops

A do-while loop is similar to a while loop, but it guarantees at


least one execution of the code block. Its syntax ensures that the
condition is checked after executing the loop content. This is
useful for situations where an action must occur before validation
of a condition.
Practice
Enter: ● Initial Execution: The
# Simulating a do-while loop while True loop
count = 1
ensures the block runs
# Run the loop at least once at least once.
while True: ● Increment and
print(f"Count is: {count}") Check: count
count += 1 # Increment the counter by 1 increments, and an if
condition checks if
# Condition to break out of the loop
if count > 5: count exceeds 5.
break ● Exit with break: If
count > 5, the
# After the loop ends break statement
print("Loop finished!") stops the loop.
Importance of Code Comments

Commenting your code is vital for maintainability. It helps others


(and your future self) to understand the purpose and function of
your code. Well-placed comments can clarify complex logic,
outline steps taken, and describe what each part of the code is
designed to do.
Functions and Procedures Defined

Functions and procedures are reusable code blocks that perform


specific tasks. They help in structuring programs and make them
easier to read and maintain. By creating functions for repeated
tasks, programmers reduce duplication and enhance readability of
the code base.
Maintaining Your Code's Integrity

To maintain code effectively, regularly review and refactor it.


Maintaining clarity through comments, consistent formatting, and
structuring code into functions aids in long-term projects. This
practice ensures that as projects grow, they remain manageable,
scalable, and understandable for future developers.

<suggested search for images: "code maintainability practices">


Collaborative Coding Practices

You are to create a simple program to add from 55 to 65, when it


get to 65 it issues a statement. Add comments to each line of your
code.

Make sure the comments can be understood by some else.


Reviewing Key Concepts

As we finish, remember that iteration and code maintainability


are interlinked. Effective use of loops simplifies tasks, while good
commenting and structuring through functions can make your
code clearer and easier to adapt. Reflect on how these practices
can improve your programming skills.
Questions
1. What is the main purpose of using loops in programming?
2. What is the difference between a 'for' loop and a 'while' loop?
3. Why is it crucial to comment on your code?
4. How does using functions improve code maintainability?
5. What is a 'do-while' loop and how does it function?
Answers
1. The main purpose is to automate repetitive tasks, allowing code to run
multiple times without being rewritten.
2. A 'for' loop runs for a set number of iterations, while a 'while' loop continues
until a specific condition is no longer true.
3. Commenting is important for code maintainability as it helps others
understand the purpose of the code and makes future modifications easier.
4. Functions reduce code duplication and improve readability, making the code
easier to manage and modify.
5. A 'do-while' loop executes the code block at least once before checking the
condition to determine if it should continue.

You might also like