What three functions can be used to get the integer floating-point number or string version?

The goal for this week is to become comfortable with four basic data types in python: integers, floats, strings, and lists. By now you should be familiar with some basic linux (cd, ls); the emacs editor; editing, saving, and running python files in your cs21 directory; recognizing the linux shell ($) and the python shell (>>>), and running basic python commands in the python shell. On the python side of things we talked about print(), raw_input(), saving data in variables, and the basic structure of a program (descriptive comment, definition of function, calling the function). If you have any questions about these topics, please let me know. We will be building on them this week.

Numbers

Two types: integers or whole number and floating point or decimal numbers.

Built in operations: + (addition), - (subtraction), * (multiplication), / (division), ** (exponentiation), % (remainder or mod), abs() (absolute value).

One tricky thing about python is that if a mathematical expression involves only integers, the result must be an integer. If an expression has at least one floating point number, the result is a float. Floating point numbers are approximations to real numbers. Usually this approximation is good enough (unless you are flying a spacecraft to Mars or trying to forecast the path of a Hurricane), but the answers may surprise you.

You may want to convert an int to a float. This can be done via casting using e.g., float(3). Alternatively, if we remember that an operation involving a float and an int returns a float, we can convert a possible integer variable val to a float using val=1.0*val, or val=1.*val.

What is the output of the following expressions? Are any expressions invalid? Are any results surprising?

int("3") int("3.2") float("3") float("3.2") str(3) str(3.2) 3/2 float(3/2) float(3)/2 3.0/2 3*1./2 5%4 6%4 8%4 7.2%4

You can import additional math functions from the math library.

>>> from math import * >>> pi 3.1415926535897931 >>> sqrt(2) 1.4142135623730951 >>> sin(pi/4) 0.70710678118654746 >>> sin(pi/2) 1.0 >>> import math >>> help(math) #displays all functions available to you.

If you need to import additional feature use the from <library> import * at the top of your program. You only need to import a library once. If you want to get help on a library, start a python shell, run import <library> followed by help(<library>).

Lists

We now introduce a new data type, the list, which can store multiple elements. Run the following range commands in the python shell. Remember to start python by typing python from the linux prompt. cumin[~]$ python Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> range(5) [0, 1, 2, 3, 4] >>> #List types. A list of what? range(5) range(1,5) range(1,5,2) Think about the following questions and discuss them with a neighbor:
  • What is the syntax for a python list? What symbols mark the beginning and end of list and what symbol separates items in a list
  • The range function can be called at least three different ways (one, two, or three arguments). What are the semantics for these three versions of range? Are there more ways to call range? What type of data can you supply as arguments to range?
  • Try to create calls to range that generate the following lists. It may not be possible to generate all lists shown below.
[2, 4, 6, 8] [-1, 0, 1, 2, 3] [0, 3, 6, 9, 12] [1, 1.5, 2, 2.5] [4, 3, 2, 1, 0] [1, 2, 4, 8, 16]

Loops

Just generating lists can be pretty boring, but we can loop over a list to have python execute code multiple times. This construct is called a for loop and it has the following syntax: for <var> in <sequence>: <body> Whitespace is significant. Loop body starts when indentation starts. Loop body ends when indentation ends. for i in range(1,5,2): print(i) for i in range(3): print("Hello there") print("i=%d" % (i)) Tracing. Loop semantics.

Strings

The string data type represents text. A string can be thought of as a list of characters, though there is a slight difference between a string and a list of characters. More on this later.

Python supports a few standard operations on strings including + (concatenation), * (duplication), and % (string formatting, more later).

List indexing and slicing

We can loop over any list and since strings are almost like a list of characters, we can can loop over strings: >>> s="Swarthmore" >>> for ch in s: ... print(ch) ... S w a r t h m o r e For any list, we can also use the function len() to determine the number of items in the list. >>> len(s) 10 >>> values=range(3) >>> len(values) 3 We can also select parts of a list using the indexing operator. Try the following statements in the python shell. What are the semantics of ls[0], ls[-1], ls[2:4], ls[:-1], and ls[2:]? Try some more examples to experiment. ls=range(1,11) s="Swarthmore" ls[0] ls[-1] ls[2:4] ls[:-1] ls[2:] s[0] s[-1] s[-4:] s[:3]+s[4]

