Lecture 3
Lecture 3
Example output:
Numeric Data Types
• Whole numbers are represented using the integer data type (int for
short).Values of type int can be positive or negative whole numbers.
• Numbers that can have fractional parts are represented as floating point (or
float) values.
• The data type of an object determines what values it can have and what
operations can be performed on it.
• The float type only stores approximations. There is a limit to the precision,
or accuracy, of the stored values. By contrast, the int type is exact.
Numeric Data Types
fact = 1
Examples:
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5,10)
[5, 6, 7, 8, 9]
>>> range(5,10,3)
[5, 8]
Accumulating Results: Factorial
• n!=n(n-1)(n-2)…(1). Write a program that will compute the factorial of a
number entered by the user.
The limits of int
(Note that in python 2.7 or later can handle this error by automatically
changing the data type.)
Handling Large Numbers: Long Ints
• Python provides a better solution for large, exact values in the form of a third
numeric type long int.
• A long int is not a fixed size, but expands to accommodate whatever value it
holds.
• To get a long int, you put an “L” suffix on a numeric literal.
Accumulating Results: Factorial
• n!=n(n-1)(n-2)…(1). Write a program that will compute the factorial of a
number entered by the user.
Type Conversions
Notice that the final value is given as a fraction with only one
decimal place. How to output something like $1.50 ?
<template-string> % (<values>)
%<width>.<precision><type-char>
Special characters:
’\n’ - newline (as if you are typing <Enter> key on your keyboard
’\t’ - <Tab>
File Processing
Three Key steps of file-processing in all programming languages:
1.Associate a file on disk with a variable in a program. This process is called
opening a file. Once a file has been opened, it is manipulated through the variable
we assign to it.
2.Define a set of operations that can manipulate the file variable. At the very least,
this includes operations that allow us to read the information from a file and write
new information to a file.
3.When we are finished with a file, it is closed. Closing a file makes sure that any
bookkeeping that was necessary to maintain the correspondence between the file
on disk and the file variable is finished up. (For example, if you write information to
a file variable, the changes might not show up on the disk version until the file has
been closed.)
File Processing: open a file
Associate a file on disk with a variable in a program. This process is called
opening a file.
Example:
infile = open(“numbers.data”,”r”)
• Notice that strings are also objects in Python. You can invoke methods of
strings:
myString.split()
Is equivalent to
string.split(myString)