0% found this document useful (0 votes)
5 views12 pages

Python Variables and Functions Guide

The document provides an overview of Python programming concepts including variables, functions, tuples, strings, sets, recursion, and libraries like NumPy and Matplotlib. It covers naming conventions for variables, function definitions, string manipulation, and the use of data structures. Additionally, it highlights common mistakes, methods for handling data, and the use of keyword arguments in functions.

Uploaded by

5cxgvjmf4s
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views12 pages

Python Variables and Functions Guide

The document provides an overview of Python programming concepts including variables, functions, tuples, strings, sets, recursion, and libraries like NumPy and Matplotlib. It covers naming conventions for variables, function definitions, string manipulation, and the use of data structures. Additionally, it highlights common mistakes, methods for handling data, and the use of keyword arguments in functions.

Uploaded by

5cxgvjmf4s
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Variables

Variables are values that have been assigned a name.

Variable names in Python can be any length and can consist of uppercase
and lowercase letters (A-Z, a-z), digits (0-9), and the underscore character
(_), cannot include spaces! The first character of a variable name
cannot be a digit.

There are also a few names you can’t use, as they have special meanings.
These are: False, def, if, raise, none, del, import, return, True, elif,
in, try, and, else, is, while, as, except, lambda, with, assert,
finally, nonlocal, yield, break, for, not, class, from, or, continue,
global, pass.

Variable names are case sensitive – so MyVariable is NOT the same


variable as Myvariable.

Functions and local/global variables


Python functions are defined with
def function_name(arguments):
[indented body]
 Function names follow the same rules as variable names and
should be descriptive.
 Arguments become local variables inside the function.
 Use return to send a value back and end the function. You can
return any object, including tuples. A function may have multiple
return statements, but execution stops at the first one.
 Functions don’t need to explicitly return a value; they can end
naturally, though style opinions vary.
 A function must be defined before it’s used.
Example:
def add_numbers(a, b):
return a + b
 Variables created inside a function are local and disappear when
the function ends.
 Functions normally cannot modify variables outside their scope.
 You can break this rule using the global keyword, but it’s
discouraged because it makes debugging harder.
Common mistakes:
 Missing the colon after def
 Incorrect indentation
 Forgetting a return
 Trying to modify outside variables without global
 Failing to test the function with main-code snippets
Tuples

Tuples are a built-in feature of python – they are similar to lists, the main
difference being that tuples are immutable – once you’ve created one you
can’t change it. They are used in all sorts of situations where you need to
bundle values/objects together.

Tuples can be created like lists, except they use round brackets rather
than square brackets. So…

a_tuple = (3, "text", variable_b)

… sets one up. Like lists, tuples can have as many elements as you like,
and the elements don’t all have to be of the same type.

A common use is for returning multiple values from a function, to get


round the ‘functions return just one value using return keyword’ problem.
Just pack your multiple values into a tuple, and return that.

Strings
Functions: take information and do something with it

e.g. print(“Hello World”)

print is a pre-defined function, other functions you will write yourself, or


import from modules (import maths)

F Strings: allows you to insert variables into text

e.g. my_variable = 5 value is 5


print(f“value is {my_variable}”) value 5 is 5.000
print(f“value {my_variable} is {my_variable:.3f}”)

f strings are also used to control formatting of numbers. :.3f can be added
to format the value to 3sf

Combining strings: combine strings together and store them in


variables

e.g. hello_variable = “Hello” Hello cruel world!


world_variable = "world!”
combined_variable = hello_variable + “ cruel ” + world_variable
print(combined_variable)

new-line in a string: two options – can use \n or you can surround your
string with triple double quotes, then use actual line breaks. So both of the
following examples:

print("new\nline") new
print("""new line
line""")
String slicing:
"slicing"[0]: means character 0 - so “s”
"slicing"[1:3]: means characters 1-2 – so “li”
"slicing"[:5]: Start to character 4 – so “slici”. Yes, it DOES mean character
4 - it’s up to but not including character 5.
"slicing"[4:]: means character 4 to end – so “ing”
"slicing"[-4:-2]: means characters 4th from end to 3rd from end – so “ci”.
Yes it DOES mean 3rd from the end - it’s up to but not including character
-2 from the end.
"slicing"[-3:] Characters 3rd from end to the end (i.e. last 3 characters) –
so “ing”

Methods for str (built-in string class)

