0% found this document useful (0 votes)
2 views25 pages

3. Python Programming Level 1 and 2

The document is a programming guide that covers fundamental concepts such as variables, data types, arithmetic operators, conditional statements, and error handling in Python. It includes examples, exercises, and explanations to help learners understand programming basics and improve their coding skills. The guide emphasizes the importance of syntax and logic in programming, providing a systematic approach to debugging and error identification.

Uploaded by

123vivaan2011
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)
2 views25 pages

3. Python Programming Level 1 and 2

The document is a programming guide that covers fundamental concepts such as variables, data types, arithmetic operators, conditional statements, and error handling in Python. It includes examples, exercises, and explanations to help learners understand programming basics and improve their coding skills. The guide emphasizes the importance of syntax and logic in programming, providing a systematic approach to debugging and error identification.

Uploaded by

123vivaan2011
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/ 25

1

Programming
(LEVEL 1)
2

Table of Contents
Test Your Skills ........................................................................................................................ 3
Questions: ............................................................................................................................ 3
Let’s Start Programming.......................................................................................................... 4
Variables.................................................................................................................................. 5
Arithmetic Operators .............................................................................................................. 6
Test Yourself ........................................................................................................................ 7
Data Types............................................................................................................................... 7
Syntax Errors ......................................................................................................................... 10
Logic Error ............................................................................................................................. 10
Systematic Approach to find errors ................................................................................... 11
Conditional Statements......................................................................................................... 14
Color Card Game ................................................................................................................ 14
Reflection ........................................................................................................................... 14
Boolean operators ............................................................................................................. 15
Loops ..................................................................................................................................... 19
The while Loop ................................................................................................................... 19
The break Statement ......................................................................................................... 19
The continue Statement .................................................................................................... 20
The else Statement ............................................................................................................ 20
Program Libraries .................................................................................................................. 21
random library. .................................................................................................................. 21
Data types ( Integer, Real and Boolean ) ............................................................................... 23
3

Test Your Skills


print("Hello, world!")
name = input("What is your name? ")
print(“hello”, name)

Refer File Name “1.Hello world”

Explanation:

1. Greeting Message:
print("Hello, world!")

This prints a simple greeting message.

2. User Input:
name = input("What is your name? ")

The input function displays the prompt message and waits for the user to
enter their name. The input is stored in the name variable.

