Monday 27 July 2015

Variables and Data Types

#!/usr/bin/env python

# Python Variables and Data Types
# The first thing to know about a variable is that it is just a place in the
# computer's memory where data is held. Think of them as boxes.

# Variables have names to make them easier to work with. In most programming
# languages variable names can be made up of numbers and letters. And they
# normally must start with a letter or underscore character "_". Python in this
# respect is like any other programming language. A variable name is called an
# "identifier". Identifiers are case sensitive. Python keywords cannot be used
# as identifiers.

# Python variables are loosely typed. The interpreter assumes the variable type
# based on the content of the variable. Variables can be integers, long integers
# octal literals (base 8), hexadecimal literals (base 16), floating-point
# numbers and complex numbers.

# Python also supports some complex data structures. These are strings, lists,
# tupels, dictionaries and sets. A list is like an array in Java or C. Except a
# list in Python can consist of mixed types. Tupels, dictionaries and sets are
# similar to lists. But they have different uses, attributes and methods of
# access.

# Examples of numbers.
a = 1 # Integer.
b = 42000000000000000000L # Long integer.
c = 010 # Octal literal.
d = 0xA1F # Hexadecimal literal.
e = 0XA1F # Hexadecimal literal.
f = 45.33 # Floating-point number.
g = 9.5541e-10 # Floating-point number.
h = 4 + 4j # Complex number.

print a
print b
print c
print d
print e
print f
print g
print h

# Examples of strings.
i = "Hello World" # String with double quotes "
j = 'Hello World' # String with single quotes '

k = '''Hello World can extend over multiple lines
and contain 'single quotes' and "double quotes"
 which is crazy.''' # String with triple quotes '''

l = '\"Hello World\"' # String with single quotes, printing double quotes.
m = "\'Hello World\'" # String with double quotes, printing single quotes.

print i
print j
print k
print l
print m

# Example of a list.
n = ["H","e","l","l","0"] # A simple list.
o = [["W","o","r","l","d"],2,3.45,0xA1F] # A list composed of multiple types.

print n
print o
print n[0]
print n[1]
print n[2]
print n[3]
print n[4]
print o[0][0]
print o[0][1]
print o[0][2]
print o[0][3]
print o[0][4]
print o[1]
print o[2]
print o[3]

# Example of a tuple.
p = ("Tuples","are","immutable","lists")
print p
print p[0]
print p[1]
print p[2]
print p[3]

# Example of a dictionary.
q = {"Name" : "Bob","Age" : 20}
print q
print q["Name"]
print q["Age"]

# Example of a set.
r = set(("Hello World",i))
s = {"Hello World",i}
print r
print s
# Why doesn't "Hello World" print twice for each set as we would expect?
# Sets contain non-repeating data only. Since "Hello World" and "i" are the same,
# one is discarded.

No comments:

Post a Comment