capitalize() return type: str - Returns a version of the string with the 1 st
letter capitalized.
count(substring) return type: int - Counts how many times ‘substring’
occurs in the string, then returns this count (which may be 0) as an
integer.
find(substring) return type: int
Returns the index (position) of the first occurrence of ‘substring’ occurs in
the string. If substring isn’t found, it returns -1.
isalpha() return type: bool
Returns True if all characters in the string are letters, otherwise returns
False
isnumeric() return type: bool
Returns True if all characters in the string are digits, otherwise returns
False
join(container) return type: string The opposite of split. Join takes a
container (e.g. a list, normally a list of strings) as an argument and joins
all the elements together into a single string, using the object string as a
separator. For example, ",".join(["goodbye", "cruel", "world"]) returns the
string “goodbye,cruel,world”.
lower() return type: str
Returns a copy of the string with all characters converted to lowercase.
replace(oldtext, newtext) return type: str
Returns a copy of the string in which all occurrences of the text oldtext are
replaced with newtext.
split(split_on) return type: list (of strings) Splits a string on the
substring split_on into a list of strings. For example, "goodbye cruel
world".split(" ") returns ["goodbye", "cruel", "world"]. split_on is normally
done on a one-character string, but it doesn’t have to be.
strip() return type: str
Returns a copy of the string with any whitespace characters (spaces, tabs,
newlines) removed from both the start and end
upper() return type: str
Returns a copy of the string with all characters converted to uppercase.

Sets: a Python container type similar to mathematical sets.


o Contain unique elements (duplicates are removed
automatically).
o Are unordered — you cannot rely on element order when
iterating.
o Are not indexable (no slicing, no element positions).
o Are iterable using for.
o Can hold elements of any type.
 Define sets with curly braces without colons:
 a_set = {1, 2, 3}
Duplicate values are ignored: {1, 3, 2, 1} becomes {1, 2, 3}.
 Creating and converting:
 a_set = set(a_list) # list → set
 a_list = list(a_set) # set → list
 empty_set = set() # empty set ({} would be a dict)
 Operations:
o Add elements with .add():
a_set.add(4)
o Combine sets with .update() (not +).
o Subtract sets using - to get the difference.
o Check membership with in:
2 in a_set # True
Sets aren’t used as often as lists or dictionaries, but they are ideal when
you need uniqueness and fast membership checks.

clear() return type: N/A - Clears the set, i.e. deletes all items within it.
copy() return type: set - Returns a copy of the set. This is NOT the
same as using =. You CAN do set_a = set_b, but that doesn’t make a copy
– set_a just refers to the same copy of the set as set_b, so if you
change set_a, you are also changing set_b. Use copy to make a real copy
you can modify separately.
remove(element) return type: N/A
Removes the element specified from the set, or throws an exception if no
such element exists.
difference(otherset) return type: set
Calculates the difference between sets, i.e. removes if any element of the
set is also in otherset, it is removed. This is the same as using the –
operator (so [Link](b) is the same as a-b, if a and b are both sets).
union(othersets) return type: set
Returns the union of the set and all sets in othersets (othersets can be
more than one set, as a list of arguments separated by commas). The
intersection is a set containing all elements that are in ANY of the sets.

Recursion
Recursion is when a function solves a problem by calling itself on smaller
parts of the problem. It’s ideal for tree-like structures.
Example: counting all descendants of a species.
For each species:
total = number of daughters + total descendants of each
daughter
A species with no daughters returns 0, which stops the recursion.
Recursion works because each call has its own local variables, and it’s a
clean way to process branching data like family trees or folder structures.

Pillow:
from PIL import Image # standard import line for
[Link]
# To read an image file into a numpy array:
img = [Link]("[Link]") # read the image into
array im
image_as_array = [Link](img)
or just
image_as_array = [Link]([Link]("[Link]") )
To write an array out as an image:
img = [Link](array_to_write_as_image)
[Link]("[Link]")
or just
[Link](array_to_write_as_image).save("[Link]")
[Link] knows about a lot of formats, so should work with png, jpg,
bmp, tiff and most common image types (but not all – there are a LOT of
image formats out there).
Array shapes and formats:
If the image is a greyscale image, the data will be a 2D array – first
dimension is height, second dimension is width. Vertical positions are
counted from the top, not the bottom, so [0,0] is the top left corner, [0,1]
is one pixel to the right of the top left corner. Each value will be a pixel
intensity, 0-255. If the image is a RGB (colour) image, you get an extra
dimension of size 3 – these are the red, green and blue levels, using the
same 0-255 scale. So [10, 20, 1] gives you the green value at position 10
pixels from the top, 20 pixels from the left.

