Chapter
8
P
r
o
g
r
a
m
m
i
n
g
Rules for Python variables:
A variable name must start with a letter or the underscore
character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three
different variables)
A variable name cannot be any of the Python keywords.
Comments in Python are the lines in the code that are
ignored by the interpreter during the execution of the
program.
Comments enhance the readability of the code.
Comment can be used to identify functionality or structure the
code-base.
Comment can help understanding unusual or tricky scenarios
handled by the code to prevent accidental removal or changes.
Comments can be used to prevent executing any specific part
of your code, while making changes or testing.
Single-line Comment
In Python, single-line comments are indicated by a hash
sign(#).
Example:
#This is a comment
print("Hello, World!")
Multiline Comments
Python does not really have a syntax for multiline comments.
Since Python will ignore string literals that are not assigned to
a variable, you can add a multiline string (triple quotes) in your
code, and place your comment inside it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
‘‘‘
This is a comment
written in
more than just one line
’’’
As long as the string is not assigned to a variable, Python will
read the code, but then ignore it, and you have made a
multiline comment. We can use triple single quotation marks
or triple double quotation marks
keyword in Python
Python keywords are reserved words that have a special
meaning associated with them and can’t be used for anything
but those specific purposes. Each keyword is designed to
achieve specific functionality.
Python keywords are case-sensitive.
1. All keywords contain only letters (no special symbols)
2. Except for three keywords (True, False, None), all keywords
have lower case letters
Python Data Types:
The basic data types you will need to use for IGCSE Computer
Science are:
1) integer – a positive or negative whole number that can
be used with mathematical operators
e.g. – 23 , -90, 0 etc
2) real – a positive or negative number with a fractional
part. Real numbers can be used with mathematical
operators
e.g. – 23.5 , -90.43, 0.05 etc
3) char – a variable or constant that is a single character
e.g. – “A” , “8”, ‘f’ etc
4) string – a variable or constant that is several characters
in length. Strings vary in length and may even have no
characters (known as an empty string); the characters
can be letters and/or digits and/or any other printable
symbol (If a number is stored as a string then it cannot
be used in calculations.)
e.g. – “Priya” , “Area-of-cylinder” etc
5) Boolean – a variable or constant that can have only two
values TRUE or FALSE.
Taking input in Python
input() function is used to take user input. By default, it
returns the user input in form of a string.
Example:
name = input("Enter your name: ")
Printing Output using print() in Python
print("Hello,", name, "! Welcome!")
Basic concepts When writing the steps required to
solve a problem, the following concepts need to be
used and understood:
» sequence
» selection
» iteration
» counting and totalling
» string handling
» use of operators.
(a) Sequence
The ordering of the steps in an algorithm is very important. An
incorrect order can lead to incorrect results and/or extra steps
that are not required by the task
1: Python Program to Swap Two Variables Using a temporary
variable
# Taking user input
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
# Printing before swap
print(f"Before swap: num1 = {num1} num2 = {num2}")
# Swapping
temp = num1
num1 = num2
num2 = temp
# Printing after swap
print(f"After swap: num1 = {num1} num2 = {num2}")
2: Python Program to convert Celsius to Fahrenheit
# Taking user-input
celsius = float(input("Enter the temperature in celsius: "))
# Converting celsius to fahrenheit
fahrenheit = (celsius * 9/5) + 32
# Printing converted temperature
print(f"{celsius} celsius = {fahrenheit} fahrenheit")
(b) Selection: Conditional statements
Conditional statements in Python are
used to execute certain blocks of code
based on specific conditions. These
statements help control the flow of a
program, making it behave differently
in different situations.
If Conditional Statement in Python
If statement is the simplest form of a
conditional statement. It executes a
block of code if the given condition is
true.
Syntax:
if age >= 18:
print("Eligible to vote.")
If else Conditional Statements in Python
Else allows us to specify a block of code that will execute if the
condition(s) associated with an if or elif statement evaluates to
False.
Else block provides a way to handle all other cases that don't
meet the specified conditions.
Syntax:
if age <= 12:
print("Travel for free.")
else:
print("Pay for ticket.")
elif Statement
elif statement in Python stands for "else if." It allows us to
check multiple conditions , providing a way to execute different
blocks of code based on which condition is true. Using elif
statements makes our code more readable and efficient by
eliminating the need for multiple nested if statements.
Syntax:
Example:
if age <= 12:
print("Child.")
elif age <= 19:
print("Teenager.")
elif age <= 35:
print("Young adult.")
else:
print("Adult.")
Nested if..else Conditional Statements in Python
Nested if..else means an if-else statement inside another if
statement. We can use nested if statements to check
conditions within conditions.
Syntax:
Example:
Sol:
Sol:
Sol:
# Program to accept a number from 1 to 12 and display the
month name and number of days
month_number = int(input("Enter a number from 1 to 12: "))
if month_number == 1:
print("January - 31 days")
elif month_number == 2:
print("February - 28 days") # Assuming non-leap year
elif month_number == 3:
print("March - 31 days")
elif month_number == 4:
print("April - 30 days")
elif month_number == 5:
print("May - 31 days")
elif month_number == 6:
print("June - 30 days")
elif month_number == 7:
print("July - 31 days")
elif month_number == 8:
print("August - 31 days")
elif month_number == 9:
print("September - 30 days")
elif month_number == 10:
print("October - 31 days")
elif month_number == 11:
print("November - 30 days")
elif month_number == 12:
print("December - 31 days")
else:
print("Invalid input! Please enter a number between 1 and
12.")
# Example : Number checker- positive, negative or zero
num = 5
if num > 0:
print("The number is positive.")
else:
if num < 0:
print("The number is negative.")
else:
print("The number is zero.")
# Example : Age classifier
age = int(input(“enter your age”))
if age >= 60:
print("You are a senior citizen.")
else:
if age >= 18:
print("You are an adult.")
else:
print("You are a teenager.")
# Password and Username Checking
username = input("Enter your username: ")
password = input("Enter your password: ")
if username == "admin":
if password == "password":
print("Login successful! Welcome, admin.")
elif password == "12345":
print("Weak password. Please reset your password.")
else:
print("Incorrect password. Please try again.")
else:
if username == "guest":
if password == "guest":
print("Login successful! Welcome, guest.")
else:
print("Incorrect password. Please try again.")
else:
print("Unknown user. Please try again.")
# Using if-else for Authentication
username = input("Enter your username: ")
password = input("Enter your password: ")
if username == "admin":
if password == "password123":
print("Login successful.")
else:
print("Invalid password.")
else:
print("Invalid username.")
Iteration : repeating a certain block of code:
1. Count-controlled loops : for loop
2. Condition-controlled loop : while loop