0% found this document useful (0 votes)
217 views14 pages

IT Note Unit 6 Grade 12

It note grade 12 Ethiopian

Uploaded by

naoltujuba383
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
217 views14 pages

IT Note Unit 6 Grade 12

It note grade 12 Ethiopian

Uploaded by

naoltujuba383
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Grade 12 IT short notes

Unit 6

Fundamental programming

PythonBasics of python

is a widely used general-purpose, high level programming language. It was initially designed by
Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed
for emphasis on code readability, and its syntax allows programmers to express concepts in fewer
lines of code.
Python is a programming language that lets you work quickly and integrate systems more efficiently.

Why to use Python:


The following are the primary factors to use python in day-to-day life:
1. Python is object-oriented
Structure supports such concepts as polymorphism, operation overloading and
multiple inheritance.
2. Indentation
Indentation is one of the greatest feature in python

3. It’s free (open source)


Downloading python and installing python is free and easy
4. It’s Powerful
 Dynamic typing
 Built-in types and tools
 Library utilities
 Third party utilities (e.g. Numeric, NumPy, sciPy)
 Automatic memory management
5. It’s Portable

Python runs virtually every major platform used today


 As long as you have a compaitable python interpreter installed, python
programs will run in exactly the same manner, irrespective of platform.
6. It’s easy to use and learn
 No intermediate compile
 Python Programs are compiled automatically to an intermediate form called
byte code, which the interpreter then reads.
 This gives python the development speed of an interpreter without the
performance loss inherent in purely interpreted languages.
 Structure and syntax are pretty intuitive and easy to grasp.
7. Interpreted Language
Python is processed at runtime by python Interpreter
8. Interactive Programming Language
Users can interact with the python interpreter directly for writing the programs
9. Straight forward syntax
The formation of python syntax is simple and straight forward which also makes it
popular.

Python Code Execution:


Python’s traditional runtime execution model: Source code you type is translated to byte
code, which is then run by the Python Virtual Machine (PVM). Your code is automatically compiled,
but then it is interpreted.

Source code extension is .py Byte code extension is .pyc (Compiled python code)

There are two modes for using the Python interpreter:


• Interactive Mode
• Script Mode

Using the Interactive Interpreter

The Interactive Interpreter contains a Python shell, which is a textual user interface used to work
with the Python language. The Interactive Interpreter is displayed when the IDLE is opened.

Notes
„ The >>> is where codes are written and is called the prompt. After a user writes a code
and presses the enter key, the prompt (>>>) reappears for the user to write the next code.
The following example demonstrates what the Interactive Interpreter does when the enter key is
pressed after a simple expression is written.

>>>5+6
11
>>>

Notes
„ 5+6 is a syntactically valid expression that evaluates to 11. Therefore, the Python interpreter
evaluated the expression and displayed 11. If, for example, a syntactically invalid expression like 5+ is
given, the interpreter generates the following syntax error:
Using the Text Editor
Python codes can be written in a file using the text editor of Python’s IDLE. The code that is kept
in such files is known as a script. A file that keeps Python scripts is saved with the .py extension
and is called a script file.

Variables and Data Types


Variables are computer memory locations. They are the means to store data in computer memory. A
variable is used every time user data or intermediary data is needed to be kept.

In Python, a variable is created along with its value. Values are assigned to variables using the
assignment (=) operator, which has two operands. The operand to the left of the operator is always
a variable while the operand to the right of the operator is either a literal value or any other type
of expression.

Multiple Assignment:
Python allows you to assign a single value to several variables simultaneously.
For example :
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables.
For example -
a,b,c = 1,2,"mrcet“
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and
one string object with the value "john" is assigned to the variable c.

Identifier
The name that is given to variables is called an identifier. Identifiers are a string of one or more
characters and have to conform to some rules in Python to be considered valid. The rules of
identifiers are:
• The first character should be either a letter or an underscore ( _ ).
• If the identifier is made up of more than one character, the characters after the first one
should be a letter, number, or underscore.
• An identifier cannot be the same as any of the keywords in Python.

• Identifiers are case-sensitive. (For instance, x and X are considered as different identifiers in
Python)

Data Types
A data type is a classification that specifies the type of values a variable can have, and the type of
operations defined on the values. Integer (int), floating-point number (float), string (str), and
Boolean (bool) are some of the major built-in data types in Python.
A statement is an instruction that the Python interpreter executes.

Expressions are what the Python interpreter evaluates to produce some value. An expression could
be a simple literal value, a variable, or something more complex which is a combination of literals,
variables, and operators.