% - For numbers, it performs a modulus calculation (i.e. works


out the remainder of a division).
print(15 % 6) # print the remainder when dividing 15 by 6 (3)
a=b%c # calculate the remainder from dividing b by c,
assign it to a.
# this assumes b and c are both numbers

NumPy Array Basics:


 NumPy uses methods (e.g., [Link](), [Link]()), not
standalone functions.
 Most NumPy methods return a new array instead of modifying the
original.
Key features:
 copy() → returns a separate copy of the array.
o new = old does not copy; both names refer to the same array.
o Use new = [Link]() to safely modify one without affecting
the other.
 reshape(size) → returns a new array with a new shape.
o Size can be a single int or a tuple.
o Number of elements must stay the same.
o Example:
[1 2 3 4 5 6].reshape((2,3)) →
o 123
o 456
 shape → a tuple describing array dimensions (e.g., (5, 6) for 5×6).
o [Link][1] gives number of columns.

import numpy as np
Then you will need to prefix all functions with np.

Matplotlib:
import [Link]
import [Link] as plt # plt is alias – prefix functions with .plt

[Link]([1, 3, 10, 7], [4, 5, 6, 3], "rx")


[Link]("Some numbers plotted")
[Link]()
Main Plot Types
 [Link] / [Link] — bar charts (vertical/horizontal).
 [Link] — histogram.
 [Link] — pie chart.
 [Link] — line or scatter plot (format strings for colour/markers).

Common Options (kwargs)


 color, linewidth, linestyle, marker, markersize, labels, bins, explode,
autopct, etc.

Plot Decorations
 [Link]() — add grid
 [Link]() — show legend
 [Link](), [Link](), [Link]() — add text labels
 [Link]() — place custom text
 [Link](), [Link]() — set axis ranges
 [Link](), [Link]() — choose tick positions and labels
 plt.subplots_adjust() — move the plot on the page

Finish
 [Link]() — displays the plot and resets it.

Loops:
break ends the loop – execution of the program moves to the line
immediately after the loop.
continue ends this iteration of the loop – execution of the program moves
back to the while to test the condition (or to the for if this is a for loop).

while loops: uses a condition to control a loop


e.g. counter = 0 1 squared is 1
while counter < 5: 2 squared is 4
counter = counter + 1 3 squared is 9
print(f"{counter} squared is {counter**2}") 4 squared is
16
5 squared is 25

for loops: used when you want to do something to or with each element
in a list
e.g. my_list = [1, 100, 999] 1
for element in my_list: 100
print(element) 999

Creating lists
my_list = [1, 20, 7]
empty_list = []
empty_list = list() # constructor form
one_to_ten = list(range(1, 11))
Indexing & slicing
 Use the same [start:stop:step] rules as strings (e.g. lst[0], lst[-1]).
Combining / measuring
 Concatenate with +:
[1,2,4] + [5,8,10]
 Length with len(lst).
Functions vs methods (practical rule of thumb)
 Many general operations are functions (e.g. len, min, max) and
work on many container types.
 List-specific actions are often methods (called with
[Link]()), e.g.:
[Link]()
Common mistakes to avoid
 Forgetting square brackets for lists
 Using 1-based indexing by accident (it’s 0-based)
 Mixing up index vs element (e.g., pop takes an index; remove
takes a value)
 Confusing append (add one item) vs extend (add many items)
 Calling list methods before the list exists (create [] first)
List comprehensions (compact “loop-to-list” syntax)
 General form:
[expression for item in iterable if condition]
 Examples:
square_numbers = [i**2 for i in range(1, 11)]
ten_zeroes = [0 for i in range(10)]
odd_numbers = [i for i in range(1, 100) if i % 2 == 1]

append(value) – Adds a single item to the end of the list.


