0% found this document useful (0 votes)
3 views8 pages

Python Note

The document provides a comprehensive overview of Python programming concepts covered over four days, including basic syntax, data types, control flow, and the use of modules. Key topics include string manipulation, variable naming rules, conditional statements, and randomization techniques. Exercises and projects such as a BMI calculator and a tip calculator are included to reinforce learning.

Uploaded by

emily900johnson
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)
3 views8 pages

Python Note

The document provides a comprehensive overview of Python programming concepts covered over four days, including basic syntax, data types, control flow, and the use of modules. Key topics include string manipulation, variable naming rules, conditional statements, and randomization techniques. Exercises and projects such as a BMI calculator and a tip calculator are included to reinforce learning.

Uploaded by

emily900johnson
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

Python Programming Notes — Days 1–4

DAY 1 — PYTHON PROGRAMMING

Programming is telling the computer what to do and to follow our command.

print() Function
print("Hello world")

• print — the print function


• " " — quotation marks (also called double quotes). Shows the beginning and end of a string.
• "Hello world" — this is a string

If any syntax — either ( ) or " " — is wrong, Python shows an error.


• ( ) — parenthesis

If there is an error in your code and you don't understand it, use Google or an AI chatbot like ChatGPT,
Claude, or Gemini.

String Manipulation & Code Intelligence


PyCharm is really good for syntax highlighting.

Printing Practice Challenge: Print 5/6 lines of statement.

You can print 5/6 lines using a single print statement by using "\n" (backslash n = newline):
print("Line 1\nLine 2\nLine 3\nLine 4\nLine 5")

String Concatenation
Combining different strings so they will be joined into one.
print("Hello" + " Don Khalifa")

The Python Input Function


input("What's your name?")

The text inside is a prompt — what you want to show the user.

If you want to print something like "Hello (user name)", use the input function inside a print with string
concatenation:
print("Hello " + input("What's your name?"))

Exercise: Add an exclamation mark to the end using string concatenation:


print("Hello " + input("What's your name?") + "!")
Thonny IDE
If you don't want a particular line of code to run/execute, use # (pound sign / hashtag) to comment it out.
• Shortcut: Ctrl + / (forward slash)

Python Variables
A variable is a concept in programming that allows us to give a label to a piece of data, so we can refer to
or reference that data using the chosen variable name.
name = input("What's your name?")

Analogy: Like storing someone's phone number under their name in your contacts.
Don = 08164421930
Vicki = 08088112256

Exercise: Check the length of the user input — how many characters are in the name they type. Use the
len() function:
print(len(input("What's your name?")))

Better practice — split everything into variables:


username = input("What's your name?")
length = len(username)
print(length)

Rules in Variable Naming


• Make sure variable names are descriptive
• Don't use spaces between words
• Don't start with numbers
• Don't use special words like print or input
• Choose simple words
• Check company guidelines

DAY 2 — DATA TYPES

Strings (str)
Any character within double quotes. Also known as "TEXT".
e.g. "Hello", "123", "Data" — string of characters strung together.

A string consists of characters. We can pull out each character individually using its index:
print("Hello"[0]) # outputs H

In Python, we start counting from 0.

We can also count negatively (from the end):


print("Hello"[-1]) # outputs o (negative indices)
Integer (int)
Whole numbers. e.g. 123, 45, -3, -2, 100

Floats (float)
Decimal numbers. e.g. 3.14159, 55.0, 7.0

Booleans (bool)
Only has 2 possible values: True or False.

Type Error / Checking & Conversion


The len() function doesn't like working with integers.
len(12345) # → TYPE ERROR. Try it!

Type Conversion
You can check the data type of any value or variable in Python using the type() function:
print(type("abc"))

Mathematical Operations
Basic Operators (PEMDAS order of precedence):
• P — Parentheses ( )
• E — Exponents **
• M — Multiply * → equal importance with divide
• D — Divide /
• A — Addition + → equal importance with subtraction
• S — Subtraction -

• ** — raises a number to a power of


• // — floor division (removes decimal places)

In calculation, the operation most to the left is evaluated first among equal-precedence operators.

print(3 * 3 + 3 / 3 - 3) # calculate this


# Change the code so it outputs 3:
print(3 / 3 * 3 + 3 - 3)

Challenge: BMI Calculator


Used to check if someone is underweight or overweight.
BMI = Weight / Height2
Number Manipulation
Flooring a number: Remove all decimal places using int(), which converts a float to an integer.

Rounding a number: Use Python's round() function. Anything over .5 rounds up, below rounds down.
round(3.7384) # → 4
round(3.14159) # → 3
round(3.14159, 2) # → 3.14

Assignment Operator
+= adds the number on the right to the original value of the variable on the left and assigns the new value.
score = 0
score += 1
print(score) # outputs 1

