CE 104 Chapter 2 Spr24

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

CE 104 Introduction to Programming

– Chapter 2 –
Input, Processing & Output
Dr. Tolga Ercan
İzmir Institute of Technology – Department of Civil Engineering
Spring 2023/2024

1
Program Development Cycle

There is much more to creating a program than writing code, however. The process of creating a program that
works correctly typically requires the five phases shown below. The entire process is known as the program
development cycle.

Design the Program: A program should be carefully designed before the code is actually written. When
programmers begin a new project, they should never jump right in and start writing code as the first step. They
start by creating a design of the program. We will discuss some techniques that you can use to design your Python
programs.

2
Program Development Cycle

Write the Code: After designing the program, the programmer begins writing code in a high-level language such as
Python. Recall that each language has its own rules, known as syntax, that must be followed when writing a
program. A language’s syntax rules dictate things such as how key words, operators, and punctuation characters can be
used. A syntax error occurs if the programmer violates any of these rules.

Correct Syntax Errors: If the program contains a syntax error, or even a simple mistake such as a misspelled key
word, the compiler or interpreter will display an error message indicating what the error is. Once all of the
syntax errors and simple typing mistakes have been corrected, the program can be compiled and translated into a
machine language program (or executed by an interpreter, depending on the language being used).

Test the Program: Once the code is in an executable form, it is then tested to determine whether any logic errors exist.
A logic error is a mistake that does not prevent the program from running but causes it to produce incorrect
results. (Mathematical mistakes are common causes of logic errors.)

Correct Logic Errors: If the program produces incorrect results, the programmer debugs the code. This means that the
programmer finds and corrects logic errors in the program. Sometimes during this process, the programmer discovers
that the program’s original design must be changed. In this event, the program development cycle starts over and
continues until no errors can be found.

3
Program Development Cycle - Design Process

The process of designing a program is arguably the most important part of the cycle. You can think of a
program’s design as its foundation.

The process of designing a program can be summarized in the following two steps:

• Understand the task that the program is to perform.


• Determine the steps that must be taken to perform the task

It is essential that you understand what a program is supposed to do before you can determine the steps that the
program will perform. Once you understand the task that the program will perform, you begin by breaking down the
task into a series of steps. This is similar to the way you would break down a task into a series of steps that another
person can follow.

An algorithm, which is a set of well-defined logical steps that must be taken to perform a task.

4
Program Development Cycle - Design Process

A programmer breaks down the task that a program must perform in a similar way. An algorithm is created, which
lists all of the logical steps that must be taken. For example, suppose you have been asked to write a program to
calculate and display the gross pay for an hourly paid employee. Here are the steps that you would take:

1. Get the number of hours worked.


2. Get the hourly pay rate.
3. Multiply the number of hours worked by the hourly pay rate.
4. Display the result of the calculation that was performed in step 3.

This algorithm isn’t ready to be executed on the computer. The steps in this list have to be translated into code.
Programmers commonly use two tools to help them accomplish this: pseudocode and flowcharts.

5
Pseudocode

• Programmers find it helpful to write a program in pseudocode before they write it in the actual code of a
programming language such as Python. The word “pseudo” means fake, so pseudocode is fake code. It is an
informal language that has no syntax rules and is not meant to be compiled or executed. Instead, programmers
use pseudocode to create models of programs.

• Because programmers don’t have to worry about syntax errors while writing pseudocode, they can focus all of
their attention on the program’s design. Here is an example of how you might write pseudocode for the pay
calculating program that we discussed earlier:

1. Input the hours worked


2. Input the hourly pay rate
3. Calculate gross pay as hours worked multiplied by pay rate
4. Display the gross pay

Each statement in the pseudocode represents an operation that can be performed in Python.

6
Flowchart

Flowcharting is another tool that programmers use to design programs. A flowchart is a diagram that graphically
depicts the steps that take place in a program.

• The ovals, which appear at the top and bottom of the flowchart, are called
terminal symbols. The Start terminal symbol marks the program’s starting
point, and the End terminal symbol marks the program’s ending point.

• Parallelograms are used as input symbols and output symbols. They represent
steps in which the program reads input or displays output.

• Rectangles are used as processing symbols. They represent steps in which the
program performs some process on data, such as a mathematical calculation.

The symbols are connected by arrows that represent the “flow” of the program.

7
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.