3. Personalized Greeting:
print("Hello”, name)

Questions:

• What does the program do?


Answer: It outputs ‘Hello world!’, asks a user to enter their name,
then says ‘Hello and name’
• What do you think 'print' means?
Answer: It is the instruction to output what is in the brackets
• What do you think 'input' means?
4

Answer: It is the instruction to wait for the text a user enters and
to then make use of this
• Why is some text in speech marks and some not?
Answer: Speech marks indicate that the exact text will be used
when the program is run. No speech marks mean that the content
of that memory space is used
• What is the purpose of 'name'?
Answer: This is a variable to store the name the user inputs.

What is the difference between this program and a Scratch (or block-based) program?
Answer: There are no blocks, you have type everything, you cannot fit pieces of code
together, you have to decide what fits where. There is no list of code that you can
choose from, there is no visual display for images or text to be displayed.

Let’s Start Programming


print("This is my first message")
print("This is my second message")
print("This is my last message")

Note:. If you discover errors, or if your program does not run, check with your pair and
carefully compare their program with the program you are displaying.

Experiment by:

• changing the text that is output


• removing one or more lines of output
• adding more lines of output.
create a list of what you now know about outputting in Python. each pair to
share one item from their lists
• there is a ‘print’ command word
5

• ‘print’ is written in lowercase


• the output message is in speech marks
• after ‘print’ there is an open bracket
• at the end of the message there is a closed bracket
• each print statement is on a new line

Variables
• A variable is used to store data
• The value in the variable can change
• A variable has a name (identifier)
• You can access data from a variable

Storing data in a variable, for example:

MyName = "Jamelia"
MyAge = 12

In this case, the variables are called ‘MyName’ and ‘MyAge’. Taking the ‘MyName’ variable
as an example, when the program is run this time, the data stored will be “Jamelia” but that
this could change the next time the program is run.
Note: there are some reserved words that cannot be used. These are words used by the
program, for example we cannot name a variable ‘print’, because this is a command word in
Python.

Here is a program that includes data stored in variables, and outputs them, for example:

MyName = "Fabrizio"
MyAge = 13
print("Hello", MyName)
print("You are", MyAge, "years old")
6

In Pairs explore the above code and answer the following questions. Are you ready ?
• What is the name of the two variables?
Answer: MyName and MyAge
• What data is stored in MyName?
Answer: "Fabrizio"
• Change the program so the name stored is "Wasim" instead. What change did you
make?
Answer: Deleted “Fabrizio” and wrote “Wasim”
• How many output statements are in the program?
Answer: Two
• What happens if you remove the speech marks, " ", from a print statement?
Answer: An error occurs.
• What is the purpose of the comma in the print statements?
Answer: It joins text with a variable so that in can be output
• Change the program so that “Wasim” is actually “15”. What change did you make?
Answer: We removed ‘13’ and put ‘15’.
• Add an extra variable to store Wasim's favourite colour. Output this colour in a
message, for example “Your favourite colour is purple”. What changes did you make?
Answer: A new variable was created and given a name, for example MyColour.
“purple” was stored in this variable. A new print statement was added with the text
"Your favourite colour is" and then a comma, and then the variable name.
• What happens if you change “Wasim” to “wasim”?
Answer: “wasim” is output

Arithmetic Operators
calculate the answers:
• 10 + 3
• 20 / 4
• 15 - 9
• 5*5
what do each mathematical operator mean.
7

for example:

Number1 = 10
Number2 = 20
Result = Number1 + Number2
print(Result)

Test Yourself
• change the operator to subtraction
• change the operator to division
• change the operator to multiplication
• add the two values, then multiply by 2
• create a third variable and store the number 30 in it
• add all three values together and output the result
• subtract two values from a third value and output the result
• multiply all three values together and output the result
• add the three values then multiply the total by 10

What is the difference between (1 + 2) * 2 and 1 + (2 * 2)? . From the output we can see
that the Mathematical BODMAS rule is applied here.

First = 1
Second = 2
Third = 2
Final = (First + Second) * Third
print(Final)

Change the position of the brackets in the statement and to identify the difference
between the values output.

Data Types
Integer, Real and String.
programs can store data of different types. Integer, Real and String
For example:
8

• 10
• blue
• 205
• 0.3
• horse
Group the displayed data according to Integer, Real and String.
How would you describe these groups?
One of the groups contains words, one contains whole numbers, one contains decimal
numbers.
These three groups are String (text), Integer (whole numbers) and Real (decimal numbers).
From the above data can you vote whether they are String, Integer or Real and the reasons
for your choice.
when writing programs, a programmer usually has to state what type of data a variable is
going to store. For example, if a variable is going to store a name, then it should be stated
in the program it is going to be a string. It will however be important for learners to
understand that Python does not require this, however. Python will allow different data
types to override a variable.
strings are surrounded by speech marks, that tell the computer to output the information
between the speech marks
only. For example:
• print(Value1) will output the content of Value1
• print("Value1") will output the word "Value1"

write the following code and then run it to see what it does: (file name: datatypes)
Number = 10 * "Bob"
print(Number)
Result = "a" + "b"
print(Result)
Result = 10 - 20.5
print(Result)
Result = 0.3 + 0.8
print(Result)
Result = 0.3 + "hello"
print(Result)
Result = 3 / "hi"
print(Result)
9

Result = 3 * "1"
print(Result)
Result = 3 * 1
print (Result)

output
1. Bob will output 10 times
2. "ab" is output
3. -10.5 is output
4. 1.1 is output
5. Error
6. Error
7. 111
8. 3

Reflection
• you cannot divide an Integer by a String
• you cannot add a string to an Integer or Real
• you can add, subtract, multiply and divide Integer and Real numbers
• you can multiply an Integer by a String and output that String a number of times
• when you add two Strings they join together.

When a user enters a value in Python, it automatically stores as a String. Therefore, if you
enter a number, it will not be stored as a number, unless you tell Python to do this.
store the data input as an Integer. For example:
Number = int(input("Enter a number"))
'int' stands for Integer, and the data in the brackets will be stored as an Integer if the data is
intended to be a number rather than a word.

Explain that a Real number in Python is known as a ‘float’ and give an example:
Number = float(input("Enter a number"))
Any value entered will be stored as a real number.

In Python, the command for converting to a String is ‘str’, for example:


10

Number = str(input("Enter a number"))


Any value entered will be stored as a String.

Syntax Errors
Find the syntax errors from the code below.

Animal = INPUT("Enter the name of an animal")


Colour = input(Enter a colour)
output("I've never seen a" Colour Animal)

Run the program and identify the errors.


• the first ‘INPUT’ should be lower case
• the second input should have speech marks, “ “, around the Enter a colour
• the comand word in the final line should be print rather than output
• in the ‘print’ command, the output text and the two variables need to be separated
with a comma, ‘,’.
• The correct program should be:
• Animal = input("Enter the name of an animal")
• Colour = input("Enter a colour")
• print("I've never seen a", Colour, Animal)

Logic Error
When logic error is present, the program will run but it does not do what it is supposed to.
The following program should add together the two numbers that are input, and output the
total.

Number1 = input("Enter a number")


Number2 = input("Enter another number")
Total = Number1 + Number1
print(Total)

Find the error?


11

The calculation adds Number1 to Number 1 and not to Number 2.


This error is an example of a logic error. Write down the term ‘logic error’. When a logic
error is present, the program will run but it does not do what it is supposed to.

Systematic Approach to find errors


• Look at each line of code, one at a time
• Check the words used were correct
• Check that each mathematical symbol, or operator, was correct
• Check that the correct variables are used
• Check that speech marks were used where needed.
• It is important to note that using a systematic approach, such as checking each line
one-by-one, helps to make sure all parts of the program are checked. This is different
from skipping to a mathematical operation and ignoring all other areas, because the
error can occur anywhere in the program, and there might be several errors.
Find the errors in the following program
Create a checklist of errors that you identify during this activity, including the process or
processes that they used for finding them. Add this to your programming guide and add
further errors in the future. The checklist should include the types of error that can occur
and examples of what they look like.

Number = input("Enter the times table you want to view")


Value = Number * 1
print (Number, " * 1 =", Value)
Value = Number * 2
print (Number, " * 1 =", Value)
Value = Number * 3
print (Number, " * 1 =" Value)
Value = Number * 4
print (Number, " * 1 =", Value)
Value = Number * 5
print (Number, " * 1 =", Value)
Value = Number * 6
print (Number, " * 1 =", Value)
Value = Number * 7
print (Number, " * 1 =", Value)
Value = Number * 8
print (Number, " * 1 =", Value)
12

Value == Number * 9
print (Number, " * 1 =", Value
Value = Number * 10
print (Number, " * 1 =", Value)
Value = Number * 11
print (Number, " * 1 =", Value)
Value = Number + 20
print (Number, " * 1 =", Value)
13

Programming
(LEVEL 2)
14

Conditional Statements
what is meant by conditional, or selection, statement
What are the three component parts of a conditional statement?
Answer: the condition; the code to run if true; the code to run if not true
What is a conditional statement?
Answer: A question that has a true or false answer.
What are the conditional operators that we can use?
Answer: <, >, =, !=, <=, >=

Color Card Game


If you are holding a blue card hair AND your height is more than 1.5 metres, stand up.
If you are NOT holding an orange card, sit on the floor.
If you are holding a blue card OR you are holding an orange card, clap your hands.
If you are holding an orange card OR your height is more than 1 metre, jump.

Reflection:
• in the first statement, both conditions must be true for learners to stand up
• in the NOT statement, it reverses the condition, so only those who are holding a blue
card sit on the floor
• in the first OR statement, either condition being true will result in a clap
• in the second OR statement, anyone holding an orange card or is taller than 1 metre
would jump.

number = 10
if number == 10:
print("Yes")
else:
print("No")
15

first = 20
if first < 20:
print("Less than 20")
else:
print("20 or more")

Note the indentation in print statements after the if and else condition.

Boolean operators (AND, OR, NOT)

first = 10
second = 20
if first < 20 and second < 20:
print("Both less than 20")

if first < 20 or second < 20:


print("At least one is less than 20")

value = True
if not value:
print("False")
else:
print("True")

Introduce the Boolean operators (AND, OR, NOT) in the same way, for example:
first = 10
second = 20
if first < 20 and second < 20:
16

print("Both less than 20")

if first < 20 or second < 20:


print("At least one is less than 20")

value = True
if not value:
print("False")
else:
print("True")

More examples to work with using Boolean operators with IF ELSE statement.
1. Take a number as input from the user and check whether it is greater than 10.
Repeat by checking if it is less than 10.

numberInput = int(input("Enter a number"))


if numberInput > 10:
print("Greater than 10")
else:
print("Less than or equal to 10")
another version:
numberInput = int(input("Enter a number"))
if numberInput > 10:
print("Greater than 10")
else:
if numberInput == 10:
print("equal to 10")
else:
if numberInput < 10:
print("Less than 10")
17

2. Ask the user a question and output whether their answer was correct.

answer = int(input("What is 2 * 2?"))


if answer == 4:
print("Correct")
else:
print("Incorrect")

3. Ask the user to guess what number is stored in the computer. Output ‘Correct’ for a
correct guess or ‘Incorrect’ for an incorrect guess.

number = 100
guess = int(input("Guess what number I am thinking of"))
if guess == 100:
print("Correct")
else:
print("Incorrect")

4. Ask the user to enter a number between 1 and 10 and output whether they did this
successfully or not.

numberInput = int(input("Enter a number between 1 and


10"))
if numberInput >= 1 and numberInput <= 10:
print("Success")
else:
print("Incorrect")

5. Take two numbers as input from the user and output the number which is larger.

first = int(input("Enter a number"))


second = int(input("Enter a number"))
18

if first > second:


print(first)
else:
print(second)

6. Ask the user a ‘yes’ or ‘no’ question and check if they answered yes with different
combinations of upper- and lower-case letters, such as ‘yes’, ‘Yes’ and ‘YES’.

answer = input("Is a dolphin a mammal?")


if answer == "yes" or answer == "YES" or answer == "Yes":
print("Correct")
else:
print("Incorrect")
method 2
myquestion = input("Is a dolphin a mammal?")
answer1 = myquestion.lower()

if answer1 == "yes":
print("Correct")
else:
print("Incorrect")

7. Ask the user to enter two test results. If either test result is greater than 90, tell them
that they passed.

result1 = int(input("Enter result 1"))


result2 = int(input("Enter result 2"))
if result1 > 90 or result2 > 90:
print("Pass")
19

8. Ask the user to enter two test results. If both results are greater than 90, tell them
that they passed with distinction.

result1 = int(input("Enter result 1"))


result2 = int(input("Enter result 2"))
if result1 > 90 and result2 > 90:
print("Distinction")

9. Ask the user to answer a question and use NOT to output whether they are incorrect.

answer = int(input("What is 10 * 10?"))


if not(answer == 100):
print("Incorrect")
else:
print("Correct")

Loops
Python has two primitive loop commands:

• while loops
• for loops

The while Loop

With the while loop we can execute a set of statements as long as a condition is true.

i = 1
while i < 6:
print(i)
i += 1

The break Statement


i = 1
while i < 6:
print(i)
20

if i == 3:
break
i += 1
The continue Statement
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)

The else Statement


i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

Here is an example of how to use while loop along with if else conditional statement. Click
here (multiply and guess the answer.py)
import random
go="yes"
while go=="yes":
# Generate a random number between 1 and 10
random_number = random.randint(1, 10)
# Ask the user to guess the number
user_guess = int(input("Guess the number (between 1 and 10): "))

# Check if the guess is correct


if user_guess == random_number:
print("Correct! You guessed the right number.")
else:
print("Wrong! The correct number was:", random_number)

myconfirmation=input("do you want to continue (y/n)")

if myconfirmation=="y":
go="yes"
if myconfirmation=="n":
go="no"
21

Program Libraries
What is the purpose of libraries (Discuss)
Have you ever been to a library?
What does a library allow you to do?
Why do you use a library?
The purpose of a library is to enable readers to borrow and read books for a set period of
time, without paying a fee.
In computing program libraries contain pre-written and tested modules, or self-contained
programs, that can be called by another program. Program libraries save programmers time
in writing and testing newly created functions. Libraries also allow less experienced
programmers to include complex things that they may not yet be able to create for
themselves. Therefore, using libraries in this way can simplify the whole programming
process.

random library.

import random

result = random.randint(3, 9)
print("Random Integer between 3 and 9: ", result)

# Returns a number between 3 and 9 (both included)

The 0 is the smallest number that will be randomly generated, the 100 is the largest
number that will be randomly generated.
Using the library do the following
• generate a random number between 1 and 10
• simulate the roll of a dice (between 1 and 6)

import random

# Example usage
random_number = random.randint(1, 10)
random_choice = random.choice(['apple', 'banana', 'cherry'])
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
22

sampled_list = random.sample(numbers, 3)
uniform_number = random.uniform(1.0, 10.0)

print("Random Integer: ", random_number)


print("Random Choice: ", random_choice)
print("Shuffled List: ", numbers)
print("Sampled List: ", sampled_list)
print("Uniform Random Float: ", uniform_number)

Discussion time:
What is a program library?
Answer: A pre-written and pre-tested programs that can be called in another
program.
How do you use a program library in Python?
Answer: You import the library and then call the functions.
What are some examples of program libraries in Python?
Answer: random and math.
Why are program libraries useful?
Answer: They save time in writing new functions. They are also pre-tested so should
already work.

Guess the Random Number Game


import random
# Generate a random number between 1 and 10
random_number = random.randint(1, 10)

# Ask the user to guess the number


user_guess = int(input("Guess the number (between 1 and
10): "))

# Check if the guess is correct


if user_guess == random_number:
23

print("Correct! You guessed the right number.")


else:
print("Wrong! The correct number was:", random_number)

Data types ( Integer, Real and Boolean )


Let’s start by answering a few questions:
• What is a data type in programming?
Answer: data that is put into categories, so the program knows what is expected
• What data types do you already know?
Answer: Integer, Real and String
• What is the difference between an Integer and a Real number?
Answer: An Integer is a whole number, a Real number is a decimal number
• What is a string?
Answer: one or more characters that can include letters, symbols and numbers that
are not used in mathematics calculations, such as telephone numbers or credit card
numbers.
Boolean data type as ‘true’ or ‘false’ because it can only be one of two values. Let’s
demonstrate this by saying a statement such as
‘10 is less than 11’
and agreeing that this is ‘true’.
What else in programming only has two values?
Answer: binary is 1 or 0

Here table of data to identify the most appropriate data type for each. Here is an example
table, with the expected answers in italics :
24

Boolean data as a ‘flag’,is used to indicate if something has occurred, or is valid or correct. If
the flag is:
• true then it is positive, meaning that it has occurred, it is valid or it is correct
• false it is negative, meaning that it has not occurred, it is not valid or it is incorrect.

Useful Tips:
Learners often identify any numeric-only values as being Integer or Real. However,
numbers that are not used in calculations, such as telephone numbers or credit card
numbers, will always be a string. Explain that if the number is never used in a calculation,
it is a string.

Integer data types cannot start with a 0. Any leading 0s will be removed. Therefore, any
integer that needs to have leading 0s, such as an ID number, will need to be stored as a
string. In this table, if the ID number of the book was stored as an integer, it would be
1182738, which might be the ID number of a different book.

Try these codes and discuss the results


When you compare two values, the expression is evaluated and Python returns the
Boolean answer:
25

print(10 > 9)
print(10 == 9)
print(10 < 9)

When you run a condition in an if statement, Python returns True or False:


Print a message based on whether the condition is True or False:

a = 200
b = 33

if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

The bool() function allows you to evaluate any value, and give you True or False in
return.

Evaluate a string and a number:


print(bool("Hello"))
print(bool(15))

Evaluate two variables:


x = "Hello"
y = 15
print(bool(x))
print(bool(y))

You might also like