Other assignment operators: += -= *= /=

F-String
Used to mix strings and different data types cleanly.
age = 12
print(f"I am {age} years old")

Project: Tip Calculator


print("Welcome to the tip calculator")
bill = float(input("What was the total bill? "))
tip = int(input("What percentage tip? 10, 12, 15: "))
people = int(input("How many people splitting the bill? "))

percent_tip = (bill / 100) * tip


total_bill = bill + percent_tip
each_person = total_bill / people
final_total = round(each_person, 2)

print(f"Each person should pay: ${final_total}")

DAY 3 — CONDITIONAL STATEMENTS, LOGICAL OPERATORS, CODE


BLOCKS & SCOPE

Control Flow with If/Else


if condition:
do this
else:
do this
Swimming pool analogy:
water_level = 500
if water_level > 500:
print('Stop pumping')
else:
print('Continue')

The else keyword defines a block of code that runs when the if condition is False.

Common Flowchart Shapes


• Oval — START / STOP
• Trapezium — INPUT / OUTPUT
• Rectangle — PROCESSING (arithmetic, data assignment, etc.)
• Diamond — DECISION (checks True / False)
• Circle — CONNECTOR
• Arrows — FLOW LINES (direction of flow)

Python Indentation
Indentation is simply spaces or tabs at the beginning of a line of code.
• It tells Python which statements belong together
• It shows where a block starts and ends
• Standard indentation = 4 spaces

print("Welcome to Khalifa Swimming Pool")


height = int(input("What is your height in cm? "))

if height > 120:


print("You can swim")
else:
print("Sorry, you have to grow taller")

# To include people exactly 120cm:


if height >= 120:

Comparison Operators
• > — Greater than
• < — Less than
• >= — Greater than or equal to
• <= — Less than or equal to
• == — Equal to
• != — Not equal to

= assigns a value to a variable. == checks if two values are equal.


Modulo Operator (%)
Gives you the remainder of a division.
6 % 2 = 0
6 % 4 = 2
6 % 5 = 1

Ticket: What is 10 % 3?

Ticket Exercise: Check if a number is odd or even:


num = int(input("Put in a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")

Nested If and Elif Statement


if condition:
if another condition:
do this
else:
do this
else:
do this

For the inner block to run, both the outer and inner conditions must be True.

Swimming pool ticket pricing example: Height > 120cm → Can Swim → Under 18: ■3,000 / Over 18:
■5,000

We can use multiple elif statements between if and else.

BMI Calculator with if/elif/else:


height = int(input("How tall are you? (m) "))
weight = float(input("What is your weight? (kg) "))
bmi = weight / height**2

if bmi < 18.5:


print("Underweight")
elif bmi < 25:
print("Normal weight")
else:
print("Overweight")

Multiple if vs if/elif/else
• With if/elif/else — only ONE branch executes
• With multiple separate if statements — ALL True conditions execute

Logical Operators
• AND — Both conditions must be True
• OR — Only one condition needs to be True
• NOT — The condition must be False

a = 12
print(a > 10 and a < 13) # True
print(a > 15 and a < 13) # False

AND checks both conditions. If either is False, the whole thing is False.

DAY 4 — RANDOMISATION AND PYTHON LISTS

Random Module
In real life, not everything follows a fixed pattern — some outcomes are unpredictable. Programming also
needs this in areas like games, simulations, and testing. Python's random module helps by generating
random numbers and selecting random choices.

To use it, import the module:


import random

# Generate a random integer between 1 and 10 (inclusive):


random_int = [Link](1, 10)
print(random_int)

What is a Module?
A module is a file in Python that contains ready-made code. It helps us do things easily without writing
everything from scratch.

Analogy: A module is like a toolbox — it contains useful tools (code) we can use anytime:
• Hammer → build/fix things | In Python: math module → calculation tools
• Screwdriver → tighten screws | In Python: random module → randomness tools

Instead of building tools yourself, you just pick what you need from the toolbox.

How to use: First import the module: import random

Creating Your Own Module


• Open PyCharm → New Project → Choose location → Create
• Right-click project folder → New → Python File → Name it e.g. my_module.py
• Write anything inside, e.g. my_fav_num = 3.1415
• Create another file called [Link] to use the module

# In [Link]:
import my_module
print(my_module.my_fav_num) # Output: 3.1415
• A module is just a Python file
• You write functions/variables inside it
• Then you reuse them in another file

Generate Random Floating Point Number


random_num = [Link]() # float between 0 and 1

random_num = [Link]() * 10 # float from 0 to 10 (not including 10)


print(random_num)

Some functions don't take any input, but still need parentheses so they can carry out their action.

Ticket: Heads or Tails


Create a coin flip program using what you've learned about randomisation. It should randomly print
"Heads" or "Tails" every time it runs.

You might also like