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

Introduction To Python Computer Science + AI

Uploaded by

alayna140693
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 views17 pages

Introduction To Python Computer Science + AI

Uploaded by

alayna140693
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

08 Introduction to Python

Learning Outcomes
Learners will be able to:

learn Python basics: syntax, structure, and simple programs.


use print() and input() for output/input.
work with variables, data types, and naming rules.
apply operators with precedence.
write commented code and simple programs.

Communication

Comic Play
Let’s begin by printing ‘Hello,
How do I start coding World!’, it’s the first step in Python.
in Python, Guru?

Great job, Kabir! You’re


This feels like magic! now a Python coder.

Thanks, didi!
Coding is fun!

83

PW_Computer_G6_Ch08.indd 83 29-11-2024 16:14:02


Think Again: Find the error!
Problem-Solving
1. The sprite should move 10 steps before saying “Welcome!” for 2 seconds.

2. The sprite should change the colour effect before broadcasting “Jump”.

Programming is giving instructions to a computer to perform specific tasks. Imagine you are
writing a list of steps for your friend to follow—like how to bake a cake or solve a puzzle.
Similarly, computers need instructions, called programs, to know what to do.
Computers follow instructions exactly as they are written. A computer cannot think for itself,
Syntax refers to the rules governing the structure and format of a specific programming
so it needs clear and precise directions. When a programmer writes a program, they tell the
language.
computer how to complete a task step by step.
It dictates how statements, commands, and instructions are written and organised in a
way that the computer can understand and execute them.
Input
Computer
Unlike some other languages (C++, Java, etc.) that uses Output
(Instruction + Data)
complicated syntax, Python uses simple and clear
print(“Hello,World”)
commands that are easy to understand. This makes it a
fantastic starting point for anyone new to programming.
Direct Perception
PYTHON 
Tech Fact
Python is a programming language that is easy to learn and read, making it an
FACTS

ideal choice for beginners. The simplicity of Python makes it perfect for those
Python
just starting their is one of the most
programming popular
journey. programming
Python was languages
createdininthe world.
the lateIt's widelyby
1980s
used by developers and is considered a great language for learning programming.
Dutch programmer Guido van Rossum.
The first version, Python
Python's role0.9.0, wasfields
in various released in February 1991. Over the years,
Python has undergone
A computerseveral
program major updates,
is a sequence or set with Pythonin3abeing
of instructions a significant
programming languagemilestone.
Python is not just
for a a language
computer for making
to execute. Python issmall
not justprograms;
a language foritmaking
is used in programs;
small lots of important
it is and
exciting areas:used in lots of important and exciting areas: Application
Web Software Database Game
Development Development Access Development
Tech Adventure

</>

Desktop Education Network 3D


Applications Programing Graphics

84 • Web Development: Think of websites you visit daily. Many of them are built using
Python. Python is like paint and brushes for artists creating the digital world.
• Data Science: Imagine being a detective, solving mysteries hidden in numbers
and data. Python helps experts analyse information and find important patterns.
PW_Computer_G6_Ch08.indd 84
Example: Prediction of malfunctions in a car based on previous car data, and image 29-11-2024 16:14:03
Cyber Tip
Python stands in second place in the list of most used languages. Testimony

Understanding Syntax
Syntax refers to the set of rules that govern how code is written and structured. It dictates
how statements, commands, and instructions are organised so that the computer can
interpret and execute them correctly.
Unlike programming languages such as C++ or Java, which have more complex syntax,
Python is known for its simple, readable commands. This ease of understanding makes
Python a fantastic starting point for beginners.

Binary Bytes
Analogy
Syntax: Refers to the rules or structure of how code is written (like the grammar
of programming languages).
Semantics: Refers to the meaning or function of the code when it runs (what the code
actually does).

Key Features of Python


Python offers several features that make it stand out:

Community Interactive Large Standard Cross-Platform


Readability Versatility
and Support Mode Library Compatibility

85

