Monday, April 7, 2025

7.6 Introduction to Python Programming | Grade 9 New Curriculum Computer Science 2082

 




7.6 Introduction to Python Programming

 

Python

·       Python is a high-level, interpreted programming language created by Guido van Rossum in 1991.

·       It is known for its simple and readable syntax, making it beginner-friendly and highly versatile.

·       Python is widely used in web development, data science and machine learning, artificial intelligence, data analysis, automation and scripting, game development, web scraping, cyber security, etc.

·       Python has a simple to understand coding style, applying indentation instead of braces to define blocks of code. For example, in a loop or conditional statement, indentation signifies the scope of the block.

 

Features of Python

·       Easy to read and write: Python uses simple and understandable syntax, making it easy for programmers to write and understand the code.

·       Versatile: Python can be used for a wide range of tasks like simple automating systems to complex web development, data analysis, and Artificial Intelligence.

·       Beginner-friendly: Python uses simple syntax, making it a great choice for those who are new to programming.

·       Extensive standard library: Python has an extensive standard library of pre-written code that offers programmers ready-made solutions, without requiring them to write code from ground level.

 

Installation process of Python

Visit the official Python website ( https://www.Python.org/downloads/ )and download the latest version of Python 3.x for Windows. The website will automatically detect your operating system and offer the appropriate installer for your system (32-bit or 64-bit).

Download and install suitable IDE for Python. (PyCharm, VS Code, Jupyter Notebook, etc)

 

7.7 Basic Syntaxes in Python

 

Python’s syntax is straightforward and beginner-friendly.

 

Comments in Python

Comments are brief messages that programmers write in their code to explain what the code is doing, like leaving helpful hints for others to understand the program.

Single-line comments start with #, and multi-line comments are enclosed in triple quotes (''' or """).

Example:

# This is a single-line comment

"""

This is a

multi-line comment

"""

Keywords

Keywords are reserved words that have predefined meanings and cannot be used as identifiers (variable names, function names, etc.).

Example: False,  await,  else,  import,  pass etc.

 

7.8 I/O statements and string formatting

 

Input/Output statements (I/O)

I/O statements help us to interact with the program. i.e. It allows us to provide our data and instructions to the program as well as display the output on screen.

 

Print Statement

The print statement in Python is used to display information on the screen. We use a ‘print’ statement to display the output of data that we want to show.

Example: print(“Hello, Python!”)

 

Input Function

The ‘input’ function allows to provide input to the program. We can give data to the program as we need.

Example: number = input(“Enter number: ”)

 

String Formatting

String formatting in Python helps to insert values into a string, making it easier to create dynamic and personalized messages.

 

Using % Operator (Old Style)

This is the old style of string formatting, where we use % to insert values into a string.

Example:

name = "Charlie"

age = 22

message = "My name is %s and I am %d years old." % (name, age)

print(message)

Output

My name is Charlie and I am 22 years old.

 

Using format( ) Method

The format( ) method allows to insert values into a string using curly braces {} as placeholders.

Example:

name = "Bob"

age = 30

message = "My name is {} and I am {} years old.".format(name, age)

print(message)

Output

My name is Bob and I am 30 years old.

We can also use numbered or named placeholders

Example:

message = "My name is {0} and I am {1} years old.".format(name, age)

print(message)

 

 

 

Using f-strings (Formatted String Literals)

f-strings are the most modern and efficient way to format strings. We can directly embed expressions inside curly braces {}. It was introduced in Python 3.6.

Example:

name = "Alice"

age = 25

message = f"My name is {name} and I am {age} years old."

print(message)

Output

My name is Alice and I am 25 years old.

 

7.9 Data types and variables

 

Data type

The classification of data based on its nature is called data type. It defines the kind of data a variable can hold.

Python supports several data types:

·       Integer (int): It is a whole number ranging from negative infinity to positive infinity.

Examples: -,...,-3,-2,-1,0,1,2,3,....,

·       Float (float): It is numbers with decimals.

Examples: 3.14, -0.5, 1.567.

·       String (str): It consists of alphabets, special characters, alphanumeric values which are enclosed in double quotes.

Examples: “hello” , “Python@”, “Mahendranagar1”, “@#@#kathmandu”

·       Boolean (bool): It only provides True or False values.

Example: is_student = True, has_mobile=False

 

Identifier

Identifiers are names given to program units such as variables, functions, classes, or other entities. They are not predefined in the programming language but are defined by programmers themselves.

 

Rules for identifier

·       An identifier name must start with a letter or the underscore character.

·       An identifier name cannot start with a number.

·       An identifier name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).

