Lesson 1 - Introduction To Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

CPE311: COMPUTER PROGRAMMING AND LANGUAGES III

(Programming in Python)

LESSON 1: INTRODUCTION TO PYTHON


Learning Outcomes:
At the end of the lesson, students should be able:
1. Explain the strengths of python programming language
2. Display output using the print() function and obtain user input using the
input() function
3. Explain the rules for naming variables
4. Use the built-in len() function to get a string's length
5. Concatenate string literals and variables using the + operator
6. Use arithmetic operators to perform calculations
7. Explain the precedence of arithmetic operators
8. Identify the error type and line number in error messages and correct them
9. Write comments and docstrings in python

1.1 The Strengths of Python

Python is a popular programming language. It was created by Guido van Rossum,


and released in 1991.

It is used for:

 web development (server-side),


 software development,
 mathematics,
 system scripting.
1.1.1 What can Python do?

 Python can be used on a server to create web applications.


 Python can be used alongside software to create workflows.

1
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software
development.
1.1.2 Why Python?

 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi,


etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.
 Python runs on an interpreter system, meaning that code can be executed as
soon as it is written. This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-oriented way or a
functional way.
Good to know

 The most recent major version of Python is Python 3, which we shall be using
in this tutorial. However, Python 2, although not being updated with anything
other than security updates, is still quite popular.
 In this tutorial Python will be written in a jupyter notebook. It is possible to
write Python in other Integrated Development Environments, such as Thonny,
Pycharm, Netbeans or Eclipse which are particularly useful when managing
larger collections of Python files.
1.1.3 Python Syntax compared to other programming languages

 Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
 Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as the
scope of loops, functions and classes. Other programming languages often
use curly-brackets for this purpose.

2
1.2 Python Outputs and Inputs
Results of computations during program execution must be displayed to the
user. These are called program outputs. Similarly, the user may need to supply
certain data to the program to aid it in carrying out its computations. Such data
are called program inputs.
1.2.1 The print() function
The print() function displays output to the user. Output is the information or
result produced by a program. The sep and end options can be used to
customize the output. Table 1.1 shows examples of sep and end. Multiple
values, separated by commas, can be printed in the same statement. By default,
each value is separated by a space character in the output. The sep option can
be used to change this behavior.
By default, the print() function adds a newline character at the end of the
output. A newline character tells

Table 1.1 Use of the print() function

3
1.2.2 The input() function

Computer programs often receive input from the user. Input is what a user enters
into a program. An input statement, variable = input("prompt"), has three parts:

1. A variable refers to a value stored in memory. In the statement above, variable


can be replaced with any name the programmer chooses.

2. The input() function reads one line of input from the user. A function is a named,
reusable block of code that performs a task when called. The input is stored in the
computer's memory and can be accessed later using the variable.

3. A prompt is a short message that indicates the program is waiting for input. In
the statement above, "prompt" can be omitted or replaced with any message.

Example of input and output statements:

Activity 1.1: Difference between source code and output

State your observed difference between the code and the output displayed
underneath.

1.3 Variables
Variables allow programs to refer to values using names rather than memory
locations. Ex: age refers to a person's age, and birth refers to a person's date of birth.

A statement can set a variable to a value using the assignment operator (=). Note that
this is different from the equal sign of mathematics. Ex: age = 6 or birth = "May 15".
The left side of the assignment statement is a variable, and the right side is the value
the variable is assigned.

4
1.3.1 Rules for Naming Variables

 A variable name can consist of letters, digits, and underscores and be of any
length.
 The name cannot start with a digit. Example: 101class is invalid.
 Variable names are case sensitive. Example: Total is different from total.
 Variable names must not have spaces between characters. Python's style guide
recommends writing variable names in snake case, which is all lowercase
with underscores in between each word, such as first_name or total_price.
 A name should be short and descriptive, so words are preferred over single
characters in programs for readability. Example: A variable named count
indicates the variable's purpose better than a variable named c.
 Python has reserved words, known as keywords, which have special
functions and cannot be used as names for variables (or other objects).

