Python Intro
Python Intro
Machine Language
Assembly Language
Since computers do not directly understand any program outside the machine
language, programs that are written in assembly language require a special type of
software. This software is known as Assembler, and it is used to translate assembly
language instructions into machine language.
High-Level Language
Just like assembly language programs, high-level language programs also cannot
be directly executed by the computer. The programs have to be first translated
into a machine language using translator software. Depending on the programming
language, the translator software can be either a Compiler or an Interpreter.
Compilers translate high-level language written programs all at once into machine
language. The machine language is then executed by the computer. Examples of
programming languages that use compilers are C, C++, Java, and C#.
Like any human language, all programming languages have syntax and semantics.
Syntax refers to the rules of the programming language. It defines the structure or
grammar of the language that programs should strictly follow. The semantics of a
programming language, on the other hand, is related to the meaning of elements of
a program and what they do.
A program must be written with the correct syntax dictated by the programming
language for the program to be executed by the computer. If a program violates any
of the syntax rules of a language, the compiler or the interpreter produces an error
message. Such type of error is known as a syntax error.
A program can have no syntax error and get executed properly but can still behave
in a way different from what it is intended to. This kind of error is known as logic
error and is associated with the semantics of a language. Since compilers or
interpreters do not catch logic errors, they are far more difficult to identify and fix
than syntax errors.
Links
See Section 6.2 for practical examples of syntax and logic errors.
Activity 6.1
1. Compare and contrast the three types of programming languages.
2. Why are logic errors more difficult to fix than syntax errors?
Python has a free integrated development environment known as IDLE. IDLE stands
for Integrated Development and Learning Environment. To write Python codes, the
interactive interpreter or the text editor of the IDLE can be used. The interactive
interpreter is used to write one line of Python code at a time and is less convenient
to write and execute a large number of codes. Using the text editor, however, any
number of codes can be written and get executed with a single command.
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. Figure 6.1 shows the Interactive Interpreter.
Links
See Section 6.4 to learn about expressions in Python.
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.
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:
To display something on the screen, the print() function is used in Python. The
following example shows how a string is displayed using the print() function.
Notes
Note that the IDLE uses different types of colors for the different
elements of a Python code to make them easily distinguishable. By
default, outputs are displayed in blue color; functions are displayed
in purple color, and strings are displayed in green color. A string is a
sequence of characters placed under quotation marks such as ”Hello
World” as can be seen in the above example. See Table 6.1 for more
on strings and operators in Python.
Links
See Section 6.5 for more on the print() function.
Activity 6.2
• Use the print() function and display your full name on the screen using the
interactive interpreter.
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.
A script file can be easily created by selecting “New File” from the “File” menu
in the IDLE’s interactive interpreter as shown in Figure 6.2. Then the text editor is
opened in a separate window, and it looks something like what is shown in Figure
6.3.
Notes
Note that the prompt (>>>) is not shown in the text editor. The >>>
appears only when code is written in the interactive interpreter, not in
the text editor. While only one line of code is written and executed in
the interactive interpreter, as many lines of code as required can be
written in the text editor.
The example shown in figure 6.4 is a script that calculates and displays the area of
a circle for a given radius value of 3. Before the script is run/executed, the script
has to be saved with the .py extension by selecting the “save” option from the “file”
menu in the text editor. To execute the script, the “Run Module” option from the
“Run” Menu should be selected. After the script is executed, the output is displayed
in the IDLE shell/interactive interpreter in a format as shown in the figure below.
Notes
Note the following points from the script shown above:
There are four statements in the script. However, the script is executed
with a single command.
There is no prompt (>>>) in the script. The prompt is shown only in
the interactive interpreter.
Though there are four statements in the script, only one output is
shown in the IDLE shell. This is because it is only the last statement
that produces an output.
The output of a script written in the text editor is shown in the IDLE
shell or the interactive interpreter.
Links
The * is multiplication operator in Python and ** is exponentiation operator.
Operators are discussed in section 6.3
Links
See section 6.4 to learn about statements in Python.
The example in Figure 6.5 demonstrates a logic error that is related to the semantics
of programming languages.
Notes
Note that the area of a circle in the above example in Figure 6.5 is
incorrectly calculated as “area=PI*radius*2”. The correct formula for
the area of a circle is “area=PI*radius**2”. However, the interpreter
did not generate any error and simply displayed the incorrect output.
This is a logic error: even though the program does not have any
syntax error, it does not produce the intended correct output.
The * symbol serves as a multiplication operator in Python. Table 6.1
of this chapter has a list of operators in Python and examples of how
they are used.
Activity 6.3
1. What is the difference between Python’s interactive interpreter and text editor?
2. Use the print() function to display your full name on the screen using the text
editor.
6.3.1 Variables
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. The following example
demonstrates how a variable named “x” is created with the value 5 in the interactive
interpreter.
The example that follows shows how a variable named “y” is created and assigned to
the result of an expression. The value of “y” would be the sum of 5 and 9, which is 14.
Links
See section 6.4 to learn about expressions in Python.
To see the current value of a variable, you can simply type the name of the variable
and press the enter key in the interactive interpreter. The value will then be displayed
as shown in the following example.
The value 25 that is shown in blue color is the value of the variable y. Moreover, a
variable can be assigned to another value than the one it was previously assigned
to. The following example shows how the value of y is changed from 25 to 30.
6.3.2 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:
• 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. See Figure
6.6 for a list of keywords in Python.
Notes
Keywords are reserved words that have predefined meanings in a
programming language.
Notes
The first two identifiers begin with a character that is not allowed. The
third identifier used the name that is considered a keyword in Python.
The last identifier is invalid because its last character is not allowed to
be used in identifiers.
Activity 6.4
• Identify the valid identifiers and explain why they are so.
a. x
b. 1x
c. _x
d. x*y
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.
Notes
Floating point numbers are numbers with decimal points that
represent real numbers. See Table 6.1 for more on Python operators.
Built-in data types are data types that are built into the Python
language.
The data type of variables in Python is set when values are assigned to the variables.
If an integer number is assigned to a variable, the variable will be of type int. If a
string is assigned to a variable, the variable then will be of type str. The following
example in the interactive interpreter shows how data types are set to variables
based on the value assigned to the variables.
Notes
As you can see in the above example, string values should be placed
in quotation marks.
To learn the data type of a particular variable, the type() function
can be used. Simply write type(variable_name) and press enter. The
interactive interpreter displays the data type of the variable as shown
above. In the above example, the data type of the variable x is int
while the data type of the variable y is str.
The four major built-in data types in Python and their descriptions are given in
Table 6.1. The table also contains the various types of operators that apply to the
respective data types with examples of how the operators are used.
Notes
Note the following points on some of the operators listed in Table 6.1:
Variables can be assigned to values of a different data type than the one they
were previously assigned to. Therefore, the value of a variable, as well as
its type, can be changed to something different from what it was first set to
in Python. As you can see in the following example, the variable “x” is first
assigned to a floating-point number. Then it is assigned to a string value
“Hello”. The second assignment results in a change not only in the value but
also in the data type of the variable.
Activity 6.5
• Write the results of the following expressions.
a. 10%2 ________________
b. 2.5**3 ________________
c. 11//3 ________________
Type conversion is the process of converting the value of one data type to another.
Type conversion is of two types in Python: implicit conversion and explicit
conversion.
Notes
Note the following points from the above example:
The data types of x and y are int and float respectively as shown in the
example.
The variable z is assigned to the value of x+y, and its data type is
automatically set to float. This is because Python always converts
smaller data types (int in this case) to larger data types (float in this
case) to avoid data loss. If the data type of z is set as int, the value that
will be stored in it will not be the correct value.
Notes
As shown in the above example, Python does not allow adding an
integer number with a string. If the numbers stored in the integer and
the string variables are to be added up, an explicit type conversion has
to be used. See the following example to learn how the above error is
avoided using explicit type conversion.
Notes
As shown in the above example, the code did not generate any error
this time. This is because explicit type conversion is used to convert
the value of y to int type before it is added with the value of x.
Activity 6.6
• Write the expressions used to convert the value 1.5 into integer as well as
string values?
The example in Figure 6.7 demonstrates the use of assignment and print() statements
in Python.
Notes
As you can see in the output in Figure 6.7, it is only the print statement
that produces an output. The two assignment statements simply assign
values to the variables and do not produce any output.
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.
Table 6.2 shows the three types of expressions, and how they are used in assignment
and print() statements.
Table 6.2 Types of expressions
Notes
Note that the expressions in the above table are those encircled with
red.
Using the print() and assignment statements, Figure 6.8 further shows the differences
and relationships between statements and expressions in Python.
Notes
However, if any expression is written in the text editor, it will not be
displayed unless it is put inside the parenthesis of a print() statement.
Therefore, to see the value of expressions on the screen while using the
text editor, the print() function has to be used.
Activity 6.7
1. What is the difference between statements and expressions in Python?
2. Identify the statements from the following list that produce outputs.
x=4*3
y=”Programming in Python is fun”
print(y)
z=x/2
print(z)
y=10
print(type(x))
3. When the code given in activity #2 is executed, what would be the out-
put on the screen?
Programs normally accept input and process the input to produce an output. As
shown in the preceding sections, the print() function is used to produce output
on the IDLE shell. As shown in multiple examples in the preceding sections, the
print() function has the following syntax:
print([value])
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.
In the above syntax, the name of the function is print. The value that is given to the
print() function as input can be any type of expression that evaluates to some value.
See the example in Figure 6.9 for the different types of values that the print()
function can take as input.
Notes
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.
In the above syntax, the name of the function is print. The value that is
given to the print() function as input can be any type of expression that
evaluates to some value.
See the example in Figure 6.9 for the different types of values that the
print() function can take as input.
To accept input from the keyboard, the input() function is used. The input() function
has the following syntax.
variable_name=input([prompt])
Notes
The following points are important to understand how the input() function works:
The prompt that is given as input to the input() function is a string that
tells the user what kind of value the user is expected to enter. Example
“Enter an integer number”
After the user enters a value and presses the enter key, the input()
function returns the value the user entered as str type. This means that
irrespective of the type of value that the user enters, the value that
the input() function returns is of str type. Therefore, if the value that
is required is of another type, the str type should be converted to the
required type.
Example:
x=input(”Enter an integer number”)
x=int(x)
The value the input() function returns should be assigned to a variable.
This indicates that when the input() function is used, it is used as an
expression in an assignment statement.
Activity 6.8
• Write a program in the text editor that has the following elements:
° Accept the name, age, and Body Mass Index (BMI) of a person
from the keyboard using the input() function,
° Convert the values to their appropriate data type , and
° Display the values using the print() function.
The following example demonstrates how the input() and the print() functions are
used in a program. It shows how the input() function is used to accept data from the
keyboard, and how the print() function is used to display the result on the screen.
The program simply accepts the radius of a circle from the user and displays the
area and circumference of the circle.
Python Script
PI=3.14
x=input(”Enter the radius:”)
radius=float(x)
area=PI*radius**2
circumference=2*PI*radius
print(”The area of the circle is:”)
print(area)
print(”The circumference of the circle is:”)
print(circumference)
Output on the IDLE Shell
Notes
The following points are important to note regarding the program shown in
Figure 6.10:
In the example shown in Figure 6.10, a print() function is used to display each
output separately. However, if multiple values are required to be displayed in one
line, the values should be given to the print() function with comma separation. See
Figure 6.11 for the modified version of the program in Figure 6.10.
Python Script
PI=3.14
x=input(”Enter the radius:”)
radius=float(x)
area=PI*radius**2
circumference=2*PI*radius
print(”The area of the circle is:”, area)
print(”The circumference of the circle is:”, circumference)
Output on the IDLE Shell
Notes
As shown in Figure 6.11, the string literal values and the variables are
given to the print() function with comma separation. As a result, the
results are displayed in one line.
Activity 6.9
1. Write a program that accepts two numbers from the user and displays
the product on the screen.
2. Write a program that displays the BMI of a person by accepting the
weight and height from the keyboard.
Unit Summary
In this unit, you have learnt about:
Key Terms
Assembler is a software used to translate programs written in assembly
language into machine language.
Assembly Language is a low-level programming language that uses symbols/
mnemonics.
Assignment Operator (=) is an operator used to assign values to variables.
Binary System is a system in which everything is represented in terms of 1s
and 0s.
bool is a data type that represents True or False values.
Data type specifies the type of values a variable can have and the operations
defined on the values.
Explicit type conversion is a data type conversion done by the programmer
using built-in functions.
Expression is what the Python interpreter evaluates to a certain value.
float is a data type for floating-point numbers.
Floating Point Number is a number with a decimal point.
Function is a piece of code that performs some tasks.
High-level Language is a programming language closer to human language.
Identifier is the name of variables.
IDLE shell is the same as the interactive interpreter.
IDLE stands for Integrated Development and Learning Environment.
Implicit type conversion is a data type conversion done by Python without
the involvement of the programmer.
int is a data type for integer values.
Keywords are reserved words that have predefined meanings in Python.
Machine Language is a low-level programming language that the computer
understands directly.
Review Questions
Part I: Write True if the statment is correct and False if it is incorrect.
1. A program written in assembly language can be directly understood by
the computer.
2. It is only high-level programming languages that have syntax and
semantics.
3. Syntax errors are easier to fix than logic errors.
4. Python’s interactive interpreter can be used to execute multiple lines of
codes at a time.
5. When Python’s text editor is opened, the prompt (>>>) immediately
appears.
6. Once a variable is set to a specific data type, its type cannot be changed.
7. The results of the two expressions 5/2 and 5//2 are not the same.
8. In implicit type conversion, the programmer has to use built-in functions
to convert values from one type to another.
9. The data type “bool” has only two possible values.
10. Expressions and statements are the same things in Python.
Part II: Match the items given under column B with associated items in
column A
A B
1. Rules of a language a. Interpreter
2. A keyword such as str b. Compiler
3. Name of variables c. Machine Language
Part III: Choose the correct answer from the given alternatives.
3. The operand on the left side of the assignment operator (=) is always:
A. A variable B. String value
C. Integer value D. An expression
5. Identify the function that is not used for type conversion purposes.
A. int() B. type()
C. str() D. float()
4. Write a program in the text editor that converts the following two string
values into floating-point numbers and displays their product on the
screen.
”4.5” ”30.2”
5. Write a program that accepts two numbers from the user and displays the
following:
a. The sum
b. The product
c. The average value