·       Python is case sensitive so identifier names are also case-sensitive. (age, Age and AGE are three different identifiers).

·       An identifier name cannot be any of the Python keywords.

 

Valid identifiers

A1, B34, First_Name, x_1 etc.

 

Invalid identifiers

1A, 34BA,198, int, print first-name. def etc.

 

Variables in Python

A variable is like a container that holds a value which stores numbers, text, or other data types. A variable is created when the value is assigned to it.

Example:

name = "Alice"     # String variable

age = 25           # Integer variable

height = 5.5       # Float variable

is_student = True #Boolean variable

 

7.10 Concept of Type Casting

 

Type Casting (Type Conversion)

Type casting is the process of converting one data type into another. For example, if we assign an integer (int) value to a float variable, the compiler will convert the int value to a float.

 

Types of casting

·       Implicit casting

·       Explicit casting

 

Implicit casting

Implicit type casting, also known as automatic type conversion, occurs when the Python interpreter automatically converts one data type to another in certain situations.

Examples:

x = 10 # integer

y = 5.5 # float

z = x + y # the integer ‘x’ is cast to a float for the addition.

print(z)

 

Explicit casting

In explicit type casting, the user intentionally converts the data type of a variable to another data type.

·       int(): Converts a value to an integer.

·       float(): Converts a value to a float.

·       str(): Converts a value to a string.

·       bool(): Converts a value to a boolean (True or False).

Example:

int(x): Converts x to an integer.

x = 3.14

y = int(x)  # Converts float to int (removes decimal part)

print(y)     # Output: 3

 

x = 25

y = str(x)    # Converts integer to string

print(y)      # Output: "25"

 

 

7.11 Operators and Expressions: Arithmetic, Relational, Logical, Assignment

 

Operators

Operators in Python are symbols that perform specific operations on variables and values. Python supports various types of operators, including arithmetic, relational, logical, and assignment operators.

 

Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication, and more.

Example:

Simple program to find the sum of the two number for the user input

num1 = float(input(“Enter first number: “))

num2 = float(input(“Enter second number: “))

sum = num1 + num2

print(“The sum of {0} and {1} is {2}”.format(num1, num2, sum))

 

Relational operator

Relational operator is used to check and compare values. These operators check the relationship between two things and tell us if they are equal, greater than or less than each other.

 

Logical operator

Logical operators in Python are used to combine conditions and make decisions based on different situations. This operator is like a tool that helps us make decisions based on different situations. There are 3 main logical operators, ‘and’, ‘or’, and ‘not’.

 

AND

Both the conditions must be true for the result to be true in the “and” operator.

Example: x = (5<2) and (5>3)

Result: False

OR

Only one of the conditions needs to be true for the result to be true in the “or” operator.

Example: (5<2) or (5>3)

Result: True

NOT

The logical operator “not” provides the opposite result of a given condition.

Example: not(5<2)

Result: True

Assignment operator

Assignment operators are used to assign values to variables.

Expression

An expression is a combination of values, variables, operators, and functions that are evaluated to produce a result.

Example:

Maths expression: result = 5 + 3

Text expression: greeting = “Hello”

Combining expression: combined = (5 * 3) + “Python”

 

Operands

Operands are values or variables that operators operate on. Operands refer to the values or entities that are operated upon by an operator.

Example: add = 5 + 3

Here, ‘5’ and ‘3’ are operands and ‘+’ is an operator, and it is performing an ‘addition’ operation.

7.1 Introduction to Programming Language | Grade 9 New Curriculum Computer Science |

 




7.1 Introduction to Programming Language

7.2 Types of programming languages 

 7.3 Programming tools: flowchart and algorithm 

 7.4 Introduction to coding, testing, and debugging 

 7.5 Compiler and interpreter

 Programming Language

A programming language is a language consisting of a set of instructions provided by the user that tells a computer what task to do and how to do it.