PW_Computer_G6_Ch08.indd 85 29-11-2024 16:14:04


Readability: Python’s syntax is simple and easy to understand, making it accessible for
1 
beginners.
2 Versatility: Python is used in various fields, from web development to scientific research,
allowing the exploration of diverse applications.
3 Community and Support: Python’s large community offers tutorials, forums, and
resources for learning.
4 Interactive Mode: Users can quickly test code, making learning and experimentation
faster.
5 Large Standard Library: Python provides built-in functions and modules, saving time on
common tasks.
6 Cross-Platform Compatibility: Python code runs across different operating systems with
minimal changes.

Tech Insight
Testimony
Python was named after the British comedy series “Monty Python’s Flying Circus”,
not the snake! The language’s creator, Guido van Rossum, was a fan of the series.

INSTALLING PYTHON
Follow the below steps to download and install the Python software:
1 Visit the URL [Link]/downloads using browser.

Click on Download
Python 3.13.0
button.
2
Open the
download file.
3

Click on Install
Now and follow
the steps. 5
Tech Adventure

Tick the Add


Python 3.10 to
PATH checkbox.
4 3

86

PW_Computer_G6_Ch08.indd 86 29-11-2024 16:14:04


After a few moments, Python will finish installing on your computer and prompt you to
choose whether to disable the path length limit. This modifies your system’s configuration,
allowing Python and other programs to bypass the 260-character “MAX PATH” restriction.

GETTING STARTED WITH PYTHON  Direct Perception

To start coding in Python, you need to install Python on your computer. Once installed, you can
use a Python Integrated Development Environment (IDE), like IDLE, which comes with Python.

Working in Interactive Mode


Interactive Mode is like having a conversation
with Python. You type a command, and Python
immediately gives you the result. This mode is great
for quickly trying out small pieces of code.

Working in Script Mode


In Script Mode, you write your Python code in a file and run it later. This is useful when you want
to write larger programs or save your work for future use. Here’s how to work in Script Mode:
1 Open Python IDLE: Launch Python IDLE from your applications or start menu.
Switch to Script Mode: In the Python IDLE Interactive Mode window, click on File in the
2 
menu bar, then select New File. This opens the Script Mode editor.
3 Write Your Code: In the new window (Script Mode editor), type your Python code.
Save the Script: Click File in the Script Mode editor and select Save As..... Enter a file
4 
name with the .py extension (e.g., [Link]) and save it in your desired location.
Run the Script: After saving, press F5 or go to the Run menu and select Run Module. This
5 
executes the code, and the output will appear in the Interactive Mode window.

2
3

87

PW_Computer_G6_Ch08.indd 87 29-11-2024 16:14:05


5

Script Mode is the best way to create longer programs, and you can run the script multiple
times without having to retype your code.

BASIC PYTHON  Direct Perception

Syntax: print(“value”)
Input And Output
The print() Command
The print() statement displays a value or information in the output.

print(“Hello World”) Hello World


print(15) 15
print(“Hello”, “My Friends!”) Hello My Friends!

The input() Function Syntax: input (“message to be shown in input prompt”)


The input() function in Python takes and stores input from the user. We can receive any kind
of information from the users as input. The input() function converts whatever is entered
as input into a string.

name = input(“Enter your name: “) Enter your name: Rahul


print(“Hello, “ + name+”!”) Hello, Rahul!

Code Quest

Write a Python program that asks the user for their favourite colour and Applying
then prints a message saying, “Your favourite colour is [colour]!”
Tech Adventure

88

PW_Computer_G6_Ch08.indd 88 29-11-2024 16:14:06


Variables
If you write a Python program to add two numbers, the program
will process two input numbers and add the two numbers. But
to use the input numbers, the program should store this data
somewhere. The containers that hold all these data in a program
are called variables.
Variables are like labelled boxes that hold different kinds of objects. Many types of data can
be stored in a variable. They are super useful because you can store data and name it.
Example: You can use the variable name to hold the name “Alice” and the variable age to
hold the number 23. This way, you can use these values in your program without repeatedly
typing them.
Creating a Variable Syntax: variable_name = value
In Python, variable declaration and initialisation are done with a single step of assigning a
value to a variable.