Figure 1.1 shows some of the common python keywords that should not be used as
identifiers.

Figure 1.1 Python Keywords

Activity 1.2: Variable names

Write a Python computer program that:


• Creates a variable, team1, assigned with the value "Liverpool".
• Creates a variable, team2, assigned with the value "Chelsea".
• Creates a variable score1, assigned with the value 4.
• Creates a variable, score2, assigned with the value 3.
5
• Prints team1, "versus", and team2 as a single line of output.
• Prints "Final score: ", score1, "to", score2 as a single line of output.

1.4 Python String Basics


A string is a sequence of characters enclosed by matching single (') or double (")
quotes.

Example: "Happy birthday!" and '21' are both strings.

To include a single quote (') in a string, enclose the string with matching double
quotes (").
Example: "Won't this work?"

To include a double quote ("), enclose the string with matching single quotes (').
Example: 'They said "Try it!", so I did'.

Table 1.2 Sample valid and invalid strings

1.4.1 The Python len() function on strings


A common operation on a string object is to get the string length, or the number of
characters in the string, including white spaces.
6
The len() function, when called on a string value, returns the string length.
Below is an illustration of the use of the len() function on strings.

Activity 1.3: len() function

Write a program that asks the user to input their first and last name separately. Use
the following prompts (example input in bold):
What is your first name? Alan
What is your last name? Turing

The program should then output the length of each name. Based on the example
input above, the output would be:
Your first name is 4 letters long
Your last name is 6 letters long

1.4.2 String Concatenation


Concatenation is an operation that combines two or more strings sequentially with
the concatenation operator (+).

Example: "A" + "part" produces the string "Apart"

Activity 1.4: String concatenation


Write a Python computer program that:
• Assigns the string "Freda" to a variable, name.
• Assigns the string "happy" to a variable, feel.
• Prints the string "Hi Freda!" with a single print() function using the variable name.
• Prints the string "I'm glad you feel happy." with a single print() function using the
variable feel.
7
1.5 Numbers in Python
Python supports two basic number formats, integer and floating-point. An integer
represents a whole number, and a floating-point format represents a decimal number.
The format a language uses to represent data is called a data type. In addition to
integer and floating-point types, programming languages typically have a string type,
which we have earlier considered, for representing text.

1.5.1 The type() function


Python does not require explicit data type declaration for variables. The data type of
a variable is inferred by the data stored in it. Thus, by the initial value stored in a
variable, python assumes and data type for it. Table 1.3 shows different initialized
values of a variable and the assumed data type by python.
Table 1.3 Python Assumed Data Types

Initialized Variable Assumed Data type


total = 23.5 float

age = 20 integer

first_name = ‘Thesy’ string

The type() function is used to find out of what data type is a variable name. Thus,
given the variables in table 1.3 above, the statement print(type(age)) will
return <class ‘int’> indicating that the variable age is of type integer.

Activity 1.5: Values and types


Write a Python computer program that:
1. Defines an integer variable named 'int_a' and assigns 'int_a' with the value 10.
2. Defines a floating-point variable named 'float_a' and assigns 'float_a' with the
value 10.0.
3. Defines a string variable named 'string_a' and assigns 'string_a' with the string
value "10".
4. Prints the value of each of the three variables along with their type.

8
1.5.2 Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, and division on numeric data. Table 1.4 shows the
basic arithmetic operators recognized by python:

Table 1.4: Basic Arithmetic Operators

Operator Description Usage Example

+ Addition 5+3=8

- Subtraction 5–3=2

* Multiplication 5 * 3 = 15

/ Floating point division 5 / 3 = 1.6666666666666667

// Integer division 5 // 3 = 1

% Modulo division 5%3=2

** Exponentiation 5 ** 3 = 125

1.6 Precedence of Operators


When a calculation has multiple operators, each operator is evaluated in order of
precedence. Ex: 1 + 2 * 3 is 7 because multiplication takes precedence over addition.
However, (1 + 2) * 3 is 9 because parentheses forces the precedence to be altered
such that the elements in the parenthesis are evaluated as a unit of its own.

The precedence of arithmetic operators are in the following order:

 Exponentiation has the highest precedence and is evaluated first.


 Unary negation is evaluated next, before multiplication, division, and
remainder.
 Multiplication, both types of division, and remainder are evaluated before
addition and subtraction.
 Addition and subtraction are evaluated before assignment (=).
 With two exceptions, operations of equal precedence are left associative, so
they are evaluated from left to right.

9
 Exponentiation and assignment operations are right associative, so
consecutive instances of these are evaluated from right to left.
 You can use parentheses to change the order of evaluation.

Figure 1.2: Precedence of Operators

Activity 1.6: Arithmetic Operators

Write a Python computer program that:


1. Assigns the integer value 10 to a variable, meters.
2. Assigns the floating-point value 3.28 to a variable, meter2feet.
3. Calculates 10 meters in feet by multiplying meter by meter2feet. Store the result
in a variable, feet.
4. Prints the content of variable feet in the output.

1.7 Python Error Messages


A natural part of programming is making mistakes. Even experienced programmers
make mistakes when writing code. Errors may result when mistakes are made when
writing code. The computer requires very specific instructions telling the computer
what to do. If the instructions are not clear, then the computer does not know what
to do and gives back an error.
10
When an error occurs, Python displays a message with the following information:
1. The line number of the error.
2. The type of error (Ex: SyntaxError).
3. Additional details about the error.
For example, typing print "Hello!" without parentheses is a syntax error. In Python,
parentheses are required to use print. When attempting to run print "Hello!", Python
displays the following error:
Traceback (most recent call last):
File "/home/student/Desktop/example.py", line 1
print "Hello"
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean
print("Hello")?

The caret character (^) shows where Python found the error. Sometimes the error
may be located one or two lines before where the caret symbol is shown because
Python may not have discovered the error until then.
Traceback is a Python report of the location and type of error. The word traceback
suggests a programmer trace back in the code to find the error if the error is not seen
right away.
Learning to read error messages carefully is an important skill. The amount of
technical jargon can be overwhelming at first. But this information can be very
helpful.

1.7.1 Common Types of Errors in Python Programming


Different types of errors may occur when running Python programs. When an error
occurs, knowing the type of error gives insight about how to correct the error. Table
1.5 shows examples of mistakes that anyone could make when programming.

11
Table 1.5: Common Errors in Python Programming

Activity 1.7: Error Messages 1


The following program has three errors.
 Type the program into your IDE exactly as it appears
 Run the program to find the first error, and correct the corresponding line of
code.
 Then run the program again to find and correct the second error.
 Keep running and correcting the program until no errors are found.

word = input("What is your favorite word? ')


print()
print("You said:", Word)
print("That's all, Folks!")

12
Activity 1.7: Error Messages 2
This code is based on an earlier example, but the code contains several mistakes.
• One line is missing required punctuation, and another line uses incorrect symbols.
• Run the program to find the first error, and correct the corresponding line of code.
• Keep running and correcting the program until no errors are found.

team1 = "Liverpool"
score1 = "4"
team2 = "Chelsea"
score2 = "3"

print(team1 "versus" team2)


print["Final score:" score1 "to" score2]

1.8 Comments in Python


Comments are short phrases that explain what the code is doing.

In the program segment above, lines 1, 8, and 10 contain comments. Each comment
begins with a hash character (#). All text from the hash character to the end of the
line is ignored when running the program. In contrast, hash characters inside of
strings are treated as regular text. For instance, the string "Item #1: " does not contain
a comment.

When writing comments:


• The # character should be followed by a single space.For example, # End of menu
is easier to read than #End of menu.

13
• Comments should explain the purpose of the code, not just repeat the code itself.
For example, # Get the user's preferences is more descriptive than # Input item1 and
item2.

1.8.1 Python Docstring


Python programs may optionally begin with a string known as a docstring. A
docstring is documentation written for others who will use the program but not
necessarily read the source code.

Documentation can be long, so docstrings are generally written as multi-line strings


("""). Common elements of a docstring include a one-line summary, a blank line,
and a longer description.

14

You might also like