[go: up one dir, main page]

0% found this document useful (0 votes)
6 views1 page

Computer Science 1001 - Notes 2

This document covers numeric data types and expressions in Python, focusing on variables, literals, constants, and arithmetic operations. It outlines the rules for naming variables, the types of numeric data (int and float), and the use of built-in functions for mathematical operations. Additionally, it explains operator precedence and the importance of using appropriate data types in programming.

Uploaded by

atefzohaf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views1 page

Computer Science 1001 - Notes 2

This document covers numeric data types and expressions in Python, focusing on variables, literals, constants, and arithmetic operations. It outlines the rules for naming variables, the types of numeric data (int and float), and the use of built-in functions for mathematical operations. Additionally, it explains operator precedence and the importance of using appropriate data types in programming.

Uploaded by

atefzohaf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Computer Science 1001

Unit 2 - Topic 2: Numeric Data Types and Expressions

Show All Examples Hide All Examples

Quotes

"I don't look at a problem and put variables in there that don't affect it." - Bill Parcells

"The numbers may be said to rule the whole world of quantity, and the four rules of arithmetic may be regarded as the
complete equipment of the mathematician." - James C. Maxwell

Introduction

While thinking about the problem solution you need to also think about the type of data that should be used within the
program. In addition, you must also think about how the stored data would be processed, i.e., what type of operations
can be performed on the stored data.

Objectives

To gain an understanding of

variables and their naming rules and conventions


literals
constants
data types
arithmetic expressions and operators
precedence of operators
built-in functions
math module

Variables

A variable is a named storage location(s) in a computer's memory (i.e., a variable has a name to identify it and it
holds some data value(s)). Variable names are also referred to as variable identifiers or sometimes just as
identifiers.

Show Example

Variable Names (Variable Identifiers)

The rules and conventions for naming variables in a Python program are as follows:

Variable identifiers should be meaningful names. When choosing a name for your variables, use full words instead
of cryptic abbreviations. For example, if in your program you need to use a variable identifier to hold the value for
area then use the identifier area and not a.
Python is case-sensitive hence area will be a different identifier from Area.
By convention all variable identifiers (non-constants) are spelt in lowercase. For example, area and not AREA or Area.
An identifier can be of any length, i.e., can be of an unlimited-length sequence (30 characters, 40 characters, 100
characters, ...), but conventionally use short and meaningful identifiers with all lowercase letters.
An identifier can begin with a letter or an underscore ( _ ) but the convention is to start an identifier with a letter.
Subsequent characters in an identifier may be letters, digits or underscore characters.
Python does not allow punctuation characters such as ?, /, @, $, ,, %, or blanks in the identifiers.
If the identifier consists of more than one word, the first letter of each subsequent word may be capitalized
(referred to as camel notation) or the words may be separated by an underscore( _ ). For example:
camelCase notation: salesTax, areaOfTheCircle
underscore notation: sales_tax, area_of_the_circle
Keywords or reserved words of the Python language cannot be used as identifiers. All Python keywords are
specified in lowercase. Some of the keywords are as follows:
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise

Show Example

To store a value in a variable, an assignment operator (=) is used where the value on the right-hand side of the
assignment operator is stored in the variable on the left-hand side of assignment operator. Thus, a variable is required
on the left-hand side of the assignment operator.

Show Example

The first time a variable is assigned a value, the variable is created and initialized with that value. After a variable has
been initialized (defined), it can be used in other statements. The value of a variable can be changed by reassigning a
new value to the variable.

Show Example

Note: We will study the assignment operator more in-depth in the topic on statements.

Literals

Literal values represent fixed or exact values that never change. Thus literal values, such as 7 days of a week, 4
weeks of a month or 10 dimes in a dollar, are values that remain fixed and do not change at all and can be used directly
in a program. Literals are also used to initialize the variables of a program (i.e., give them some initial value that may
change later).

Replacing input data values with literal values in a program makes it a very limited program as the program will work
only for those literal values and not for a different set of input values. To make a program more general, one that will
solve problems with any instance of the problem, one must use variables to store input values in the memory of the
computer.

Constants

A constant is a variable that holds a data value that should not be altered within the program while the program is
being executed. Constant literal values, i.e., the exact values such as 5, 0.15, .1, 3.14, "Days", are used to set up
assumption variables (these variables are also called constants or constant variables). Assumptions describe the
data values that are not given as input values, but are required and are necessary to generate the desired results. The
assumption/constant variables hold values such as, number of WEEKDAYS (5), TAXRATE (0.15), DISCOUNT_RATE (.1),
approximation of PI (3.14), etc., that do not change very often and should be used for such purposes only. The value of
such variables, once associated with the variable, should not be changed while the program is running. Some languages
have keywords which can be used to force such variables to remain constant, however Python relies on the programmer
to not change such constants after they have been assigned.

By convention the assumption/constant variables (variables holding constant literals) are specified in upper case to
distinguish them from the regular program variables.

Show Example

Data Types

