You are on page 1of 24

Chapter Two:

Variables and
Data Types
Variables
• Are not declared, just assigned
• The variable is created the first time you assign it a
value
• Are references to objects
• Type information is with the object, not the
reference
• Everything in Python is an object
Enough to Understand the Code
• Assignment uses = and comparison uses ==.

• For numbers +, -, *, /, % are as expected.


• Special use of + for string concatenation.
• Special use of % for string formatting.

• Logical operators are words (and, or, not)


not symbols (&&, ||, !).

• The basic printing command is “print.”

• First assignment to a variable will create it.


• Variable types don’t need to be declared.
• Python figures out the variable types on its own.
Comments
• Start comments with # – the rest of line is ignored.

• Can include a “documentation string” as the first line


of any new function or class that you define.

• The development environment, debugger, and other


tools use it: it’s good style to include one.
def my_function(x, y):
“““This is the docstring. This
function does blah blah blah.”””
# The code would go here...
Python Build-in types
• Numbers 3.1415
• Strings “Hello World”
• Lists [1,2,3,4]
• Dictionaries {‘test’: ‘yum’}
• Files input=open(‘file.txt’, ‘r’)
Strings
• The next major build-in type is the Python STRING ---
an ordered collection of characters to store and
represent text-based information

• Python strings are categorized as immutable sequences


--- meaning they have a left-to-right order (sequence)
and cannot be changed in place (immutable)

• This definition of immutable sequences is sufficient for


now. You will learn more from examples.
Indexes in slices

• Characters in a string are numbered with indexes starting at 0:


• Example:
name = "P. Diddy"

index 0 1 2 3 4 5 6 7
character P . D i d d y

• Accessing an individual character of a string:


variableName [ index ]
• Example:
print name, "starts with", name[0]
Output:
P. Diddy starts with P

7
String Methods: modifying and checking strings
assigned to variables
• Assign a string to a variable
• In this case “hw”
• hw.title()
• hw.upper()
• hw.isdigit()
• hw.islower()
• The string held in your variable
remains the same
• The method returns an altered string
• Changing the variable requires
reassignment
• hw = hw.upper()
• hw now equals “HELLO WORLD”
Examples of Strings
• "hello"+"world" "helloworld" # concatenation
• "hello"*3 "hellohellohello" # repetition
• "hello"[0] "h" # indexing
• "hello"[-1] "o" # (from end)
• "hello"[1:4] "ell" # slicing
• len("hello") 5 # size
• "hello" < "jello" 1 # comparison
• "e" in "hello" 1 # search
• New line: "escapes: \n "
• Line continuation: triple quotes ’’’
• Quotes: ‘single quotes’, "raw strings"
raw_input: reading text from
input

• raw_input : Reads a string of text from user input.


• Example:
name = raw_input("Howdy, pardner. What's yer
name? ")
print name, "... what a silly name!"
Output:
Howdy, pardner. What's yer name? Paris
Hilton
Paris Hilton ... what a silly name!

10
Python Objects: Lists, Tuples,
Dictionaries
• Lists (mutable sets of strings)
• var = [] # create list
• var = [‘one’, 2, ‘three’, ‘banana’]
• Tuples (immutable sets)
• var = (‘one’, 2, ‘three’, ‘banana’)
• Dictionaries (associative arrays or ‘hashes’)
• var = {} # create dictionary
• var = {‘lat’: 40.20547, ‘lon’: -74.76322}
• var[‘lat’] = 40.2054

• Each has its own set of methods


How Tuples, Lists, and Strings are defined
Defining Tuples

• Tuples are defined using parentheses (and commas).


>>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’)
Defining Lists
• Lists are defined using square brackets (and commas).
>>> li = [“abc”, 34, 4.34, 23]
Defining Strings

• Strings are defined using quotes (“, ‘, or “““).


>>> st = “Hello World”
>>> st = ‘Hello World’
>>> st = “““This is a multi-line
string that uses triple quotes.”””
The ‘in’ Operator in containers
• Boolean test whether a value is inside a container:
>>> t = [1, 2, 4, 5]
>>> 3 in t
False
>>> 4 in t
True
>>> 4 not in t
False
• Be careful: the ‘in’ keyword is also used in the syntax of
other unrelated Python constructions:
“for loops” and “list comprehensions.”
Lists are the most flexible containers

