Unit 1 Notes Python
Unit 1 Notes Python
Unit 1 Notes Python
The CPU
The central processing unit, or CPU, is the part of a computer that actually runs programs. The CPU is
the most important component in a computer because without it, the computer could not run software. CPUs are
small chips known as microprocessors
Input Devices
Input is any data the computer collects from people and from other devices. The component that collects
the data and sends it to the computer is called an input device. Common input devices are the keyboard, mouse,
scanner, microphone, and digital camera.
Output Devices
Output is any data the computer produces for people or for other devices. It might be a sales report, a list
of names, or a graphic image. The data is sent to an output device, which formats and presents it. Common
output devices are video displays and printers.
Software:
The programs that run on a computer are referred to as software. There are two general categories of
software: system software and application software.
System Software:
The programs that control and manage the basic operations of a computer are generally referred to as
system software. System software typically includes the following types of programs:
i. Operating Systems: An operating system is the most fundamental set of programs on a computer. The
operating system controls the internal operations of the computer’s hardware, manages all of the devices
connected to the computer, allows data to be saved to and retrieved from storage devices, and allows other
programs to run on the computer.
ii. Utility Programs: A utility program performs a specialized task that enhances the computer’s operation or
safeguards data. Examples of utility programs are virus scanners, file compression programs, and data backup
programs.
iii. Software Development Tools: Software development tools are the programs that programmers use to create,
modify, and test software. Assemblers, compilers, and interpreters are examples of programs that fall into this
category.
Application software
Programs that make a computer useful for everyday tasks are known as application software. These are
the programs that people normally spend most of their time running on their computers.
A program is nothing more than a list of instructions that cause the CPU to perform operations. CPUs
only understand instructions that are written in machine language, and machine language instructions always
have an underlying binary structure. A machine language instruction exists for each operation that a CPU is
capable of performing. The entire set of instructions that a CPU can execute is known as the CPU’s instruction
set. Program to contain thousands or even millions of machine language instructions.
Programs are usually stored on a secondary storage device such as a disk drive. It has to be copied into
main memory, or RAM, each time the CPU executes it.
When a CPU executes the instructions in a program, it is engaged in a process that is known as the
fetch-decode-execute cycle. This cycle, which consists of three steps, is repeated for each instruction in the
program. The steps are
1. Fetch A program is a long sequence of machine language instructions. The first step of the cycle is to fetch,
or read, the next instruction from memory into the CPU.
2. Decode A machine language instruction is a binary number that represents a command that tells the CPU to
perform an operation. In this step the CPU decodes the instruction that was just fetched from memory, to
determine which operation it should perform.
3. Execute The last step in the cycle is to execute, or perform, the operation.
From Machine Language to Assembly Language:
assembly language was created in the early days of computing as an alternative to machine language.
Instead of using binary numbers for instructions.
assembly language uses short words that are known as mnemonics. A special program known as an
assembler is used to translate an assembly language program to a machine language program.
High-Level Languages:
A high-level language allows you to create powerful and complex programs without knowing how the
CPU works and without writing large numbers of low-level instructions. In addition, most high-level languages
use words that are easy to understand. Eg: Ada,Java, C++ etc.
Operators
Programming languages have operators that perform various operations on data. For example, all
programming languages have math operators that perform arithmetic.
Syntax:
In Python, as well as most other languages, the + sign is an operator that adds two numbers. The
following adds 12 and 75: 12 + 75
Each language also has its own syntax, which is a set of rules that must be strictly followed when writing
a program. The syntax rules dictate how keywords, operators, and various punctuation characters must be used
in a program. When you are learning a programming language, you must learn the syntax rules for that
particular language.
The individual instructions that you use to write a program in a high-level programming language are
called statements. A programming statement can consist of keywords, operators, punctuation, and other
allowable programming elements, arranged in proper sequence to perform an operation.
Compilers and Interpreters
Generally the CPU understands only machine language instructions, programs that are written in a high-
level language must be translated into machine language. Depending on the language that a program has been
written in, the programmer will use either a compiler or an interpreter to make the translation.
A compiler is a program that translates a high-level language program into a separate machine language
program. The machine language program can then be executed any time it is needed.
The Python language uses an interpreter, which is a program that both translates and executes the
instructions in a high-level language program. As the interpreter reads each individual instruction in the
program, it converts it to machine language instructions and then immediately executes them. This process
repeats for every instruction in the program.
A syntax error is a mistake such as a misspelled key word, a missing punctuation character, or the
incorrect use of an operator. When this happens the compiler or interpreter displays an error message indicating
that the program contains a syntax error.
USING PYTHON
The python Interpreter
Python is an interpreted language. When you install the Python language on your computer, one of the
items that is installed is the Python interpreter. The Python interpreter is a program that can read Python
programming statements and execute them.
You can use the interpreter in two modes: interactive mode and script mode.
In interactive mode, the interpreter waits for you to type Python statements on the keyboard.
Script mode, the interpreter reads the contents of a file that contains Python statements. Such a file is known as
a Python program or a Python script. The interpreter executes each statement in Python program as it reads it.
Chapter-2:
I. INPUT, PROCESSING, AND OUTPUT
Computer programs typically perform the following three-step process:
1. Input is received.
2. Some process is performed on the input.
3. Output is produced.
Input is any data that the program receives while it is running. One common form of input is data that is typed
on the keyboard. Once input is received, some process, such as a mathematical calculation, is usually performed
on it. The results of the process are then sent out of the program as output.
Displaying Output with The Print Function:
We use the print function to display output in a Python program. A function is a piece of prewritten
code that performs an operation. Python has numerous built-in functions that perform various operations.
Perhaps the most fundamental built-in function is the print function, which displays output on the screen. Here
is an example of a statement that executes the print function:
print('Hello world')
In interactive mode, if you type this statement and press the Enter key, the message Hello world is displayed.
Here is an example:
>>> print('Hello world')
Hello world
>>>
When programmers execute a function, they say that they are calling the function. When you call the print
function, you type the word print, followed by a set of parentheses. Inside the parentheses, you type an
argument, which is the data that you want displayed on the screen.
III. COMMENTS
Comments are part of the program, but the Python interpreter ignores them. Comments are short notes
placed in different parts of a program, explaining how those parts of the program work. Comments are intended
for any person reading a program's code, not the computer.
In Python you begin a comment with the # character. When the Python interpreter sees a # character, it
ignores everything from that character to the end of the line. Large and complex programs can be almost
impossible to read and understand if they are not properly commented.
Ex-2 Program: (comment.py)
Variables:
A variable is a name that represents a value stored in the computer’s memory. Programs use variables to
access and manipulate data that is stored in memory. A program that calculates the distance between two cities
might use the variable name distance to represent that value in memory. When a variable represents a value in
the computer’s memory, we say that the variable references the value.
When you pass a variable as an argument to the print function, you do not enclose the variable name in quote
marks. To demonstrate why, look at the following interactive session:
>>> print('width')
width
>>> print(width)
10
As shown in the following interactive session, an error occurs if the item on the left side of the = operator is not
a variable:
>>> 25 = age
SyntaxError: can't assign to literal
>>>
Performing Calculations:
Python has numerous operators that can be used to perform mathematical calculations. A programmer’s
tools for performing calculations are math operators. Table lists the math operators that are provided by the
Python language.
Table python operators
Notice that the multiplication (*), floating-point division (/), integer division
(//), and remainder (%) operators have the same precedence. The addition (+) and
subtraction (−) operators also have the same precedence. When two operators
with the same precedence share an operand, the operators execute from left to
right.
Example Program:
# Get a number of seconds from the user.
total_seconds = float(input('Enter a number of seconds: '))
# Get the number of hours.
hours = total_seconds // 3600
# Get the number of remaining minutes.
minutes = (total_seconds // 60) % 60
# Get the number of remaining seconds.
seconds = total_seconds % 60
# Display the results.
print('Here is the time in hours, minutes, and seconds:')
print('Hours:', hours)
print('Minutes:', minutes)
print('Seconds:', seconds)
Mixed-type expressions:
my_number = 5 * 2.0
When this statement executes, the value 5 will be converted to a float (5.0) and then multiplied by 2.0.
The result, 10.0, will be assigned to my_number.
The int to float conversion that takes place in the previous statement happens implicitly. If you need to
explicitly perform a conversion, you can use either the int() or float() functions. For example, you can use the
int() function to convert a floating-point value to an integer, as shown in the following code:
fvalue = 2.6
ivalue = int(fvalue)
The first statement assigns the value 2.6 to the fvalue variable. The second statement passes fvalue as an
argument to the int() function. The int() function returns the value 2, which is assigned to the ivalue variable.
Each of the statements shown here displays a string and then prints a newline character. You do not see
the newline character, but when it is displayed, it causes the output to advance to the next line.
If you do not want the print function to start a new line of output when it finishes displaying its output,
you can pass the special argument end=' ' to the function, as shown in the following code:
print('One', end=' ')
print('Two', end=' ')
print('Three')
Notice that in the first two statements, the argument end=' ' is passed to the print function. This specifies
that the print function should print a space instead of a newline character at the end of its output. Here is the
output of these statements:
One Two Three
Escape Characters
An escape character is a special character that is preceded with a backslash (\), appearing inside a string
literal. When a string literal that contains escape characters is printed, the escape characters are treated as
special commands that are embedded in the string.
For example, \n is the newline escape character. When the \n escape character is printed, it isn’t
displayed on the screen. Instead, it causes output to advance to the next line.
A control structure is a logical design that controls the order in which a set of statements execute. The
following are the various control structures or decision structures
1. The if Statement
2. The if-else Statement
3. Comparing Strings
4. Nested Decision Structures and
5. the if-elif-else Statement
6. Logical Operators
7. Boolean Variables
The if Statement:
The if statement is used to create a decision structure, which allows a program to have more than one
path of execution. The if statement causes one or more statements to execute only when a Boolean expression is
true.
In Python we use the if statement to write a single alternative decision structure. Here is the general
format of the if statement:
If the condition is true, we follow one path, which leads to an action being performed. If the condition is
false, we follow another path, which skips the action.
if condition:
statement
statement
etc.
When the if statement executes, the condition is tested. If the condition is true, the statements that appear
in the block following the if clause are executed. If the condition is false, the statements in the block are
skipped.
For example, the greater than operator (>) determines whether one value is greater than another. The equal to
operator (==) determines whether two values are equal. Table 3-1 lists the relational operators that are available
in Python.
Comparing Strings:
Python allows you to compare strings. This allows you to create decision structures that test the value of a string.
For example, look at the following code:
name1 = 'Mary'
name2 = 'Mark'
if name1 == name2:
print('The names are the same.')
else:
print('The names are NOT the same.')
The == operator compares name1 and name2 to determine whether they are equal.
Logical Operators:
The logical and operator and the logical or operator allow you to connect multiple Boolean expressions to create
a compound expression. The logical not operator reverses the truth of a Boolean expression.
The and Operator
The and operator takes two Boolean expressions as operands and creates a compound Boolean
expression that is true only when both subexpressions are true.
The following is an example of an if statement that uses the and
operator:
The or Operator
The or operator takes two Boolean expressions as operands
and creates a compound Boolean expression that is true when either
of the subexpressions is true. The following is an example of an if
statement that uses the or operator:
if temperature < 20 or temperature > 100:
print('The temperature is too extreme')
Condition-Controlled and Count-Controlled Loops: two broad categories of loops: condition-controlled and
Count-controlled. A condition-controlled loop uses a true/false condition to control the number of times that it
repeats. A count-controlled loop repeats a specific number of times.
1.The while Loop: A Condition-Controlled Loop:
The condition is tested, and if it is true, the process repeats. If the condition is false, the program exits the
loop.Here is the general format of the while loop in Python:
while condition:
statement
statement
etc
2.The for Loop: A Count-Controlled Loop:
A count-controlled loop iterates a specific number of times. In Python you use the for statement to write a
count-controlled loop.
In Python, the for statement is designed to work with a sequence of data items. When the statement
executes, it iterates once for each item in the sequence. Here is the general format:
Here is an example:
for num in range(1, 5):
print(num)
Here is an example:
x=x+1
On the right side of the assignment operator, 1 is added to x. The result is then assigned to x, replacing the value
that x previously referenced.
When input is given to a program, it should be inspected before it is processed. If the input is invalid, the
program should discard it and prompt the user to enter the correct data. This process is known as input
validation
Figure 4-7 shows a common technique for validating an item of input. In this technique, the input is
read, and then a loop is executed. If the input data is bad, the loop executes its block of statements. The loop
displays an error message so the user will know that the input was invalid, and then it reads the new input. The
loop repeats as long as the input is bad.
Nested Loops:
A loop that is inside another loop is called a nested loop. A nested loop is a loop that is inside another
loop. A clock is a good example of something that works like a nested loop.
Syntax
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
Example:
for x in range(1,5):
for y in range(1,10):
print (x,"*",y,"=",(x*y))
Output :
1*1=1
1*2=2
1*3=3
1*4=4
1*5=5
1*6=6
1*7=7
1*8=8
1 * 9 = 9 so on
Boolean Variables:
A Boolean variable can reference one of two values: True or False. Boolean variables are commonly
used as flags, which indicate whether specific conditions exist.
Python also provides a bool data type. The bool data type allows you to create variables that may
reference one of two possible values: True or False. Here are examples of how we assign values to a Boolean
variable:
Ex:
x=10
Print(x==10)
o/p:
true
====xxx====
(Choice –Easy notes)
Repetition Structures: (LOOPING STATEMENTS IN PYTHON)
A loop statement allows us to execute a statement or group of statements multiple times. The following
diagram illustrates a loop statement –
Python programming language provides following types of loops to handle looping requirements.
1 while loop:Repeats a statement or group of statements while a given condition is TRUE. It tests the condition
before executing the loop body.
2 for loop:Executes a sequence of statements multiple times and abbreviates the code that manages the loop
variable.
3 nested loops: You can use one or more loop inside any another while, for loop.
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any non-zero value. The loop iterates while the condition is true. When the condition
becomes false, program control passes to the line immediately following the loop.
In Python, all the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code. Python uses indentation as its method of grouping
statements.
Flow Diagram
Here, key point of the while loop is that the loop might not ever run. When the condition is tested and
the result is false, the loop body will be skipped and the first statement after the while loop will be executed.
Example
count = 0
while (count < 9):
print (“The count is:”, count)
count = count + 1
print "Good bye!"
When the above code is executed, it produces the
following result −
The block here, consisting of the print and increment statements, is executed repeatedly until count is no longer
less than 9. With each iteration, the current value of the index count is displayed and then increased by 1.
2. The For loop :
A count-controlled loop iterates a specific number of times. In Python you use the for statement to write a count-
controlled loop.
In Python, the for statement is designed to work with a sequence of data items. When the statement
executes, it iterates once for each item in the sequence. Here is the general format:
The for statement executes in the following manner: The variable is assigned the first value in the list,
and then the statements that appear in the block are executed. Then, variable is assigned the next value in the
list, and the statements in the block are executed again. This continues until variable has been assigned the last
value in the list.
Example:
>>> for var in list(range(5)):
print (var)
Output:This will produce the following output.
0
1
2
3
4
Example:
Number of integers (whole numbers) to generate, starting from zero.
Example: range(3) == [0, 1, 2].
Nested Loops:
A loop that is inside another loop is called a nested loop. A nested loop is a loop that is inside another
loop. A clock is a good example of something that works like a nested loop.
Syntax:
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
Example:
for x in range(1,5):
for y in range(1,10):
print (x,”*”,y,”=”,(x*y))
Output :
1*1=1
1*2=2
1*3=3
1*4=4
1*5=5
1*6=6
1*7=7
1*8=8
1*9=9
so on
==*****==