By the end of this lesson, you should be able to:
We will start this lesson by running a Python program in the Eclipse IDE that you installed in the previous lesson. You do not need to understand the first program; it is just meant to familiarize you with the programming environment. After that we will briefly discuss the basic structure of a Python program.
In the next section of this lesson the input and output functionality of Python will be discussed, and we will also perform basic processing to make programs useful. Errors, variables and datatypes will be introduced, and later we will also learn about typecasting from one datatype to another and about formatted output. I hope you will find this lesson an exciting one.
We understand that we have students with a wide range of computing experience. Some of you might have a variable degree of programming experience but there are also those who will program for the first time in this course.
Start by copying and running the following program in Eclipse. You may not understand this program for now and that is fine. The purpose of the program is to test your Python installation and to introduce comments. Please consult Lesson 1 of the course if you need any help in running the program.
# Program Name: Prog 2-01
# This program is part of Lesson 02 of the programming course
quote = input("Enter your favorite quote: ")
print("Quote written in reverse:", quote[::-1]) # Prints the quote in reverse
print ("********* Program Ending *********")
This program shows the use of comments. Understanding of the code is not required at the moment.
The following shows sample output from executing the program. The quote entered by the user is underlined.
Enter your favorite quote: Those who live in the past limit their future. Quote written in reverse: .erutuf rieht timil tsap eht ni evil ohw esohT ********* Program Ending *********
Comments are included in programs as documentation and explanations that can help you or someone else who is reading the code to understand the logic used. When you start writing complex programs, you will like to read your own comments when you go back to your code after a few months.
The first two lines of Code Listing 1 are comments.
Every comment starts with a pound symbol (
#
). This symbol tells the Python Interpreter that any text
written after the
#
is part of a comment and is ignored during execution. There is
also a comment on line 5. This comment follows executable code.
Empty lines are ignored by the Python interpreter. All other lines are treated as code and the Python interpreter attempts to execute them.
Anyone reading this code can see the comments and know that the program name is Prog 2-01 and it is part of the second lesson. The comment on line 5 tells us that this line of code implements the functionality to reverse and then print a quote. (You do not need to know how it does so.) We discuss string processing in detail in a later Lesson.
Lines of codes or statements in a computer program can be broadly categorized into three categories:
Input statements get data from an external source, and pass it on to the program for processing. This input can come from a variety of sources like keyboard, mouse, a computer file, or sensor etc. In this course we use the keyboard and computer files for input.
Processing Statements are a major part of a computer program. They implement the logic that processes input and turns it into useful information.
output statements display information on the screen, or print some data on a printer, or store data on a computer file, etc. In this course we output textual data on the console (computer screen) and also store (output) it in computer files.
Figure 1 shows the relationship between the three categories of statements.
Data is taken from the user and after processing it is displayed through the output statements.
An Algorithm is a list of well-defined computer instructions used to solve a problem. A non-technical example of an algorithm can be a cooking recipe or the directions given in a textual format by Google Maps. A recipe, for example, provides a step by step guide to prepare a dish and includes precise details like cooking time and measurements of each ingredient.
Similarly, a list of statements that implement an algorithm using a programming language like Python is called a computer program or source code or just code. Page Rank is an example of a computer algorithm. It is used by Google to order webpages.
We look at basic statements to perform input and output in this section. In a later section we revisit input and output to see some advanced examples.
input
is a built-in Python function that prompts a user to enter a
value. The following is a simple program that demonstrates the
use of the
input
statement by accepting three inputs from a user. It asks the
user to enter a first name, current semester and year from a
keyboard. After executing the three input statements, the
program does not perform any other processing or any output.
firstname = input("Enter your name: ")
term = input("Enter term (Fall/Winter/Spring): ")
year = input("Enter year: ")
Let us dissect line 1 of this program:
firstname
=
firstname
.
input ("Enter your name: ")
input
is the name of a built in function in python. A built-in
function provides a basic functionality that we can use in our
programs. For example, taking input from the user is a common
task that is required in a lot of computer programs. So the
code that is needed to take input from the user has been
programmed and stored in a function called
input
.input
function. In line 4 the
input
function accepts input from the user and after the user has
entered the data, that data is assigned to the programmer
specified variable
firstname
.
Every function has a distinct name, and to execute it that name
is followed by a pair of parentheses.
"Enter your name: "
is a string literal provided to the function as an
argument. A function may or may not have arguments. We will
discuss Python functions in detail in a later section. For now
we only need to understand that
input
is a function name which displays the user provided string
without the double quotes (in this case:
Enter your name:
) and halts the execution of the program for wait for input from
the user. Once the user has entered some data it is assigned to
the programmer specified variable.
The following shows a sample run of this program.
Enter your name: Harris Enter term (Fall/Winter/Spring): Fall Enter year:
The example shows that the user has provided input for the first
two input statements. The name "Harris" is assigned to the
variable
firstname
and "Fall" is assigned to the variable
term
. Quotes are used around Harris and Fall (in the description
above) to denote that they are string literals. The
input
function always reads data from the console as text. This
textual data is called string in Python.
The user has not entered anything for the third call to the
input
function. The Python interpreter is waiting for the user to type
some text and press the return key to continue the program.
There is a built-in function to output data on the console as
well. The name of the function is
print
. As required, the function name is always followed by a set of
parentheses and the data to be displayed is put inside the
parentheses. Calling
print
with empty parentheses outputs an empty line. Let's look at some
code to understand output statements:
firstname = input("Enter your name: ")
term = input("Enter term (Fall/Winter/Spring): ")
year = input("Enter year: ")
print("**** Starting to Print ****")
print()
print(firstname)
print(term, "term in", year)
This program takes input from the user then outputs it without any further processing.
Lines 1 to 3 are the same as in Code Listing 1. We are taking input in these lines and assigning the user entered values to the programmer specified variables.
Lines 5 to 8 are output statements. The calls to the
print
function perform output to the console but do not generate
anything that can be stored in variables. This is why there is
no assignment operator (
=
) in these output statements. (The result of a
print
cannot be usefully stored in a variable in any case.)
firstname
is displayed. As we are using a variable name as an argument
to the
print
function we do not use any quotes. We simple state the
variable name. The contents of variable, rather than its name,
are printed on the console.
print
function to display multiple elements. The elements are
separated from each other using a comma. In this case we are
displaying:
term
term in
is printed as is. Note that
we used double quotes in this case. We can used either
single quotes or double quotes when printing string
literals
year
Enter your name: Maria Enter term (Fall/Winter/Spring): Spring Enter year: 2023 **** Starting to Print **** Maria Spring term in 2023
Let us include some processing statements to the input and output statements. The program below calculates a total salary and the difference of salaries for the months of June and July:
employee_id = input("Enter Employee ID: ")
june_salary = 1500
july_salary = 1300.75
total = june_salary + july_salary
difference = july_salary - june_salary
print("Salary Information for", employee_id)
print("Total:", total, "and difference:", difference)
Shows input, processing and output in a single program. The total and difference of salaries is calculated and displayed to the user.
employee_id
. As is the case for all the user
input
taken using the input function, the data is read as a string.
june_salary
and
july_salary
. These salaries are not being entered by the user but instead
they are hard coded into the program. The values for salaries
are not inside single quote or double quotes, which means they
are numbers and not strings. A statement like the
following would have turned 1500 into a string:june_salary = "1500"
total
and the difference to the variable
difference
.
Enter Employee ID: 12345 Salary Information for 12345 Total: 2800.75 and difference: -199.25
Errors and bugs are a common occurrence for programmers. As you start writing code you will realize that you run into errors quite often. This is absolutely fine. Experienced programmers also produce bugs frequently, and it is part and parcel of being a programmer.
Debugging is the process of finding bugs in your programs and sorting them out. Whenever an error occurs in your program and you use messages produced by Python Interpreter to track the error and fix it, you are practicing bug fixing. Initially it takea time, DO NOT be disheartened, it is supposed to take time in the start. Finding a bug is part of the learning process. You can only be good at programming if you remain resilient and patient while dealing with bugs.
There are two kinds of errors.
These are the language mistakes made by a programmer while writing code in a programming language like Python. It is similar to making a spelling error or a typo in text that you write. The good thing about these errors is that the Python Interpreter is going to help you and provide useful messages to track and sort out these errors.
Table 1 provides examples of the some common syntax errors:
Code | Python Error Message | Description |
---|---|---|
|
Print("Monday") NameError: name 'Print' is not defined |
Python warns us that the name 'Print' is not defined.
The function name is actually print (with a
lower-case p).
|
|
print("Monday) ^ SyntaxError: EOL while scanning string literal |
EOL stands for End of Line. It seems that we started a string with double quotes but there are no double quotes to end a string. Any string that is started must end too with quotes. |
|
print(salary_june) ^^^^^^^^^^^ NameError: name 'salary_june' is not defined |
The 2nd line of code has a print statement and salary_june
is written without any quotes. It means it should be a
valid variable name but the actual name that is used in
the program is june_salary |
|
total = sal1 + sal2 ~~~~~^~~~~~ TypeError: can only concatenate str (not "int") to str |
Python complained that on line 3 you are trying to add a string and a number. It seems that the bug exists on line 1 where we have used quotes to make 1500 a string rather than keeping it as a number. There should be no quotes around 1500. |
|
print("salary" sal1) ^^^^^^^^^^^^^ SyntaxError: invalid syntax. Perhaps you forgot a comma? |
Python hints strongly that we did not add a comma after
the string "salary" to separate it from the variable sal1 .
|
For logic errors you are on your own without any help from the Interpreter. Python will not detect or complain about logical errors, it will execute the program fine and produce the output but that output will be incorrect. Logical error means that the algorithm that is used in the program is wrong. Let's understand it with a simple example. Prog 2-05 in Code Listing 5 shows code for calculating average of three quizzes.
score_quiz1 = 4
score_quiz2 = 8
score_quiz3 = 6
total = score_quiz1 + score_quiz2 + score_quiz3
average = total / 2
print("Average of three quizzes is", average)
A logic error while calculating average of three values.
Lines 1 to 3 assign marks to variables for each of three quizzes. Note that the quiz marks are entered without any quotes around the data. That means they are numbers and not strings and therefore mathematical operations can be performed on them.
Line 5 computes the sum of the three quizzes and assigns the
result to the variable
total
. Line 6 computes the average but rather than dividing
total
by 3, the programmer made a logical error and divided the sum by
2. Python executes the code successfully and assign the result
to the variable
average
but the result is incorrect. We end up with an average of 9.0
rather than 3.0.
You have already used variables. Variables are a key component of programming. A programmer can assign a value to a variable and then that value can be retrieved and used anywhere in the code using the variable name. Values assigned to a variable can be updated in the program and the latest value is always accessible through the same variable name. This assists programmers to write generic and modular programs that can be used with a range of input data.
Users have the freedom to name the variables but certain rules apply. Python enforced rules must be followed or else we can end up with a syntax error. There are also some guidelines of good programming practice that are highly recommended. Let's first look at the Python enforced rules for naming variables.
Some valid variable names can be:
first_name
,
_firstname5
,
_first_21name
,
_Firstname
,
Firstname1_
Note - Python reserved keywords are listed below. Do not use them as variable names.
and | as | assert | break | class | continue |
def | del | elif | else | except | exec |
finally | for | from | global | if | import |
in | is | lambda | not | or | pass |
raise | return | try | while | with | |
yield |
A constant is a value that you know before a program
even runs. It is a named value that does not change, or at least
does not change while a program is executing. Named constants
make programs and functions easier to read and write.
Mathematical values such as
pi
and
e
are constants, physical values such as
c
(the speed of light in a vacuum), and the acceleration due to
gravity close to the earth (\(9.8 {m/s}^2\)) are also constants.
Values such as sales tax percentages can be treated as constants
while a program is executing, but constants such as these may
have to be updated between program executions if the sales tax
is changed by the government.
If you have to ask a user for the value, or read it from a file or a database, it is not a constant.
Unlike many other programming languages, Python does not have a true constant. You can, however, simulate a constant through coding standards. Use all capitals for its name (you may still use numbers and underscore) in order to make the name stand out. (This is the Laurier Way.) NEVER CHANGE THE VALUE OF THIS CONSTANT.
Define constants at the beginning of a module. (i.e. define the constant before any executable code.) In order to be visible a constant must either be defined in the same module in which it is used, or imported into the module in which it is to be used. (Importing is discussed later.)
In the following example, the constant
GRAVITY_ACCEL
is defined in the module
gravity.py
:
"""
According to Newton's Law the force of gravity for objects
near the earth is mass times acceleration. Acceleration due
to gravity (for the earth) is 9.8 m/s^2.
"""
# Constants
GRAVITY_ACCEL = 9.8 # m/s^2
# Inputs
mass = float(input("Enter mass (kg): "))
time = int(input("Time falling (s): "))
# Calculations
force_calc = GRAVITY_ACCEL * mass
final_velocity = GRAVITY_ACCEL * time
# Outputs
print()
print(f"Force: {force_calc:.2f} kg m/s^2")
print(f"Final velocity: {final_velocity:.2f}")
In this example the constant
GRAVITY_ACCEL
is used in two different calculations. Good naming makes the
code more readable, and defining the value in only one place
makes it easier to change the calculations - in this case, for
example, to add more decimals of accuracy to the value.
All of these previous example constants refer to real-world
properties that can be 'named'. What about values that are more
difficult to name? For example, conversion from Celsius to
Fahrenheit involves the formula:
fahrenheit = 9 / 5 * celsius + 32
The value 32 is the Fahrenheit freezing point of water,
and could be given a name - for example,
FAHRENHEIT_FREEZING
. However, the ratio
9/5
is just a mathematical ratio. That's fine - we can give it a
name that makes it clear it is a ratio:
# Constants
FAHRENHEIT_FREEZING = 32
F_C_RATIO = 9 / 5 # Fahrenheit to celsius ratio
fahrenheit = F_C_RATIO * celsius + FAHRENHEIT_FREEZING
Note the use of an in-line comment to make the meaning of the constant clearer. Further, you do not have to actually calculate the ratio - simply state it and let Python calculate it for you.
What about inconstant constants? i.e. can values that do not arise from fundamental properties of the universe be treated as constants? If these values change only rarely, and never during a particular program run, yes. Tax rates, for example, even though they do change upon occasion (particularly when a government is looking for votes), are unchanged long enough to be treated as constants for most programs. When a tax change is announced, then the program must be updated to match.
# Constants
HST = 13 / 100 # Harmonized Sales Tax % in Ontario
price = float(input("Enter price: $"))
total = price + price * HST
print(f"Total cost: ${total:.2f}")
Again, the use of a common acronym for a constant makes this program more readable and easier to update.
X
and
Y
are rarely good names, except perhaps in certain formulas. Add
an in-line comment to the constant definition if it helps.
_
).
# Constants
Variables that we declare are assigned a value. This value can be of different types. In this section we discuss strings and numbers.
The Python name for the string datatype is
str
. Strings are composed of one or more characters defined between
quotes. A character can be a letter in the alphabet, a digit, a
symbol, or a combination of these. Strings can be indicated in
Python by enclosing a value in single quotes, double quotes, or
triple quotes. The following program demonstrates some examples
of using strings:
my_university = "Wilfrid Laurier University"
date_established = "1960"
former_name = 'Waterloo Lutheran University (1960-73)'
brief_history = '''Wilfrid Laurier University (commonly referred
to as WLU or simply Laurier) is a public university in Waterloo,
Ontario, Canada. Laurier has a second campus in Brantford,
Ontario, and recently has opened a third campus in Milton.
(Wikipedia)'''
print(my_university, date_established, '[', former_name, ']')
print('--------------------------------')
print("Brief History")
print(brief_history)
my_university
. We know the datatype of the variable
my_university
is
str
because the value assigned to this variable is between double
quotes. The value consists of letters in the alphabet and
spaces.
date_established
.
1960
looks like a number, but note that it is inside two single
quotes. Therefore, Python treats it as text and therefore the
datatype of the variable is
str
. You cannot apply mathematical operations to this variable.
former_name
. Again single quotes are used to specify
str
datatype, but this string contains a combination of letters in
the alphabet, symbols, spaces, and digits.
brief_history
. As it is long string and we want to break it into multiple
lines, we used triple quotes to enclose all the text.
Triple quotes allow us to write multiline strings. Note that
triple quotes may consist of matching pairs of either three
single quotes (
'''
) or of three double quotes (
"""
).
brief_history
is displayed on the console. Line structure is maintained
while printing.
We now know that to create strings we can use single, double, and triple quotes. But what if we want to make quotes part of the string? For example, consider the following sentences:
When we have situations like the above, we can either alternate
the use of single, double or triple quotes or take advantage of
the escape character. The backslash '
\
' is an escape character that we can use inside strings. An
escape character changes the meaning of the character appearing
immediately afterwards. See:
print("This is Mary's car")
print('This is Mary\'s car')
print('''To David's question she answered "We are expecting rain today".''')
print("To David's question she answered \"We are expecting rain today\".")
print('This is a single backslash \\ in a string.')
\'
results in printing a single because
\
is the escape character.
This is Mary's car This is Mary's car To David's question she answered "We are expecting rain today". To David's question she answered "We are expecting rain today". This is a single backslash \ in a string.
Escape character can be used for string formatting as well. Some common escape sequences follow:
Escape Sequence | Explanation |
---|---|
\\ |
Prints a single backslash |
\n |
Line feed. Starts a new line |
\t |
Horizontal tab. Skips one tab in the current line |
The following program demonstrates the use of these escape sequences:
print("Total Price:\t$15")
print("Printing on line 2\nand\nprinting on line 4")
\n
appears inside a string.
Total Price: $15 Printing on line 2 and printing on line 4
Numbers can be Integers or Floating Point
Numbers. The Python name for Integers is
int
and for floating point numbers is
float
. Ints are whole numbers without a decimal point. Floats have a
decimal point. We can apply mathematical operations to ints as
well as floats.
Every variable has a datatype. We know when we use quotes the variable stores a string. When a whole number is specified, the variable stores an integer, and when a decimal point is used in a value, the variable stores a float.
Code | Datatype | Python Name |
---|---|---|
cash_available = 9 |
Integer | int |
cash_available = 9.5 |
Floating Point | float |
cash_available = 9.0 |
Floating Point | float |
cash_available = '9' |
String | str |
When we perform mathematical operations the result is assigned
to a variable, and the datatype of that variable is decided
based on the type of operation and the datatype of the operands.
(Note:
*
* is used in Python for multiplication.)
Operand 1 | Operator | Operand 2 | Example | Result | Result Datatype |
---|---|---|---|---|---|
int |
+,-,* | int |
result = 5 + 6 |
11 | int |
int float |
+,-,* | float int |
result = 5 - 6.0 |
-1.0 | float |
float |
+,-,* | float |
|
34.552 | float |
int |
/ | int |
result = 5 / 1 |
5.0 | float |
int |
// | int |
result = 10 // 3 |
3 | int |
float |
// | int |
result = 10.4 // 3 |
3.0 | float |
float |
/ | float |
result = 6.7 / 8.1 |
0.8271604938271605 | float |
float int |
/ | int float |
|
0.9333333333333332 | float |
In short the result is always
float
if any of the operands is
float
or if non-integer division is being computed. The result is
int
only when both the operands are
int
and the operation is either addition, subtraction,
multiplication or integer division
//
Before we continue, we need to know about another built-in
function that returns the datatype of a given variable.
type
is the built-in function and it requires a variable argument.
The function returns the datatype of the variable. The following
program shows an example of mathematical operations and prints
the datatypes of various variables:
op1 = 5
op2 = 2
result = op1 + op2
print("Operation\t op1 type\t op2 type\t\t result type")
print("Addition\t", type(op1), "\t", type(op2), "\t\t", type(result))
op1 = 5
op2 = 2.1
result = op1 + op2
print("Addition\t", type(op1), "\t", type(op2), "\t", type(result))
op1 = 5
op2 = 2
result = op1 / op2
print("Division\t", type(op1), "\t", type(op2), "\t\t", type(result))
op1 = 5
op2 = 2
result = op1 * op2
print("Multiplication\t", type(op1), "\t", type(op2), "\t\t", type(result))
We encourage you to extend the program and experiment with different variations of operands and operations. It will help you understand how Python assigns datatypes as a result of mathematical operations.
Operation op1 type op2 type result type Addition <class 'int'> <class 'int'> <class 'int'> Addition <class 'int'> <class 'float'> <class 'float'> Division <class 'int'> <class 'int'> <class 'float'> Multiplication <class 'int'> <class 'int'> <class 'int'>
The tab escape sequence
\t
structures the output into a table. It is much easier to scan
the data and understand it. Note that on line 11 uses a single
\t
as the fifth argument whereas for all the rest of the print
statements it was
\t\t
. Change the code and experiment to understand why did we do it.
In type casting we convert a value from one datatype to another datatype. You must take care when performing type casting, as it is error prone and it may also result in loss of precision. We can convert each of the three datatypes we looked at (integer, float, and string) into any of the other datatypes given it is permissible depending upon the value.
We have built-in functions to perform type casting. The
int()
function converts string or a float into an
int
. A string must consist of only digits to be successfully
converted into an integer. An error occurs if the string
contains anything other than digits.
For example, '900' can be converted into an integer, but '90.2' or '9A' cannot. Typecasting a float into an integer drops the decimal portion. For example, if we typecast 9.9 to an integer it becomes 9 after conversion.
The
float()
function converts strings or integers into a
float
. In this case a string must consist of only digits and an
optional period. Period is optional though. An integer converted
into a float simple has .0 added to its end.
Anything can be converted to a string by the function
str()
.
The following table shows examples of typecasting:
Typecasting | Code | Result |
---|---|---|
String to Integer | int("9") |
9 |
String to Integer | int("9.0") |
Error |
String to Integer | int("9A") |
Error |
Float to Integer | int(9.0) |
9 |
Float to Integer | int(9.99) |
9 |
String to Float | float("9") |
9.0 |
String to Float | float("9.2") |
9.2 |
String to Float | float("9.2[data]") |
Error |
Integer to Float | float(9) |
9.0 |
Integer to String | str(9) |
"9" |
Float to String | str(9.99) |
"9.99" |
String to String | str("99.9 unchanged") |
"99.9 unchanged" |
We return back to the problem we mentioned earlier that the
input
function always returns a string. If we want the data read from
the user as an integer or a float we must convert it into an
appropriate datatype so we can perform mathematical operations
on the data. The following code converts user input into
int
and
float
. An error occurs if the user enters incompatible data.
test_integer = int(input("Enter a whole number: "))
test_float = float(input("Enter a floating point number: "))
The standard rules of precedence apply when these lines of code
are executed. The expression on the right of the assignment
operator is executed first and the final result is assigned to
the variable on the left. On the right side of the assignment
operator, whatever is inside the brackets is executed first.
Thus the
input
function is executed first and the string it gets from the user
is passed to the surrounding
int()
or
float
which perform the appropriate conversions.
The following code shows sample input statements and conversions. You are encouraged to run the program with different inputs, but for the sake of practice predict the output before seeing the output generated by the program.
test_string = input("Enter a string: ")
test_float = float(input("Enter a floating point number: "))
test_integer = int(input("Enter a whole number: "))
test_var = int(test_string)
print("[String->Int]\tResult is", test_var, "with datatype", type(test_var))
test_var = int(test_float)
print("[Float->Int]\tResult is", test_var, "with datatype", type(test_var))
1
test_var = float(test_string)
print("[String->Float]\tResult is", test_var, "with datatype", type(test_var))
test_var = float(test_integer)
print("[Int->Float]\tResult is", test_var, "with datatype", type(test_var))
1
test_var = str(test_integer)
print("[Int->String]\tResult is", test_var, "with datatype", type(test_var))
test_var = str(test_float)
print("[float->String]\tResult is", test_var, "with datatype", type(test_var))
Sample program results:
Enter a string: 4500 Enter a floating point number: -9 Enter a whole number: 4 [String->Int] Result is 4500 with datatype <class 'int'> [Float->Int] Result is -9 with datatype <class 'int'> [String->Float] Result is 4500.0 with datatype <class 'float'> [Int->Float] Result is 4.0 with datatype <class 'float'> [Int->String] Result is 4 with datatype <class 'str'> [float->String] Result is -9.0 with datatype <class 'str'>
Formatted output is a powerful tool to customize output. This allows the programmers to present the data to the user in the most effective and readable manner. Formatted output separates the data from the string and therefore makes is easier to manage.
Python has three methods to define formatted strings, but we are only going to use and demonstrate one: f-string formatting or formatted string literals. This is a Python string enclosed in a pair of single quotes, double quotes, or triple quotes preceded by the character "f". This string may contain literals, values enclosed in brace brackets ({}), and (optionally) formatting codes within the brace brackets.
item = "apples"
bought = 3
cost = 2.5
total = bought * cost
# f-string method
print(f"{bought:d} {item} at ${cost:.2f} each cost ${total:.2f}")
which produces:
3 apples at $2.50 each cost $7.50
The formatted print statement consists of a single string with string literals and four format fields. These fields:
{bought:d}
bought
as an integer.
d
is the Python format code for
int
.
{item}
item
. If no formatting code is provided, Python prints the
variable value as given. This format could have been written
as
{item:s}
, where
s
is the Python format code for
str
, but it isn't necessary in this case
{cost:.2f}
float
with 2 decimal places, where
f
is the Python format code for
float
.
{total:.2f}
See: Python 3's f-Strings: An Improved String Formatting Syntax.
As we have seen in the above example, the formatting is achieved through format fields. A format field consists of {variable[:optional_format_specification]}, which tells the print function to output the variable value in format defined by the optional_format_specification, if defined. If the optional_format_specification part is omitted, it outputs the variable by its default default.
Let's discuss some examples of the code that we can put the format specifications inside the curly brackets to format the variables. The following are some sample formatting fields and their descriptions:
Format | Description |
---|---|
{:,f} |
f - the data is printed as float, - commas are be placed in the number
(separating groups of three digits) to enhance readabilityFloating point numbers are right justified by default. |
{:.2f} |
.2 - two digits are displayed after the
decimal point. Digits beyond two are be rounded off. If
there are fewer than two digits in the number, 0's are
appended after the decimal point. |
{:,.1f} |
A float with one digit after the decimal
point is displayed and commas are placed in the number.
|
{:,d} |
d - An integer is printed with
commas placed. Integers are right justified by default. |
{:10,d} |
10 - 10 characters are reserved for
displaying the integer. Extra spaces are left blank for
integers with fewer than 10 digits. In case of more digits
the number is not truncated, extra space characters are
used to accommodate the number. |
{:8,.1f} |
a float is displayed with one digit after
the decimal point and commas separators are used. The
entire number (digits, commas, and decimal) is printed
with a width of 8 characters.
|
{:06d} |
Integer are printed with 6 characters reserved for display. Empty space on the left of the number is filled by 0s. |
Some formatting examples:
long_float = 78921.9876
long_int = 12345
print(f"{{long_float:,f}} = {long_float:,f}")
print(f"{{long_float:.2f}} = {long_float:.2f}")
print(f"{{long_float:,.2f}} = {long_float:,.2f}")
print(f"{{long_float:,.1f}} = {long_float:,.1f}")
print(f"{{long_int:,d}} = {long_int:,d}")
print(f"{{long_int:10,d}} = {long_int:10,d}")
print(f"{{long_int:010,d}} = {long_int:010,d}")
Note: brace brackets (
{
and
}
) can be printed within an f-string by using double
brace-brackets (
{{
and
}}
) as demonstrated in the sample execution:
{long_float:,f} = 78,921.987600 {long_float:.2f} = 78921.99 {long_float:,.2f} = 78,921.99 {long_float:,.1f} = 78,922.0 {long_int:,d} = 12,345 {long_int:10,d} = 12,345 {long_int:010,d} = 00,012,345
Using a consistent format width and number of decimals makes it easy to print a table. Add spaces after titles to make things line up, as in this example:
breakfast = 10.95
lunch = 23
dinner = 125.21
print("Meal Price")
print(f"Breakfast {breakfast:7.2f}")
print(f"Lunch {lunch:7.2f}")
print(f"Dinner {dinner:7.2f}")
Meal Price Breakfast 10.95 Lunch 23.00 Dinner 125.21
In the last example we use the
%
symbol to print percentages:
score = 0.819
print(f"{{score:.0%}} : {score:.0%}")
print(f"{{score:.2%}} : {score:.2%}")
print(f"{{score:4.0%}}: {score:4.1%}")
{score:.0%} : 82% {score:.2%} : 81.90% {score:4.0%}: 81.9%
In this lesson, we learnt how we can combine input, output, and processing statements to make basic programs. We practiced input typecasting and formatted output to make our programs dynamic and more useful.
In this week’s assessments, you learnt more about formatted output and also get a chance to practice. The exercise will reinforce the concepts covered in this lesson and in the textbook. In the next lesson you will learn more about mathematical operations, problem solving and Python’s math lesson.
We hope you are ready to attempt this week’s quiz and exercise. They are available on MyLearningSpace. Consult the syllabus for clarity about the deadlines for preparation activities, quizzes, and exercises/assignments. Please regularly visit the MyLearningSpace for announcements, course material and discussion boards.