• Lists are Python’s most flexible ordered collection


object type

• Lists can contain any sort of object:


• numbers,
• strings
• and even other lists
Lists are mutable
• Ordered collection of data
• Data can be of different
>>> x = [1,'hello', (3 + 2j)]
types
>>> x
• Lists are mutable [1, 'hello', (3+2j)]
• There are issues with shared
>>> x[2]
references and mutability (3+2j)
• Lists have the same subset >>> x[0:2]
operations as Strings [1, 'hello']
More list operations: range, append, pop, insert,
reverse, sort

>>> a = range(5) # [0,1,2,3,4]


>>> a.append(5) # [0,1,2,3,4,5]
Pop from end,
>>> a.pop() # [0,1,2,3,4] removes from end,
5 returns this value

>>> a.insert(0, 5.5) # [5.5,0,1,2,3,4]


>>> a.pop(0) # [0,1,2,3,4]
Pop from front
5.5
>>> a.reverse() # [4,3,2,1,0]
>>> a.sort() # [0,1,2,3,4]
Tuples
• Like a list, tuples are iterable arrays of objects

• Tuples are immutable –


once created, unchangeable

• To add or remove items, you must redeclare

• Example uses of tuples


• County Names
• Land Use Codes
• Ordered set of functions
Tuples
• What is a tuple?
• A tuple is an ordered collection which cannot
be modified once it has been created.
• In other words, it's a special array, a read-only array.

• How to make a tuple? In round brackets


• E.g.,
>>> t = ()
>>> t = (1, 2, 3)
Not
the >>> t = (1, )
same
>>> t = 1,
>>> a = (1, 2, 3, 4, 5)
>>> print a[1] # 2
Tuples are
Immutable
We want wrongly to change 4.56 to 3.14 in tuple t

>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)


Python
>>> t[2] = 3.14 protests

Traceback (most recent call last):


File "<pyshell#75>", line 1, in -toplevel-
tu[2] = 3.14
TypeError: object doesn't support item assignment

You’re not allowed to change a tuple in place in memory;


memory so,
you can’t just change one element of it.
But it’s always OK to make a fresh tuple and assign its
reference to a previously used name.
>>> t = (1, 2, 3, 4, 5)
Dictionaries
• Dictionaries are sets of key & value pairs

• Allows you to identify values by a descriptive name


instead of order in a list

• Keys are unordered unless explicitly sorted

• Keys are unique:


• var[‘item’] = “apple”
• var[‘item’] = “banana”
• print var[‘item’] prints just banana
Dictionaries
{"name":"Guido", "age":43}
• Dictionaries: curly brackets
• What is dictionary? pairs
• Refer value through key; “associative arrays”
• Like an array indexed by a string
• An unordered set of key: value pairs
• Values of any type; keys of almost any type
• {"name":"Guido", "age":43, ("hello","world"):1,
42:"yes", "flag": ["red","white","blue"]}

d = { "foo" : 1, "bar" : 2 }
print d["bar"] # 2
some_dict = {}
some_dict["foo"] = "yow!"
print some_dict.keys() # ["foo"]
Dictionaries

• A set of key-value pairs

>>> d = {1 : 'hello', 'two' : 42, 'blah' : [1,2,3]}


>>> d
{1: 'hello', 'two': 42, 'blah': [1, 2, 3]}
>>> d['blah']
[1, 2, 3]
Dictionaries: Add/Modify
• Entries can be changed by assigning to that entry
>>> d
{1: 'hello', 'two': 42, 'blah': [1, 2, 3]}
>>> d['two'] = 99
>>> d
{1: 'hello', 'two': 99, 'blah': [1, 2, 3]}
modify

• Assigning to a key that does not exist adds an entry


>>> d[7] = 'new entry'
>>> d
{1: 'hello', 7: 'new entry', 'two': 99, 'blah': [1, 2, 3]}

adds
Thanks
Prepared by:Eng
mohamed ahmed

You might also like