Remember that the computer is an electronic device where all the programs and all data values are represented as
strings of binary digits (0's and 1's). Data types of data values provide an interpretation for this binary data so that we
can think about the data as a number or text and then use the data value appropriately. In addition, a data type also
provides a description of the operations in which the data items can participate. With numbers, operations such as
addition, subtraction, multiplication and division are common. Thus, a data type defines a set of data values and the
operations allowed on those values.

All data in Python is represented by objects (or by relations between objects). Every object has an identity (think of
this as its memory address), a type and a value. An object's identity never changes after it has been created.

The main built-in types in Python are numerics, sequences, mappings, classes, instances and exceptions.

In this unit, we will look at two of the main built-in numeric classes (int and float) that implement the integer and
floating-point data types and a text sequence class for strings (str) which implements the text string or alphanumeric
data type. Each data type has operations defined specifically for that data type. Thus, the data values stored in a
memory cell can be of many types.

Show Example

Here is a brief description of the three basic data type classes we will look at in this unit:

int: integer values which are whole numbers, i.e., without any fractional part, such as 5, 0, -9, 1038, ..., etc.
float: floating point numbers are numbers with fractional parts, such as 5.98, 3.14, 122.0, -9.0, etc.
str: string data type (alphanumeric or text data) which is a sequence of characters enclosed within (single or
double) quotes, such as "CS1001", "71 Blvd", 'Canada', "150", or "St. John's".

The data type of the value stored in the variable determines the following:

the classification or type of data (int, float, str) that the variable holds
the type of operations that can be performed on it

Note: Since the programmer does not indicate to the interpreter what type of data can be assigned to a variable, it also
means that any data type can be assigned to the same variable changing the data type of the variable and Python is
perfectly happy about that. You can inspect the type of a variable by using the type command.

Show Example

Important! Although you can assign different data types to a single variable, it is not a good practice to do so. If you
use a variable and it has an unexpected type, an error will occur in your program.

Arithmetic Expressions

An arithmetic expression is a combination of

numeric (int and/or float) operands which can be numeric data values (literals or variables) or function calls
operators that manipulate the numeric (int and/or float) data types

A simple expression is a single data value or a single variable, e.g. year or 15. Operators, variables and data values
can be combined to form arithmetic expressions. For example, a*5 where a and 5 are operands and * is the
multiplication operator.

In Python some common arithmetic operators defined for integers and floating point numbers are as follows:

(Assume that a = 15, b = 5 and c = 2.5 for each given expression in the examples column.)

Arithmetic Operators
Arithmetic
Description Examples
Operator
Adds the two operands on either side of the addition operator. a + b evaluates to 20
Addition (+)
Format: operand1 + operand2 b + c evaluates to 7.5
Subtraction Subtracts operand2 from operand1. a - b evaluates to 10
(-) Format: operand1 - operand2 b - c evaluates to 2.5
Multiplication Multiplies operand1 by opernd2. a * b evaluates to 75
(*) Format: operand1 * operand2 b * c evaluates to 12.5
Divides operand1 by operand2 and returns the floating-point a / b evaluates to 3.0
Division (/) quotient. b / c evaluates to 2.0
Format: operand1 / operand2 17 / c evaluates to 6.8
a % b evaluates to 0
7 % 2 evaluates to 1
7 % -2 evaluates to -1 (a negative divisor
Divides operand1 by operand2 and returns the remainder
here returns a negative remainder)
Modulus (%) after division.
-7 % -2 evaluates to -1
Format: operand1 % operand2
-7 % 2 evaluates to 1
c % 2 evaluates to 0.5
c % 3 evaluates to 2.5
Raises operand1 to the power of operand2 and evaluates b**2 evaluates to 25
Exponent
operand1operand2. c**2 evaluates to 6.25
(**)
Format: operand1 ** operand2 a ** 3 evaluates to 3375
a // b evaluates to 3
b // a evaluates to 0
Division of operands where the result is the quotient with the a // 2 evaluates to 7
digits after the decimal point removed. c // 2 evaluates to 1.0
Floor
If one of the operands is negative, the result is floored, i.e., c // -2 evaluates to -2.0 (not -1.0 since
Division (//)
rounded away from zero (towards negative infinity). the result is rounded away from zero)
Format: operand1 // operand2 7 // -2 evaluates to -4 (not -3.5 since the
result is rounded away from zero)
7 // 2 evaluates to 3

Note: In general, expressions with

(int operand) operator (int operand) -- returns an int result (with the exception of regular division)
(int operand) operator (float operand) -- returns a float result
(float operand) operator (int operand) -- returns a float result
(float operand) operator (float operand) -- returns a float result

Precedence (Order) of Operators in Complex Expressions

When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence.
Operators with the same precedence are evaluated from left-to-right (exponentiation is the exception to this rule).

Operator Precedence
Precedence Operator and Parenthesis Description
1 () Anything enclosed within parenthesis
2 ** Exponentiation (raise to the power)
3 + - (unary) Unary plus and minus
4 * / % // Mulitply, divide, modulo and floor division
5 +- Addition and subtraction

Operator precedence affects how an expression is evaluated.

Show Example

The order in which the operators are performed can generate different results. Thus, care must be taken in writing the
expressions.

