02 Lecture MD
02 Lecture MD
Programming
Lecture slides - Variables and Types
10 * 2 + (4 / 2.5 * 2)
● We store the results of expressions, and other types of values using variables
age
average_value
highest_score
student_name
1_person
&hello
Assignment
age = 23
average_value = (10 + 20 + 30) / 3
highest_score = last_score
student_name = "Jon"
● Notice how the right side of the ‘=’ can be an expression, or the name of
another variable
● The ‘=’ has a low precedence, which means that the right-hand side is
evaluated prior to the value been stored in the variable
Updating Variable Values
● Variable values are often changed relative to their own current value, e.g.
age = age + 1
● Since the right hand side is evaluated first, this takes the current value of
‘age’, increases it by 1, then assigns the result back to the ‘age’ variable
● Remember the ‘=’ symbol causes an assignment, it is NOT testing whether
the left-hand value is equal to the right-hand value
Augmented Assignment
● Assignments which include the same variable to the left and right of the
assignment symbol (=) are common, e.g. count = count + 1
● Because of this there are a set of short-cuts available for writing such
expressions (inherited from the C programming language)
● Many other languages use static typing, which ensures each variable can
only ever store one specific type of value
● The fact that variables can change data-type over their life-time can lead to
unexpected run-time errors, so care must be taken when programming
● A type() function exists which will tell you the type of a value or variable
Common Data-Types
● Python has a number of built-in types, which are very commonly used.
These primitive-types are -
○ float refers to decimal values, i.e. numbers that include a decimal place
● Python also has additional built-in types, that we shall examine later
More on Data-Types
x = 10.2
type(x)
float
x = "hello"
type(x)
str
● Since these operands are based on a string data-type, the ‘+’ performs
concatenation rather than addition
● It is also possible apply the ‘*’ operator to strings, resulting in the content
being repeated a number of times, e.g.
police_greeting = greeting * 3
Introducing Functions
● Python provides many built-in functions, and many libraries that contain
functions
● This function takes a single argument, then tells us the type of that value
Functions
● We have already seen the built-in print() function within an earlier lesson
● We often need to read input from the user. We can use the built-in function
input() to do this, e.g.
● The value typed by the user is returned as a string, and in the above example
assigned to the ‘name’ variable
● If the input value is to be used as something other than a string, then it needs
to be converted, e.g.
age = input("What's your age? ")
print("In ten years you will be", int(age) + 10)
● This example calls to the function int() to convert the string to an integer
Strings: Single and Double Quotations
● A string type value can be delimited using single quotes or double, e.g.
\n Insert a newline character in a string. When the string is displayed, for each newline, move the
screen cursor to the beginning of the next line.
\t Insert a horizontal tab. When the string is displayed, for each tab, move the screen cursor to the
next tab stop.
● Can be used for multi-line strings, strings containing both single and
double quotes, or docstrings (to be discussed later), e.g.
● Unlike many other languages Python allows -ve index values to be used
● An index of less than 0 starts counting from the right-side of the string, e.g.
name = "Black Knight"
last_letter = name[-1]
● Notice how the -ve index is NOT zero based (since -0 is the same as 0)
● As with positive indices, attempting to use an index that is out of range will
result in an error, e.g. the following would cause an error -
last_letter = name[-13]
Strings: Slicing
● The start indexed value is included, the end indexed value is excluded
● If either the start or end index is omitted then these default to be 0 (for the
start) or the length of the string (for the end)
● As with single character access, -ve indexing is also allowed
Strings: Slicing Examples
● Note: Unlike single character indexing, out of range slice indices are
handled gracefully, e.g. the following would NOT cause a run-time error -
primes = [2, 3, 5, 7, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 ]
Lists
● Lists usually always contain elements all of the same type, but can contain
values of any type (even other lists), e.g.
mixed = [10, 20.25, False, [1,2,3], "Mark"]
● Lists (like Strings) are a type of sequence within Python, and thus support
common features such as indexing and slicing, e.g.
first_prime = primes[0]
last_prime = primes[-1]
mid_primes = primes[4:9]
● Lists and Strings are very similar but have one important difference, which
is that Lists are mutable, whereas strings are immutable
● This basically means an existing list can be changed after it is created,
whereas strings can never be modified following creation, e.g.
squares = [4, 9, 15, 25]
squares[2] = 16 # change the third element within the list
name = "Park"
name[0] = "M" # would cause an error, since a string is immutable
● Python has useful built-in function called len() that can be used to find out
how many elements are present within a string or list, e.g.
name = input("Enter your name : ")
print("your name contains", len(name), "characters")
● This function is often useful when using indexing and slicing, e.g.
names[len(names):] = ["Pete", "Josh"]
● The above example would insert two new names at the end of the list
● The len() function can be applied to other data-types which contain
multiple values, such as tuples, sets, and dictionaries that we will see later
Summary
● We use the input() function to get information from the user, this always
returns a string type value
● Strings and lists are both a type of sequence, that we can index and slice