We use a programming language to communicate with computers and tell them what to do. It helps us create apps, games, websites, and much more.

Python, Java, PHP, C++, etc. are some examples of popular programming languages.

 

Programming

It is the process of providing detailed instructions to a computer step by step to do specific tasks.

 

Programmer

A programmer is a person who is involved in writing computer programs.

 

Syntax

The rule for writing commands is called syntax.

7.2 Types of programming languages

·       High-level programming language

·       Low-level programming language

 

High-level programming language

·       A high-level programming language is a type of programming language that is easy for humans to read, write, and understand.

·        It uses English-like words and symbols to create computer programs and needs to be translated into machine language using a compiler or interpreter.

·       Programs written in high-level languages are called program code, and they’re readable to humans but not to computers.

·       Examples: Python, Java, C++, PHP etc.

Low-level programming language

·       Low level programming language is a type of programming language which consist of 0s and 1s and directly understood by computers.

·       Programs are written in the form of machine code, which is difficult for humans to understand without specialized knowledge.

·       Machine language and Assembly language are the types of low level programming language.

·       Machine language is a type of low level programming language which consists of binary code (0s and 1s) that the computer's CPU understands directly. Example: 10101100 01011101

·       Assembly Language is a human-readable form of machine language which uses symbolic codes or mnemonics (e.g., MOV, ADD, SUB) instead of binary.

·       Requires an assembler to convert the assembly code into machine code. Example: MOV AX, 5 ; ADD AX, 3

High level language Vs Low level language

Low-Level Language

High-Level Language

Close to computer hardware (machine)

Close to human language (English-like)

Hard to understand and write

Easy to read, write, and learn

Very fast and powerful

Slower but more user-friendly

Example: Machine code, Assembly language

Example: Python, Java, JavaScript

 

High-level languages are better for beginners because:

  • They are easy to read and write
  • Use English-like words
  • Require less time to learn
  • Help beginners focus on solving problems instead of writing complex code

 

 

7.3 Programming tools: Flowchart and Algorithm

 

Algorithm

An algorithm is a set of step-by-step instructions designed to solve a specific problem or perform a particular task.

It begins with “start” and ends with “stop.”

The instructions are written in simple, general language (like spoken languages).

 

Flowchart

A flowchart is defined as the pictorial and graphical representation of an algorithm.

It uses shapes like rectangles, diamonds, and arrows to show the steps in the process.

The shapes have distinct meanings in a flowchart

 


The table below shows shapes used in flowchart and their meaning:

 




 

We use flowcharts in programming because:

  • They help us visualize the process before writing code.
  • They make it easier to understand how the program works.
  • They help in debugging by showing where things might go wrong.
  • They make complex processes simpler to follow.

 

7.4 Coding, testing and debugging

 

Coding

Coding is the process of writing instructions in a programming language to create software or applications. These instructions, known as code, tell the computer exactly what tasks to perform.

 

Testing

Testing is the process of running program to make sure it works correctly.

Once the code is written, testing is conducted to ensure the program functions as expected.

This involves running the program to identify any errors or bugs and verifying that all parts of the program work correctly.

 

The purpose of testing a program is to make sure that the program works correctly and produces the expected results. Testing helps us identify errors or bugs in the code before it is used in real-world situations.

 

Debugging

Debugging is the process of finding and fixing mistakes (called bugs) in the code.

If testing reveals any errors or bugs, the process of debugging begins.

Bugs can occur because of simple mistakes like missing a comma, using the wrong variable, or logical errors.

 

Debugging is important because:

  • It helps ensure that the program runs correctly.
  • It allows us to find and fix errors that can cause the program to fail.
  • It makes the program more reliable and stable.
  • Without debugging, programs might give incorrect results or crash, which can be frustrating for users.

 

7.5 Compiler and Interpreter

 

Compiler

A compiler is a translator of computer programs that translate the entire high-level language into machine level programming language in a single operation on a computer.

Examples:  JAVA, C#, C, C++, FORTRAN, etc.

 

Interpreter

Interpreter is a translator of computer programs that translate high-level language into machine level programming language one instruction (line of code) and then moves on to the other line.

Examples: Python, Ruby, Qbasic, JavaScript etc.

 


An Assembler is a special tool that translates programs written in Assembly language into machine code, which the computer can understand