If you append a list, it becomes one element → use extend or + to add
multiple items.
count(element) – Returns how many times a value appears.
extend(newlist) – Adds each element of another list to the end (not
nested). List is modified in-place.
insert(index, element) – Inserts an item at a specific position.
pop(index) – Removes and returns the item at that index. Use this when
you know the index.
remove(element) – Removes the first matching value. Use this when
you know the element value.
reverse() – Reverses the list in-place.
sort() – Sorts the list in-place (numbers or strings). For a non-destructive
version, use sorted(list).

KWARGS:
Here’s a concise summary:

Keyword Arguments (kwargs) in Python


 Normally, function arguments are positional:
value = func(a, b, c)
 Keyword arguments let you pass values using the parameter
names, making order irrelevant and code more readable:
value = func(a=1, c=3, b=2)
 Many functions (especially in libraries like Matplotlib) mix
positional arguments and optional kwargs:
plot(x, y, 'bx', markersize=10, markeredgewidth=3)
 When defining your own functions, kwargs use the names of your
parameters automatically.
 Benefits:
o No need to remember argument order
o Clearer code
o Reduces errors from passing wrong values
 Caveat: you must use the correct parameter names; Python will
raise an error if you don’t.
Import:
import module [as alias] # the 'as alias' is optional
import math
import numpy as np

from math import sin, cos, pi

if/ elif/ else code blocks: does/doesn’t run a block of code depending on
whether a condition is true or false

e.g. a=5 a is less than 10


if a > 10: got past if block
print(“a is greater than 10”)
elif a = 10:
print(“a is 10”)
else:
print(“a is less than 10”)
print(“got past if block”)

Common Python Functions


 abs(number) → returns the absolute value (int or float).
 chr(int) → returns the single-character string for an ASCII code.
 ord(string) → returns ASCII code for a single-character string.
 float(value) → converts a value to a float.
 int(value) → converts a value to an integer (truncates toward 0).
 str(value) → converts a value to a string.
 input(prompt) → gets user input as a string.
 len(container or string) → returns number of
elements/characters.
 min(container) → returns smallest value (numbers or
alphabetically first string).
 max(container) → returns largest value (numbers or alphabetically
last string).
 print(value) → displays value in the terminal.
 range(start, stop, step) → generates a sequence of integers
(iterable, not a list).
 open(filename, mode) → opens a file and returns a file object ('r',
'w', 'a').
Notes:
 Functions either return a value or N/A (e.g., print).
 range can be converted to a list with list(range(...)) if needed.

Opening files:
resit_modules = open("q5_resit_data_modules.csv", "r")
header_modules = resit_modules.readline()
modules_data = resit_modules.readlines()
resit_modules.close()

for line in modules_data:


split_data = [Link](",")
module_name = split_data[0] # key
module_ECTS = split_data[1]

close() → closes the file; frees it for other programs.


read(character_count) → reads up to character_count characters as a
string; all if omitted.
readline() → reads the next line as a string (includes \n at end).
readlines() → reads entire file into a list of strings (each line keeps \n).
write(string) → writes a string to the file (no automatic newline).
writelines(stringlist) → writes a list of strings to the file (no automatic
newlines).
try and except combination: help to catch exception errors.
try:
a = float(input(“Enter value: ”))
print(10/a)
except ZeroDivisionError:
print(“Error – can’t divide by zero”)
except ValueError:
print(“Error – input not a number”)
except Exception: # Exception catches all errors not
already found
print(“Arggg… unknown error thrown”)

Dictionaries:
Concept: Key/value pairs (like a flexible lookup table), unordered, no
indices.
Creation: Use curly braces {}: digit_dict = {"one":1, "two":2}
Access: Use keys like indices: digit_dict["two"] # returns 2
Iteration:
for key in digit_dict: print(key) # keys
for key in digit_dict: print(digit_dict[key]) # values
Adding/Updating:
digit_dict["ten"] = 10 # single item
digit_dict.update({"eleven":11}) # add dict
Removing: pop(key)
Get lists: keys() → keys, values() → values
Differences from lists:
Unordered → no slicing or + addition
len, min, max, sum operate on keys
in checks keys, not values
Common errors: Using wrong brackets, slicing, assuming order, using
floats as keys.

Dictionary Methods:
 clear() → N/A: Removes all items.
 copy() → dict: Returns a separate copy (not the same object).
 keys() → list: Returns a list of all keys.
 values() → list: Returns a list of all values.
 pop(key) → varies: Removes and returns the value for the key.
 update(newdict) → N/A: Adds all key/value pairs from another
dictionary in-place.

You might also like