Comments:
Single-line comments begins with a hash(#) symbol and is useful in mentioning that the
whole line should be considered as a comment until the end of line.
A Multi line comment is useful when we need to comment on many lines. In python, triple double
quote(“ “ “) and single quote(‘ ‘ ‘)are used for multi-line commenting.

Modules: Python module can be defined as a python program file which contains a python code
including python functions, class, or variables. In other words, we can say that our python code file
saved with the extension (.py) is treated as the module. We may have a runnable code inside the
python module. A module in Python provides us the flexibility to organize the code in a logical way.
To use the functionality of one module into another, we must have to import the specific module.
Syntax:
import <module-name>
Every module has its own functions, those can be accessed with . (dot)
Note: In python we have help () Enter the name of any module, keyword, or topic to get help on
writing Python programs and using Python modules. To quit this help utility and return to the
interpreter, just type "quit".

A function is a piece of code that performs some task and is called by its name. It can be passed
data as input to operate on, and can optionally return data as output. print(), input() and type() are
examples of functions.

Functions and its use: Function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable. It avoids repetition and
makes code reusable.
Basically, we can divide functions into the following two types:
1. Built-in functions - Functions that are built into Python.
Ex: abs(),all().ascii(),bool()………so on….
integer = -20
print('Absolute value of -20 is:', abs(integer))
Output:
Absolute value of -20 is: 20
2. User-defined functions - Functions defined by the users themselves.
def add_numbers(x,y):
sum = x + y
return sum
print("The sum is", add_numbers(5, 20))
Output:
The sum is 25
Flow of Execution:
1. The order in which statements are executed is called the flow of execution
2. Execution always begins at the first statement of the program.
3. Statements are executed one at a time, in order, from top to bottom.
4. Function definitions do not alter the flow of execution of the program, but remember that
statements inside the function are not executed until the function is called.
5. Function calls are like a bypass in the flow of execution. Instead of going to the next statement,
the flow jumps to the first line of the called function, executes all the statements there, and then
comes back to pick up where it left off.

Parameters and arguments:


Parameters are passed during the definition of function while Arguments are passed during
the function call.
Example:
#here a and b are parameters
def add(a,b): #//function definition
return a+b
#12 and 13 are arguments
#function call
result=add(12,13)
print(result)

There are three types of Python function arguments using which we can call a function.
1. Default Arguments
2. Keyword Arguments
3. Variable-length Arguments
Syntax:
def functionname():

statements
. . .
functionname()
Function definition consists of following components:
1. Keyword def indicates the start of function header.
2. A function name to uniquely identify it. Function naming follows the same rules of writing
identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements must have
same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.
Example:
def hf():
hello world
hf()

In the above example we are just trying to execute the program by calling the function. So it will
not display any error and no output on to the screen but gets executed.
To get the statements of function need to be use print().
#calling function in python:
def hf():
print("hello world")
hf()
Output:
hello world

def hf():
print("hw")
print("gh kfjg 66666")
hf()
hf()
hf()
Output:
hw
gh kfjg 66666
hw
gh kfjg 66666
hw
gh kfjg 66666
---------------------------------
def add(x,y):
c=x+y
print(c)
add(5,4)
Output:
9
def add(x,y):
c=x+y
return c
print(add(5,4))
Output:
9

def add_sub(x,y):
c=x+y
d=x-y
return c,d
print(add_sub(10,5))
Output:
(15, 5)
The return statement is used to exit a function and go back to the place from where it was
called. This statement can contain expression which gets evaluated and the value is returned.
If there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the None object.
def hf():
return "hw"
print(hf())
Output:
hw
----------------------------
def hf():
return "hw"
hf()

6.1. Program Flow Controls and Syntax in Python

A program flow control is the order in which the program’s code executes. In Python, the flow
control of the program is regulated by the implementation of three types of programming language
constructs or program logic, namely sequential, branching, and loop.

Conditionals Program Flow Controls

Conditional Expression
Conditional expressions are statements that use Boolean operators (such as AND, OR, NOT) or
comparison operators (such as >,<. ≠). Like in mathematics, comparisons of two values in Python are
described with comparison signs used in mathematics.
Conditional or branching statements
Conditionals are statements in a program in which the program decides at runtime whether some
parts of the code should or should not be executed. From the earlier even/odd example, a given
integer number can be even or odd, but this can be decided based on the remainder after dividing
the number by two. Therefore, first: Decide whether (num % 2 == 0) is or is not true.

In Python, a conditional statement is written using the if keyword. Like many other programming
languages, Python provides various versions of branching statements that can be implemented using
the if clause: simple if statement, if..else statement, and if..elif…else statement.

if statement: this is the simplest implementation of a conditional statement that decides only one
part of the program to be executed if the condition is satisfied or ignored if the condition fails.
The condition is an expression that is either true or false. If the condition (expression) is true,
then do the indented statement(s)

Notes
„ You can have any statement before or after the ‘if statement’ which is not considered as part of
the ‘if statement’ and is executed as normal.
However, the ‘if expression’ must follow at least one statement to be executed, otherwise it is a
syntax error.
if…else statement: The ‘if...else statement’ provides two alternative statements or
blocks: one following the ‘if expression’ and another following the ‘else clause’.
‘if…else’ allows us to specify two options: one which is executed if a condition is

true (satisfied), and another which is executed if the condition is false (not satisfied)

If...elif…else statement: Assume a problem that could have many options to


choose from or require several conditions. For example, you want to develop a
program that will print ‘Excellent, Very Good, Good, Satisfactory, or Fail’ based
on the student mark. In such situations, Python allows you to add any number of
alternatives using an elif clause after an if and before an else clause.
The elif is a keyword in Python to say “if the previous condition(s) are not true,
then try this condition”. The else keyword catches anything that is not caught by
all the preceding conditions.

The general syntax for ‘if…elif…else’ is given in

if expression1:
statement1
statement2
...
elif expression2:
statement3
statement4
...
elif expression3:
statement5
statement6
....................
else:
statement7
statement8
...

Using ‘and’ and ‘or’ with if…statement: The ‘and’, and ‘or’ keywords are also used with
‘if...statement’ in Python. The ‘and’ and ‘or’ keywords are logical operators and are used to combine
conditional statements.
‘and’ operator in if … statement:
Using ‘or’ operator with if… statement: The ‘or’ operator is used to combine conditional
statements. The three conditional statements compare the value of mySubject with ‘Physics’,
‘Chemistry’, and ‘Geograpy’. The evaluation of the ‘if’ expression is True if one of these three
conditions is satisfied. Otherwise,

the expression evaluates to False, and in that case, it executes the statement under
the else clause.

Loops or Iteration Program Flow Controls

Python provides several language features to make iteration/looping easier. There are two types of
loops that are built into Python: for loops and while loops. In the following section, implementation
of ‘for loop’ is discussed and then followed by ‘while loop’ in python.
for loops: The for loop in python is used to iterate over a sequence.

Syntax:
for

variable_name in sequence :
statement_1
statement_2
[....]

for loop with range() function: The range() function returns a list of consecutive integers. The
sequence of numbers starts from 0 by default, and counts by incrementing 1(by default), and ends
at a specified number. It is widely used count controlled loops.
range(x): generates a sequence of numbers from 0 to x, excluding x, incrementing by 1.

range(x, y): This generates a sequence of numbers from x to y excluding y,


incrementing by 1.

range(x, y, z): This generates a sequence of numbers from x to y excluding y,


incrementing by z. This is different from the above range function in that the
increment is set by the z value

for loop in iterable object: Now let us see an example of a for loop in an iterable object. Unlike
the earlier example, the loop iterates while something is true. This type of loop is called a condition
controlled loop.

Syntax: for variable_name in string


for loop can iterate through string. The string is an iterable object in python because it contains a
sequence of characters. Thus, applying for loop in a string allows us to access the content
character by character.

break Statement with for: The term break is a keyword in python. With the break statement, you
can stop the loop before it has looped through all the items:

continue keyword with for loop: The term continue is a keyword in python. With the continue
statement, you can stop the current iteration of the loop, and it continues with the next.
while Statement: The while statement in Python supports repeated execution of a statement or
block of statements that is controlled by a conditional expression.
The general syntax for the while statement is:
Syntax:
while expression:
Note that in python expression must end by
Statement_1
colon(:). Statements under the while must be
Statement_2
indented.
[…]

The while loop runs as long as the condition (expression) evaluates to True and executes the
program block (statement_1, statement_2 …). The expression is checked every time at the
beginning of the loop and the first time when the expression evaluates to False, the loop stops
without executing any remaining statement(s)

break and continue keywords with while loop: With the break statement, you can stop the
loop even if the while condition is true. It causes the loop to quit even before reaching the last
iteration. The loop in the program below terminates when the value of count is 5 (in the 5th
iteration).

You might also like