8
Displaying Output with the print Function

A function is a piece of prewritten code that performs an operation. Python has numerous built-in functions that
perform various operations. The print function, which displays output on the screen. Here is an example of a statement
that executes the print function:

In interactive mode, if you type this statement and press the Enter key, the message Hello world is displayed. Here
is an example:

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. In the previous example, the argument is 'Hello world'. Notice
the quote marks are not displayed when the statement executes. The quote marks simply specify the beginning
and the end of the text that you wish to display.

9
Displaying Output with the print Function

will produce

These are line numbers, NOT part


of the program/script

It is important to understand that the statements in this program execute in the order that they appear, from the
top of the program to the bottom. When you run this program, the first statement will execute, followed by the
second statement, and followed by the third statement.

10
Strings and String Literals

A sequence of characters that is used as data is called a string. When a string appears in the actual code of a
program, it is called a string literal. In Python code, string literals must be enclosed in quote marks. The quote
marks simply mark where the string data begins and ends.

In Python, you can enclose string literals in a set of single-quote marks (') or a set of double-quote marks (").

String literals String literals

will produce will produce

Same !
11
Strings and String Literals

If you want a string literal to contain either a single-quote or an apostrophe as part of the string, you can enclose the
string literal in double-quote marks.

will produce

Likewise, you can use single-quote marks to enclose a string literal that contains double quotes as part of the
string.

will produce

12
Comments

Comments are notes of explanation that document lines or sections of a program. Comments are part of the
program, but the Python interpreter ignores them. They are intended for people who may be reading the source
code.
In Python, you begin a comment with the # character. When the Python interpreter sees a # (dash) character, it
ignores everything from that character to the end of the line.

will produce

End-line comment

An end-line comment is a comment that


appears at the end of a line of code. It
usually explains the statement that appears in
that line.

13
Variables

A variable is a name that represents a value stored in the computer’s memory.

Programs usually store data in the computer’s memory and perform operations on that data. For example: You browse a
website and add the items that you want to purchase to the shopping cart. As you add items to the shopping cart, data
about those items is stored in memory.

A variable is a name that represents a value in the computer’s memory. For example, 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.

You use an assignment statement to create a variable and make it reference a piece of data. Here is an example of an
assignment statement:

14
Variables

After this statement executes, a variable named “age” will be created, and it will reference the value 25. Think of the
value 25 as being stored somewhere in the computer’s memory. The arrow that points from age to the value 25
indicates that the name age references the value.

An assignment statement is written in the following general format:

variable = expression

The equal sign (=) is known as the assignment operator. In the general format, variable is the name of a variable and
expression is a value, or any piece of code that results in a value. After an assignment statement executes, the
variable listed on the left side of the = operator will reference the value given on the right side of the = operator.

15
Variables

If you would like to display these values; which one you should write?
Option 1:
>>> print (width)
>>> print (length)

Option 2:
>>> print (‘width’)
>>> print (‘length’)

16
Variables

The first statement creates a variable named width and assigns it the value 10. The second statement creates a variable
named length and assigns it the value 5. Next, you can use the print function to display the values referenced by these
variables, as shown here:

When you pass a variable as an argument to the print function, you do not enclose the variable name in quote marks.

17
Variables

In the first statement, you passed 'width' as an argument to the print function, and the function printed the string width.
In the second statement, you passed width (with no quote marks) as an argument to the print function, and the function
displayed the value referenced by the width variable.

In an assignment statement, the variable that is receiving the assignment must appear on the left side of the = operator.
As shown in the following interactive session, an error occurs if the item on the left side of the = operator is not a
variable:

18
Variables

will produce

Python allows us to display multiple items with one call to the print function. We simply have to separate the
items with commas as shown.

will produce

19
Variables

WARNING! You cannot use a variable until you have assigned a value to it. An error will occur if you try to
perform an operation on a variable, such as printing it, before it has been assigned a value.

Sometimes a simple typing mistake will cause this error. One example is a misspelled variable name, as shown
here:

In this code, the variable temperature is created by the assignment statement. The variable name is spelled
differently in the print statement, however, which will cause an error. Another example is the inconsistent use of
uppercase and lowercase letters in a variable name. Here is an example:

In this code, the variable temperature (in all lowercase letters) is created by the assignment statement. In the print
statement, the name Temperature is spelled with an uppercase T. This will cause an error because variable names
are case sensitive in Python.
20
Variable Naming Rules

Although you are allowed to make up your own names for variables, you must follow these rules:

• You cannot use one of Python’s key words as a variable name. (See Table given on slides of Chapter 1)

• A variable name cannot contain spaces.

• The first character must be one of the letters a through z, A through Z, or an underscore character (_).

• After the first character you may use the letters a through z or A through Z, the digits 0 through 9, or
underscores.

• Uppercase and lowercase characters are distinct. This means the variable name ItemsOrdered is not the
same as itemsordered.

In addition to following these rules, you should always choose names for your variables that give an indication of
what they are used for. For example, a variable that holds the temperature might be named temperature, and a
variable that holds a car’s speed might be named speed.

21
Variable Naming Rules

22
Variable Re-assignment (Variables may vary!)

Variables are called “variable” because they can reference different values while a program is running. When you
assign a value to a variable, the variable will reference that value until you assign it a different value.

will produce

The statement in line 3 creates a variable named dollars and assigns it the value 2.75.

23
Variable Reassignment

Then, the statement in line 8 assigns a different value, 99.95, to the dollars variable. The old value, 2.75, is still in the
computer’s memory, but it can no longer be used because it isn’t referenced by a variable (SEE the cartoon below).
When a value in memory is no longer referenced by a variable, the Python interpreter automatically removes it
from memory through a process known as garbage collection.

24
Numerical Data Types and Literals

Computers use a different technique for storing real numbers (numbers with a fractional part) than for storing
integers. Not only are these types of numbers stored differently in memory, but similar operations on them are
carried out in different ways.

Because different types of numbers are stored and manipulated in different ways, Python uses data types to
categorize values in memory.

• When an integer is stored in memory, it is classified as an int.

• When a real number is stored in memory, it is classified as a float.

25
Numerical Data Types and Literals

A number that is written into a program’s code is called a numeric literal. When the Python interpreter reads a numeric
literal in a program’s code, it determines its data type according to the following rules:

• A numeric literal that is written as a whole number with no decimal point is considered an int. Examples are 7, 124,
and -9.

• A numeric literal that is written with a decimal point is considered a float. Examples are 1.5, 3.14159, and 5.0.

So, the following statement causes the number 503 to be stored in memory as an int:

And the following statement causes the number 2.75 to be stored in memory as a float:

26
Numerical Data Types and Literals

When you store an item in memory, it is important for you to be aware of the item’s data type. As you will see, some
operations behave differently depending on the type of data involved, and some operations can only be
performed on values of a specific data type.

WARNING! You cannot write currency symbols, spaces, or commas in numeric literals. For example, the following
statement will cause an error:

value = $4,567.99 # Error!

This statement must be written as:


value = 4567.99 # Correct

27
Storing Strings with the str Data Type

In addition to the int and float data types, Python also has a data type named str, which is used for storing strings
in memory.

first_name and last_name are now str variables.

28
Re-assigning a Variable to a Different Type

Internally, the Python interpreter keeps track of the variable names that you create and the pieces of data to which those
variable names refer. Any time you need to retrieve one of those pieces of data, you simply use the variable name that
refers to it.

A variable in Python can refer to items of any type. After a variable has been assigned an item of one type, it can
be reassigned an item of a different type.

The statement in line 1 creates a variable


named x and assigns it the int value 99.

Then, the statement in line 4 assigns a string


to the x variable. After this statement
executes, the x variable no longer refers to an
int, but to the string 'Take me to your leader'.

29
Re-assigning a Variable to a Different Type

The statement in line 1 creates a variable


named x and assigns it the int value 99.

Then, the statement in line 4 assigns a string


to the x variable. After this statement
executes, the x variable no longer refers to an
int, but to the string 'Take me to your leader'.

30
Reading Input from the Keyboard

Most of the programs that you will write will need to read input and then perform an operation on that input. Now we
will discuss a basic input operation: reading data that has been typed on the keyboard. When a program reads
data from the keyboard, usually it stores that data in a variable so it can be used later by the program.

We use Python’s built-in input function to read input from the keyboard. The input function reads a piece of data
that has been entered at the keyboard and returns that piece of data, as a string, back to the program. You
normally use the input function in an assignment statement that follows this general format:

In the general format, prompt is a string that is displayed on the screen. Here is an example of a statement that uses
the input function to read data from the keyboard:

Prompt

31
Reading Input from the Keyboard – Practice yourself

When this statement executes, the following things happen:

• The string 'What is your name? ' is displayed on the screen.


• The program pauses and waits for the user to type something on the keyboard and then to press the Enter key.
• When the Enter key is pressed, the data that was typed is returned as a string and assigned to the name variable.

will produce

32
Reading Numbers with the input Function

The input function always returns the user’s input as a string, even if the user enters numeric data. For example,
suppose you call the input function, type the number 72, and press the Enter key. The value that is returned from the
input function is the string '72’. This can be a problem if you want to use the value in a math operation. Math
operations can be performed only on numeric values, not strings.

Python has built-in functions that you can use to convert a string to a numeric type.

The int() and float() functions work only if the item that is being converted contains a valid numeric value. If
the argument cannot be converted to the specified data type, an error known as an exception occurs. An exception
is an unexpected error that occurs while a program is running, causing the program to halt if the error is not
properly dealt with.
33
Reading Numbers with the input Function

For example, suppose you are writing a payroll program and you want to get the number of hours that the user has
worked. Look at the following code:

The first statement gets the number


of hours from the user and assigns
that value as a string to the
string_value variable.

The second statement calls the int() function, passing


string_value as an argument. The value referenced by
string_value is converted to an int and assigned to the hours
variable.

34
Performing Calculations

Most real-world algorithms require calculations to be performed. A programmer’s tools for performing
calculations are math operators.

Two different
division operators !

The values on the right and left of the + operator are called operands. These are values that the + operator adds
together.

35
Performing Calculations

Variables may also be used in a math expression. For example, suppose we have two variables named hours
and pay_rate. The following math expression uses the * operator to multiply the value referenced by the hours
variable by the value referenced by the pay_rate variable:

When we use a math expression to calculate a value, normally we want to save that value in memory so we can
use it again in the program. We do this with an assignment statement.

will produce

36
Floating Point and Integer Division

Remember that Python has two different division operators. The / operator performs floating-point division, and
the // operator performs integer division. Both operators divide one number by another. The difference between
them is that the / operator gives the result as a floating-point value, and the // operator gives the result as a whole
number.

Now let’s use the // operator to perform integer division:

37
Floating Point and Integer Division

The // operator works like this:

• When the result is positive, it is truncated, which means that its fractional part is thrown away.
• When the result is negative, it is rounded away from zero to the nearest integer.

The following interactive session demonstrates how the // operator works when the result is negative:

38
Operator Precedence

First, operations that are enclosed in parentheses are performed first. Then, when two operators share an
operand, the operator with the higher precedence is applied first. The precedence of the math operators, from
highest to lowest, are:

1. Exponentiation: **

2. Multiplication, division, and remainder: * / // %

3. Addition and subtraction: + -

4. Notice 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.

The value that will be assigned to outcome is 14.0 because the division operator has a higher precedence than the
addition operator.

39
Grouping with Parantheses

Parts of a mathematical expression may be grouped with parentheses to force some operations to be performed
before others.

40
The Exponent & the Remainder Operators

• Two asterisks written together (**) is the exponent operator, and its purpose is
to raise a number to a power. For example, the following statement raises the
length variable to the power of 2 and assigns the result to the area variable:

• The % symbol is the remainder operator. (This is also known as the modulus
operator.) The remainder operator performs division, but instead of returning
the quotient, it returns the remainder.

This statement assigns 2 to leftover because 17 divided by 3 is 5 with a remainder of 2. The remainder
operator is useful in certain situations. It is commonly used in calculations that convert times or
distances, detect odd or even numbers, and perform other specialized operations.

41
Mixed-type Expressions and Data Type Conversion

When you perform a math operation on two operands, the data type of the result will depend on the data type of the
operands. Python follows these rules when evaluating mathematical expressions:

• When an operation is performed on two int values, the result will be an int.

• When an operation is performed on two float values, the result will be a float.

• When an operation is performed on an int and a float, the int value will be temporarily converted to a
float and the result of the operation will be a float. (An expression that uses operands of different data
types is called a mixed-type expression.)

When this statement executes, the value 5 will be converted to


a float (5.0) then multiplied by 2.0. The result, 10.0, will be
Int Float assigned to my_number.

42
Mixed-type Expressions and Data Type Conversion

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:

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.
After this code executes, the fvalue variable is still assigned the value 2.6, but the ivalue variable is assigned
the value 2.

As demonstrated in the previous example, the int() function converts a floating-point argument to an integer by
truncating it. As previously mentioned, that means it throws away the number’s fractional part. Here is an example
that uses a negative number:
In the second statement, the value -2 is returned from the int() function.
After this code executes, the fvalue variable references the value -2.9,
and the ivalue variable references the value -2.

43
Breaking Long Statements into Multiple Lines

If a programming statement is too long, however, you will not be able to view all of it in your editor window
without scrolling horizontally. Python allows you to break a statement into multiple lines by using the line
continuation character, which is a backslash (\).

Line continuation character

The line continuation character that appears at the end of the first line tells the interpreter that the statement is
continued on the next line.
Python also allows you to break any part of a statement that is enclosed in parentheses into multiple lines
without using the line continuation character. For example, look at the following statement:

44
Suppressing the print Function’s Ending Newline

The print function normally displays a line of output. For example, the following three statements will produce
three lines of output:

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. (You can think of the newline
character as a special command that causes the computer to start a new line of output.)

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:

will produce

45
Specifying an Item Separator

When multiple arguments are passed to the print function, they are automatically separated by a space when they
are displayed on the screen. Here is an example, demonstrated in interactive mode:

If you do not want a space printed between the items, you can pass the argument sep=‘’ to the print function, as
shown here:

46
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. For example, look at the following statement:

will produce

47
Escape Characters

The \t escape character advances the output to the next horizontal tab position. (A tab position normally appears
after every eighth character.) The following statements are illustrative:

will produce

You can use the \\ escape character to display a backslash, as shown in the following:

will produce

48
Displaying Multiple Items with the + Operator

Earlier you saw that the + operator is used to add two numbers. When the + operator is used with two strings,
however, it performs string concatenation. This means that it appends one string to another. For example, look
at the following statement:
will produce

will produce

49
Formatting Numbers

You might not always be happy with the way that numbers, especially floating-point numbers, are displayed on the
screen. When a floating-point number is displayed by the print function, it can appear with up to 12 significant
digits.

will produce

It would be nice to see that amount rounded to two decimal places. Fortunately, Python gives us a way to do just
that, and more, with the built-in format function.

50
Formatting Numbers

When you call the built-in format function, you pass two arguments to the function: a numeric value and a format
specifier. The format specifier is a string that contains special characters specifying how the numeric value should
be formatted. Let’s look at an example:
Format specifier

The first argument, which is the floating-point number 12345.6789, is the number that we want to format. The
second argument, which is the string '.2f', is the format specifier. Here is the meaning of its contents:

• The .2 specifies the precision. It indicates that we want to round the number to two decimal places.

• The f specifies that the data type of the number we are formatting is a floating-point number.

The format function returns a string containing the formatted number.

51
Formatting in Scientific Notation

Notice the number is rounded to two decimal places. The following example shows the same number, rounded to
one decimal place:

If you prefer to display floating-point numbers in scientific notation, you can use the letter e or the letter E instead
of f. Here are some examples:

52
Inserting Comma Separators

If you want the number to be formatted with comma separators, you can insert a comma into the format specifier, as
shown here:

Here is another example:

will produce

53
Specifying a Minimum Field

The format specifier can also include a minimum field width, which is the minimum number of spaces that should
be used to display the value. The following example prints a number in a field that is 12 spaces wide:

In this example, the 12 that appears in the format specifier indicates that the number should be displayed in a field
that is a minimum of 12 spaces wide. In this case, the number that is displayed is shorter than the field that it
is displayed in. The number 12,345.68 uses only 9 spaces on the screen, but it is displayed in a field that is 12
spaces wide. When this is the case, the number is right justified in the field. If a value is too large to fit in the
specified field width, the field is automatically enlarged to accommodate it.
Here is an example that specifies field width and precision, but does not use comma separators:

54
Formatting Integers

There are two differences to keep in mind when writing a format specifier that will be used to format an integer:

• You used as the type designator.


• You cannot specify precision.

In the following session, the number 123456 is printed with no special formatting:

In the following session, the number 123456 is printed with a comma separator:

In the following session, the number 123456 is printed with a comma separator in a field that is 10 spaces wide:

55

You might also like