The primary difference between lists and strings is that lists are mutable while strings are not. Thus, we can change elements in a list, but not in a string.

print(ls) ls[0]=2009 s[3]='a'

The accumulator pattern

A design pattern is a generic method for solving a class of problems. The standard algorithm might be described as follows:

get input process input and do computation display output

Almost any computational problem can be set up in this very general way, but step two is a very vague. Let's look at another common pattern, the accumulator.

initialize accumulator variable(s) loop until done: update accumulator variable(s) display output Many useful computational problems fit this pattern. Examples include computing a sum, average, or standard deviation of a list of numbers, reversing a string, or counting the number of times a particular value occurs in a list. Let's try to compute the average of a list of numbers entered by the user. Prompt the user to first enter the number of values he/she wishes to average and then prompt for each number. Finally display the average. Start with pseudocode, a written idea that organizes your thought process. Then write your solution in python and test.

String Formatting

We can get more control over how data values are displayed using string formatting. myInt = 86 myFloat = 1./3 print("The value %d is an integer but %0.2f is not" % (myInt, myFloat)) Using this new style requires a few steps. First, set up a string that contains one or more formatting tags. All tags have the form %<width><.><precision><type-char>. The type-char is s for strings, d for integers (don't ask why), and f for floats. Do not put any variable names in the format string, just tags which serve as placeholders for data that will come later. After the format string put a single % symbol after the close quote. Finally, place the data elements that you wish to substitute for the tags separated by commas and enclosed in parentheses. Let's step through a few examples in the python shell. >>> month="Sep" >>> day=8 >>> year=2015 >>> print("Today is %d %s %d" % (day, month, year)) Today is 8 Sep 2015 >>> print("Tomorrow is %d/%d/%d" %(9,day+1, year)) Tomorrow is 9/8/2015 >>> for val in range(1,200,20): ... print("%7.2f" % (val*6.582118)) ... 6.58 138.22 269.87 401.51 533.15 664.79 796.44 928.08 1059.72 1191.36

Python includes three numeric types to represent numbers: integers, float, and complex number.

Int

In Python, integers are zero, positive or negative whole numbers without a fractional part and having unlimited precision, e.g. 0, 100, -10. The followings are valid integer literals in Python.

>>> 0 0 >>> 100 100 >>> -10 -10 >>> >>> y=5000000000000000000000000000000000000000000000000000000 5000000000000000000000000000000000000000000000000000000

Integers can be binary, octal, and hexadecimal values.

>>> 0b11011000 # binary 216 >>> 0o12 # octal 10 >>> 0x12 # hexadecimal 15

All integer literals or variables are objects of the int class. Use the type() method to get the class name, as shown below.

>>>type(100) <class 'int'> # type of x is int >>> x= >>> type(x) <class 'int'> # type of x is int >>> y=5000000000000000000000000000000000000000000000000000000 >>> type(y) # type of y is int <class 'int'>

Leading zeros in non-zero integers are not allowed e.g. 000123 is invalid number, 0000 is 0.

>>> x=0 SyntaxError: invalid token

Python does not allow comma as number delimiter. Use underscore _ as a delimiter instead.

>>> x=1_234_567_890 >>> x

Note that integers must be without a fractional part (decimal point). It it includes a fractional then it becomes a float.

>>> x=5 >>> type(x) <class 'int'> >>> x=5.0 >>> type(x) <class 'float'>

The int() function converts a string or float to int.

>>> int('100') 100 >>> int('-10') -10 >>> int('5.5') 5 >>> int('100', 2) 4

Binary

A number having 0b with eight digits in the combination of 0 and 1 represent the binary numbers in Python. For example, 0b11011000 is a binary number equivalent to integer 216.

>>> x=0b11011000 >>> x 216 >>> x=0b_1101_1000 >>> x 216 >>> type(x) <class 'int'>

Octal

A number having 0o or 0O as prefix represents an octal number. For example, 0O12 is equivalent to integer 10.

>>> x=0o12 >>> x 10 >>> type(x) <class 'int'>

Hexadecimal

A number with 0x or 0X as prefix represents hexadecimal number. For example, 0x12 is equivalent to integer 18.

>>> x=0x12 >>> x 18 >>> type(x) <class 'int'>

Float

In Python, floating point numbers (float) are positive and negative real numbers with a fractional part denoted by the decimal symbol . or the scientific notation E or e, e.g. 1234.56, 3.142, -1.55, 0.23.

>>> f=1.2 >>> f 1.2 >>> type(f) <class 'float'>

Floats can be separated by the underscore _, e.g. 123_42.222_013 is a valid float.

>>> f=123_42.222_013 >>> f 12342.222013

Floats has the maximum size depends on your system. The float beyond its maximum size referred as "inf", "Inf", "INFINITY", or "infinity". Float 2e400 will be considered as infinity for most systems.

Scientific notation is used as a short representation to express floats having many digits. For example: 345.56789 is represented as 3.4556789e2 or 3.4556789E2

>>> f=1e3 >>> f 1000.0 >>> f=1e5 >>> f 100000.0 >>> f=3.4556789e2 >>> f 345.56789

Use the float() function to convert string, int to float.

>>> float('5.5') 5.5 >>> float('5') 5.0 >>> float(' -5') -5.0 >>> float('1e3') 1000.0 >>> float('-Infinity') -inf >>> float('inf') inf

Complex Number

A complex number is a number with real and imaginary components. For example, 5 + 6j is a complex number where 5 is the real component and 6 multiplied by j is an imaginary component.

>>> a=5+2j >>> a (5+2j) >>> type(a) <class 'complex'>

You must use j or J as imaginary component. Using other character will throw syntax error.

>>> a=5+2k SyntaxError: invalid syntax >>> a=5+j SyntaxError: invalid syntax >>> a=5i+2j SyntaxError: invalid syntax

Arithmetic Operators

The following table list arithmetic operators on integer values:

Operator Description Example
+ (Addition) Adds operands on either side of the operator. >>> a=10; b=20 >>> a+b

30

- (Subtraction) Subtracts the right-hand operand from the left-hand operand. >>> a=10; b=20 >>> b-a 10 >>> a-b

-10

* (Multiplication) Multiplies values on either side of the operator. >>> a=10; b=20 >>> a*b

200

/ (Division) Divides the left-hand operand by the right-hand operand. >>> a=10; b=20 >>> b/a

2

% (Modulus) Returns the remainder of the division of the left-hand operand by right-hand operand. >>> a=10; b=22 >>> b%a

2

** (Exponent) Calculates the value of the left-operand raised to the right-operand. >>> a=3 >>> a**2 9 >>> a**3

27

// (Floor Division) The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity): >>> a=9; b=2 >>> a//b

4

Arithmetic Operations on Complex Numbers

Addition and subtraction of complex numbers is straightforward. Real and imaginary parts are added/subtracted to get the result.

>>> a=6+4j >>> a+2 (8+4j) >>> a*2 (12+8j) >>> a/2 (3+2j) >>> a**2 (20+48j) >>> b=3+2j >>> a+b (9+6j) >>> a-b (3+2j)

The arithmetic operators can also be used with two complex numbers, as shown below.

>>> a=6+4j >>> b=3+2j >>> a+b (9+6j) >>> a-b (3+2j) >>> a*b (10+24j)

The process of multiplying these two complex numbers is very similar to multiplying two binomials. Multiply each term in the first number by each term in the second number.

a=6+4j b=3+2j c=a*b c=(6+4j)*(3+2j) c=(18+12j+12j+8*-1) c=10+24j

Built-in Functions

A numeric object of one type can be converted in another type using the following functions:

Built-in Function Description
int Returns the integer object from a float or a string containing digits.
float Returns a floating-point number object from a number or string containing digits with decimal point or scientific notation.
complex Returns a complex number with real and imaginary components.
hex Converts a decimal integer into a hexadecimal number with 0x prefix.
oct Converts a decimal integer in an octal representation with 0o prefix.
pow Returns the power of the specified numbers.
abs Returns the absolute value of a number without considering its sign.
round Returns the rounded number.