name = “Kohli” Kohli 8


number = 8
print(name,number)

word, age = “Rahul”, 10 Rahul 10


print(word, age)

Note: If we change the value of a variable and reuse it, the old value is switched to the
new value.

Rules for naming the variables


Variable names must begin with a letter (a-z, A-Z) or an underscore (___).
After the initial character, variable names can contain letters, numbers, and underscores.
Python is case-sensitive, so myVar and myvar are treated as different variables.
Variable names cannot have spaces or special characters like !, @, #, $, etc.
You cannot use reserved words like if, else, while, for, etc., as variable names.
Use descriptive names that convey the purpose of the variable.
Avoid using the names of Python’s built-in functions or libraries (e.g., print, str, list)
as variable names.
 amelCase capitalises the first letters of each word except the first word and does not use
c
spaces. While snake_case uses lowercase with underscore between words. Choose one
for readability and consistency. (e.g., myName, my_name)
Names that start with double underscores (__) have special meanings in Python. They are
usually reserved for system-defined names.

89

PW_Computer_G6_Ch08.indd 89 29-11-2024 16:14:06


Think Again: Variable Name Checker!
Problem-Solving
Tick the name of the valid variables.
1 2number 2  my-name
class
3   4  total amount
@score
5   6  myVariable!
user123 8  float
7  
number_of_items
9   10  finalGrade

Data Types
Data types define what type of data a variable, a named memory location, can hold.
Data Type Description Example

Integer (int) Stores non-decimal numbers in a variable. 27, -13, 876954

Float (float) Stores decimal point numbers in a variable. 5.5, -2.4

String (str) Stores words and characters in a variable. “Hey”,” World”

Boolean (bool) Stores two values: True and False True, False

Comments
Comments are an essential part of writing clean and understandable code. They are notes or
explanations written by the programmer that the Python interpreter ignores.

Single Line Comment


A single-line comment begins with a # symbol. Everything after the # on that line is ignored
by the Python interpreter.

# This is a single-line comment


print(“Hello, World!”) # This comment is ignored
Tech Adventure

Multi-Line Comment
For multi-line comments, Python doesn’t have a specific syntax. However, multiple single-line
comments or a string of triple quotes (‘’’ or “””) can be used for documentation purposes.

90

PW_Computer_G6_Ch08.indd 90 29-11-2024 16:14:06


“““
This is a multi-line comment
that spans several lines.
It is often used for large explanations.
”””

Operators Direct Perception

Operators are symbols that perform operations on variables and values. Python includes
various types of operators, each serving a specific purpose.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations.

Operator Description Example(int x = 6 and y = 3) Output


+ Addition x + y 9

- Subtraction x - y 3

* Multiplication x * y 18

/ Division x / y 2.0

// Floor Division x // y 2

% Modulus (Remainder) x % y 0

** Exponentiation x ** y 216

Example:

a = 12 Addition: 17
b = 5 Subtraction: 7
print (“Addition:”, a + b) Multiplication: 60
print (“Subtraction:”, a - b) Division: 2.4
print (“Multiplication:”, a * b)
Modulus: 2
print (“Division:”, a / b)
Exponentiation: 248832
print (“Modulus:”, a % b)
print (“Exponentiation:”, a ** b) Floor Division: 2
print (“Floor Division:”, a // b)

91

PW_Computer_G6_Ch08.indd 91 29-11-2024 16:14:06


Assignment Operators
Assignment operators are used to assign values to variables.

Operator Description Example Result

= Assignment x = 5 5

+= Addition Assignment x += 3 8

-= Subtraction Assignment x -= 2 3

*= Multiplication Assignment x *= 4 20

/= Division Assignment x /= 2 10.0

//= Floor Division Assignment x //= 2 5

%= Modulus Assignment x %= 3 2

**= Exponentiation Assignment x **= 2 100

Example:

a = 10 15
b = 5 10
a += b 50
print(a) 10.0
a -= b
0.0
print(a)
0.0
a *= b
0.0
print(a)
a /= b
print(a)
a %= b
print(a)
a **= b
print(a)
a //= b
print(a)
Tech Adventure

92

PW_Computer_G6_Ch08.indd 92 29-11-2024 16:14:06


Logical Operators
Logical operators are used to combine conditional statements.
Operator Description Example Output

and Logical AND True and False False

or Logical OR True or False True

not Logical NOT not True False

Example:

a = True False
b = False True
print(a and b) False
print(a or b)
print(not a)

Relational Operators
Relational operators are used to compare values.
Operator Description Example Output

== Equal to 5 == 3 False

!= Not equal to 5 != 3 True

> Greater than 5 > 3 True

< Less than 5 < 3 False

>= Greater than or equal to 5 >= 3 True

<= Less than or equal to 5 <= 3 False

Example:

a = 10 False
b = 5 True
print(a == b) True
print(a != b) False
print(a > b)
True
print(a < b)
False
print(a >= b)
print(a <= b)

93

PW_Computer_G6_Ch08.indd 93 29-11-2024 16:14:06


Teacher’s Tip
Please ensure to teach arithmetic (+, -, *, /, %), assignment (=, +=, -=), logical (and,
or, not), and relational (==, !=, <, >) operators in detail. Use real-life examples and
interactive exercises to illustrate each operator’s function. Encourage students to
practise with hands-on coding exercises to solidify their understanding.

Code Quest

Given two variables, a and b, perform the following operations in Python and Applying
answer the questions
a = 8 b = 3
1 What is the result of a + b?
2 What is the result of a - b?
3 What is the result of a * b?
4 Is a greater than b?
5 Compute (a + b) / b and check if the result is greater than 3.

Operator Precedence in Python


Order Operator(s) Description
1 () Parentheses
2 ** Exponentiation
3 *, /, //, % Multiplication, Division, Floor Division, Modulus
4 +, - Addition, Subtraction
5 ==, !=, >, <, >=, <= Comparison
6 = , +=, -=, *=, /=, //=,
%=, **= Assignment

7 and, or, not Logical

Examples of Precedence
Unary and Binary Operators:

result = -2 + 3 * 4 10
print(result)
Tech Adventure

Parentheses:

result = (2 + 3) * 4 20
print(result)

94

PW_Computer_G6_Ch08.indd 94 29-11-2024 16:14:07


Look Again
Assignment: Giving a value to a variable (e.g., x = 5). Remembered Perception

Comment: Notes in code that explain what it does, are ignored by the computer.
Function: A block of code designed to perform a specific task.
Input: Data that a user provides to a program.
Interactive Mode: A way to test code immediately.
Library: A collection of pre-written code for common tasks.
Operator: A symbol that performs operations on values (e.g., +, -).
Output: Information that a program displays or returns.
Programming: Giving a computer instructions to perform tasks.
Python: A simple and popular programming language.
Readability: How easy it is to understand code.
Script Mode: Writing and saving code in a file.
Semantics: The meaning of the code when it runs.

TECH QUEST

Tick the correct answer: Remembering


1. Which of the following is a feature of Python?
a. Complex syntax b. Large Standard Library
c. Poor readability d. No community support
2. Who created Python?
a. Guido van Rossum b. James Gosling
c. Bjarne Stroustrup d. Dennis Ritchie
3. What is the purpose of the input() function in Python?
a. To display output b. To perform calculations
c. To take user input d. To create a variable
4. Which of these is a valid Python variable name?
a. 2number b. my-name
c. sser123 d. finalGrade!
5. What type of data does a float variable hold?
a. Whole numbers b. Decimal numbers
c. Words and characters d. True or False values

95

PW_Computer_G6_Ch08.indd 95 29-11-2024 16:14:07


Write T(True) or F(False) for the below statements. Analysing
1. Python was created in the early 1980s.
2. The print() function in Python is used to receive input from the user.
3. Python’s syntax is known for being complex and hard to read.
4. Variables in Python can start with a number.
5. Python supports multiple programming paradigms, including procedural 
and object-oriented programming.
Answer the Following Questions Understanding

1. Explain what syntax refers to in programming.


2. What does the print() function do in Python? Give an example.
3. Describe the difference between Interactive Mode and Script Mode in Python.
4. List three features of Python that make it suitable for beginners.
5. How do you create a variable in Python? Provide an example.
6. What is the purpose of comments in Python code?

Coding Questions
1. Write a Python program that prints the message “Welcome to Python Application
Programming!”
2. Create a Python program that asks the user for their age and then prints “You are [age]
years old!”
3. Write a Python code snippet to perform the following calculations and print the results:
Addition of 10 and 5, Subtraction of 10 from 15, Multiplication of 4 and 5.
4. Write a Python program to store the values 20 and 15 in two variables, then swap their
values and print the results.

Application-Based Questions

1. 
If you want to store the score of a game in a Python program, what Application
type of variable would you use and why?
2. You have a list of names in a variable and want to print them one by one. Write a
Python snippet to achieve this.
3. Imagine you are building a simple calculator in Python. Which operators would you use
Tech Adventure

for addition, subtraction, multiplication, and division?


4. Explain how you would use the input() function in a Python program to get a
user’s favourite movie and then display a message including that movie name.

96

PW_Computer_G6_Ch08.indd 96 29-11-2024 16:14:07


Critical Thinking
Dive in Activity: Operational Maze!
Colour the path of the operational maze given below:

START
1 -7-3-3-1(-1) 12 4-(-2)-3
10-(-9)
-1 19 1 -1 -14

6+(-2)-3 17 -8+(-6)-(-3) 5 -9+(-1)-4

0 -17 -11 -5 -12

2-2-(-2)+2 5 5-4-(-3)+(1) 7 1-2+3-(-4)

2 4 -1 -4 6

-1-1+(-1) 0 -3-1+(-2) -6 GOAL!

Critical Thinking
Dive in Activity: Find the error!
Underline the code below where you find the error and write the correct answer in blanks.
1.
print(“Hello World)

2.
name, number = “Rahul”, 10
print(word, number)

3.
a = 12
b = 5
print(“Division:”, a // b)

4.
name = input(‘Enter your name: ’)
print(“Hello,” + name!)
5.
a = True
b = False
print(a or and b)

97

PW_Computer_G6_Ch08.indd 97 29-11-2024 16:14:07


Dive in Activity: Match it! Remembering

Data Type Description

a. Integer (int) a. Stores non-decimal number

b. Float (float) b. Store decimal point number

c. String (str) c. Store words and characters

d. Boolean (bool) d. Stores two values: True and False

e. Variable e. A container that holds data in a program

Experiential Learning
Dive in Activity: Find the output!
1.
colour = input(“Enter your favourite colour: “)
print(“Your favourite colour is “ + colour + “!”)

2.
num1 = int(input(“Enter the first number: “))
num2 = int(input(“Enter the second number: “))
print(“The sum is:”, num1 + num2)

3.
length = float(input(“Enter the length of the rectangle: “))
width = float(input(“Enter the width of the rectangle: “))
area = length * width
print(“The area of the rectangle is:”, area)
Tech Adventure

98

PW_Computer_G6_Ch08.indd 98 29-11-2024 16:14:08


4.
num1 = int(input(“Enter the first number: “))
num2 = int(input(“Enter the second number: “))
print(num1, “is greater than”, num2, “:”, num1 > num2)

5.
celsius = float(input(“Enter temperature in Celsius: “))
Fahrenheit = (celsius * 9/5) + 32
print(“Temperature in Fahrenheit is:”, Fahrenheit)

99

PW_Computer_G6_Ch08.indd 99 29-11-2024 16:14:08

You might also like