If, for example, you wish to evaluate

a + b
2

Assuming the variable a holds the value 4 and the variable b holds the value 16, the expression should be coded as (a+b)
/ 2 and not as a + b / 2 in your program.

(a + b) / 2 will generate the value 10.0, but a + b / 2 will generate the value 12.0.

Built-in Functions

A function is a group of statements that performs a specific task which can either be user-defined or built-in.

Functions that come built into the Python language itself are called built-in functions and are readily available to the
programmer to be used directly in the program. Built-in functions are defined for numeric as well as string data types.
Here we will look at numeric built-in functions.

A built-in function is like a black box which is identified by a name that indicates the task it performs and it requires 0
or more input values to be processed. Given the required input value(s), called arguments of the function, the
function processes the input value(s) and returns a single result.

Python has several built-in functions that perform common operations that are too time-consuming, tedious and difficult
for the programmers to code every time they need to use it. Some common complex operations include finding the
square root of a function or finding the highest number amongst a large number of values. Related functions are
included in the same module of Python's library. Before the functions from a library module are used the module must
be included in the program that uses the functions. Python's math module includes a number of mathematical
functions. To use any of the math functions, the math module should be imported as follows:

import math

This makes all the math functions from the math module available to be used in the program. Or to use a specific
function to, for example, compute the square root of a number, import the function(s) from the math module and use
it, as follows:

from math import sqrt


x = 16
squareroot = sqrt(x)
print(squareroot)

Using a built-in function is referred to as calling or invoking a function. The format of any function call is:

function_name(comma-separated list of 0 or more arguments)

where

function_name is the name of the built-in or user-defined function to be used


the set of parenthesis () must follow the name of the function
inside the parenthesis there may be zero or more required arguments, separated by commas if there is more than
one argument

The function call supplies the input value(s) as argument(s) to the function. The function takes the input value(s),
performs the desired computation and returns the result to the point where the function was called.

Show Example

The common numeric built-in functions are as follows:

Common Numeric Built-in Functions


Function Explanation Examples
abs(-6) returns 6
requires a single positive or negative numeric argument and returns
abs(arg) abs(6) returns 6
the absolute value of the argument
abs(-6.5) returns 6.5
max(arg1, arg2, requires more than one argument and returns the highest value from
max(5,10,2,0,-4) returns 10
..., argn) the listed arguments
min(arg1, arg2, requires more than one argument and returns the lowest value from
min(5,10,2,0,-4) returns -4
..., argn) the listed arguments
int(10.6) returns 10
int(-10.6) returns -10
requires a single argument and converts the number or (integer-
int(arg) int("71") returns 71
looking) string argument to an integer
int("71.5") causes an error
int("71x") causes an error
float(8) returns 8.0
onverts a (number-looking) string or an integer numeric argument to float("50")returns 50.0
float(arg)
a floating point number float("50.3") returns 50.3
float("50d") causes an error
pow(2,4) returns 16
pow(arg1, arg2) returns arg1 raised to the power of arg2
similar to 2**4
round(5.5) returns 6
round(float_arg) returns the rounded floating-point value (as a whole number) round(5.8) returns 6
round(5.4) returns 5
b = "Bob" and type(b)
returns <class 'str'>
b = 5 and type(b) returns
type(variable_arg) returns the data type of a variable (object)
<class 'int'>
x = 2.4 and type(x) returns
<class 'float'>

Math Module

The math module includes several mathematical functions and mathematical constants (e.g., pi and e). All Python
math module functions are listed here: https://docs.python.org/3/library/math.html

Show Example

Important Points
A variable is a storage location inside the memory of the computer that holds a data value.
Variable names or identifiers (the variable's identity) can be thought of as the address of the storage location.
All variable identifiers must satisfy the rules and conventions of naming a variable.
Variable identifiers should be short and self-explanatory. Names should indicate how the variable is used.
Except in the case of initialization, a literal value should only be used in a program if it represents a value that is
permanent and will not ever change, such as 7 days in a week.
Use constants/constant (assumption) variables to hold the values that should remain unchanged throughout your
program.
Constants are specified using uppercase characters.
An assignment statement stores a value in a variable.
A variable is created the first time a value is assigned to the variable.
The value of a variable can be changed by re-assigning a value to the variable.
Three of most basic built-in data types for variables are: int, float or str
Integers (int data type) are whole numbers without a fractional part.
Floating point numbers (float data type) contain a fractional part.
Numeric data types (int and float), as operands, are combined with the defined operations for numeric data types
to form expressions.
Mixing int and float data types in an arithmetic expression yields a float data type.
The expressions are evaluated based on the rules of operators and their precedence.
Expressions evaluate to a single value.
Besides the arithmetic operators there are built-in and user-defined functions.
To use a built-in function, you call or invoke the function providing the required arguments.
Built-in functions can return a single value that is substituted in place of the function call.
Python has a standard library that provides functions and methods that can be used in the program.
A library module must be imported into the program before it can be used.

Prepared By: © Radha Gupta, Department of Computer Science, Memorial University of Newfoundland
(BE170731)

You might also like