Python 1

Arjun Jayaprakash

2019/06/25

Data Types

Here is how a simple code looks like. Saving variables as int (integers) or float (floating points) are shown.

# Create a variable savings
savings = 100

# Create a variable growth_multiplier
growth_multiplier = 1.1

# Calculate result
result = savings*growth_multiplier**7

# Print out result
print(result)
## 194.87171

Variable savings is of data type int and growth_multplier is of data type float. Two other data types that is of use are str (string) and bool (Boolean).

# Create a variable desc
desc = "compound interest"

# Create a variable profitable
profitable = True

If you want to find the type of a variable, use the function type(). This is analogous to the class() function in R.

An important thing in Python is that the operators like ‘+’ have different behaviors based on the type of the variables being operated upon. Sum of two integers will be an integer. If you sum two strings, you will get a concatenated string.

"A" + "B"
## 'AB'

Type conversion

Seems like type conversion of variables is a useful feature in Python. Functions int(), str(), float(), and bool() could be used to convert variables having different types to integer, string, float, and boolean respectively. Here is an application:

age = 7
print("I am " + str(age) + " years old")
## I am 7 years old

Python Strings

Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes (‘…’) or double quotes (“…”) with the same result.  can be used to escape quotes:

'spam eggs'  # single quotes
## 'spam eggs'
'doesn\'t'  # use \' to escape the single quote...
## "doesn't"
"doesn't"  # ...or use double quotes instead
## "doesn't"
'"Yes," they said.'
## '"Yes," they said.'
"\"Yes,\" they said."
## '"Yes," they said.'
'"Isn\'t," they said.'
## '"Isn\'t," they said.'

If you don’t want characters prefaced by  to be interpreted as special characters, you can use raw strings by adding an r before the first quote:

print('C:\some\name')  # here \n means newline!
## C:\some
## ame
print(r'C:\some\name')  # note the r before the quote
## C:\some\name

String literals can span multiple lines. One way is using triple-quotes: “”“…”“” or ‘’’…‘’’. End of lines are automatically included in the string, but it’s possible to prevent this by adding a  at the end of the line. The following example:

print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")
## Usage: thingy [OPTIONS]
##      -h                        Display this usage message
##      -H hostname               Hostname to connect to

Strings can be concatenated (glued together) with the + operator, and repeated with *:

print(3 * 'un' + 'ium')
## unununium
prefix = 'Py'
print(prefix + 'thon')
## Python
text = ('Put several strings within parentheses '
         'to have them joined together.')
print(text)
## Put several strings within parentheses to have them joined together.

Python strings cannot be changed — they are immutable. Therefore, assigning to an indexed position in the string results in an error:

word = 'Python'
word[0] = 'J'

This produces an error! If you need a different string, you should create a new one:

word = 'Python'
'J' + word[1:]
## 'Jython'

Python Lists

A convenient way to compile information of multiple data types is to create a list. List is yet another data type in python. It can be assigned to a variable name. Also, lists can contain more lists. A list is defined by putting in the elements of the list inside square brackets “[]”. Here is an example code for a list of lists.

# area variables (in square meters)
hall = 11.25
kit = 18.0
liv = 20.0
bed = 10.75
bath = 9.50

# house information as list of lists
house = [["hallway", hall],
         ["kitchen", kit],
         ["living room", liv],
         ["bedroom", bed],
         ["bathroom", bath]]

# Print out house
print(house)

# Print out the type of house
## [['hallway', 11.25], ['kitchen', 18.0], ['living room', 20.0], ['bedroom', 10.75], ['bathroom', 9.5]]
print(type(house))
## <type 'list'>

First Program

We can write an initial sub-sequence of the Fibonacci series as follows:

# Fibonacci series:
a, b = 0, 1
while a < 10:
  print(a)
  a, b = b, a+b
## 0
## 1
## 1
## 2
## 3
## 5
## 8

This example introduces several new features.

  • The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

  • The while loop executes as long as the condition (here: a < 10) remains true. In Python, like in C, any non-zero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. The test used in the example is a simple comparison. The standard comparison operators are written the same as in C: < (less than), > (greater than), == (equal to), <= (less than or equal to), >= (greater than or equal to) and != (not equal to).

  • The body of the loop is indented: indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.

  • The print() function writes the value of the argument(s) it is given. It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple arguments, floating point quantities, and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this:

i = 256*256
print("The value of i is", i)
## ('The value of i is', 65536)