Variables and Functions
Lecture 1.2 -- Introduction to Computer Science, HUJI Dr. Arie Schlesinger
Variables
Objects can have names -- variables are names of objects.
Generally, in a program we describe operations on data. We need to name/refer to the objects involved, like data and groups of instructions.
This is done by identifiers, symbolic names used to specify variables, functions, classes, modules, or other parts.
- A Python program accesses data values through references/names that refer to values/objects.
- A reference can be a variable (and also an attribute, or an item).
- Variables are called so because the information they represent can change.
Giving Names to Values
Until now we manipulated literal values/expressions directly. Symbolic expressions can express general ideas:
2 + 3vsx + y-- the addition idea(3 + 5)/2vs(x + y)/2-- the average3 + 1 > 3vsx + y > x-- true for all positive values
Giving names to values is the first step towards abstracting whole processes.
Assigning a Value to a Name
= is the assignment/binding operator. It creates a binding between the name (on the left) and the value/object (on the right).
A complete life cycle of a variable/name:
- Binding:
x = 8 - Using it in expressions
- Rebinding:
x = -1.2 - Unbinding:
del x
Rebinding or unbinding a name/reference does not affect the object referred to. An unreferred object can be erased by a mechanism called garbage collection.
# variable initializations
x = 5 # binds name x to 5 (obj)
y = 1 + 3 # binds name y to result 4 (obj), not to the expression 1 + 3
# rebinding x
x = 'Iosi'
print(x)
# unbinding x
del x
print(x) # NameError: name 'x' is not defined
# faulty names
2ndString = 'second string'
# SyntaxError: invalid syntax -- starts with a digit
# undefined variable
aVar + 1 # NameError: name 'aVar' is not defined
Updating an Existing Variable
A simple re-binding can change the object a name represents to another object.
x = 2 - 3
id(x) # the address of the object -1
x = 'iosi' * 3
id(x) # the address of the object 'iosiiosiiosi'
In math, x = 2 is an equation stating equivalence between the two sides.
In programming, x = 2 is an assignment operation -- after performing it, x is the name of 2.
Identifier/Naming Rules
- Use 1 or more of: letters, digits,
_. Do not start with a digit. - Case sensitive:
numandNumare different. - Use meaningful names:
newDiagis better than_x17_YtR. - Any length is allowed, but too long names impair readability.
Keywords
Keywords are reserved words with specific meanings. Do not use them as variable names.
from keyword import kwlist
kwlist
# ['False', 'None', 'True', 'and', 'as', 'assert', ...]
Increments and Shortcuts
In programming, a = a + 1 means: increase the value of a by 1. This has a shortcut:
| Shortcut | Equivalent |
|---|---|
a += b | a = a + b |
a -= b | a = a - b |
a *= b | a = a * b |
a /= b | a = a / b |
a //= b | a = a // b |
a **= b | a = a ** b |
a %= b | a = a % b |
a = 5 # a is bound to 5
a = a + 1 # first evaluate the right-hand expr, then re-bind a with the new result
a # a is bound to 6
More on Names
- Each object belongs to a class, but variable names have no class -- Python is dynamically typed.
- One object can have many names:
x = 1000
y = x
z = y
# all are names of 1000, and have the same address
print('x address:', id(x))
print('y address:', id(y))
print('z address:', id(z))
Multiple Assignments
# Assign different names to same object:
a = b = c = d = 2
print(a, b, c, d)
# Assign different objects to different names:
x, y = 2, 3
# Swap values:
x, y = y, x
# (with the compliments of tuple unpacking magic)
The "Concierge"
In interactive mode only, the special variable _ stores the result of the last operation:
2 + 3 # 5
_ * 3 # 15
Printing Variables
name = "Ety"
print(name) # prints strings without quotes
num = -12
fact = 3.4
print(num, fact) # separator is one blank
# typically 'label and value' printing
print("num =", num, "fact =", fact)
n = 'November'
birth = 1992
year = 2020
print('Iosi', "will be", year - birth, 'years old in', n)
User-Defined Functions in Python
A function is a group of statements that together perform some specific task.
General Syntax
def function_name(parameters_list):
'''docstring'''
# comment about the function
statement(s)
def hello(name):
'prints a greeting'
print('Hello', name)
# function call
hello('Ety')
Syntax Details
- The function header starts with
defand ends with a colon: - The
function_nameis an identifier following the same rules as variables - The
parameters_listcontains identifiers separated by commas, enclosed in parentheses - Indentation: function statements are indented by 4 spaces
The DocString
The docstring (triple-quotes string) documents the function. Though optional, it is highly appreciated.
help(hello) # prints the docstring
Parameters and Arguments
- At definition, the identifiers are called (formal) parameters
- The values supplied when the function is called are called arguments
The return Statement
Every function returns a value when called. If there is no return statement, or the return specifies no value, None is returned.
def f1(x): # returns a value
return pow(x, x + 1)
print(f1(2)) # 8
def f2(x): # no return statement - returns None
y = pow(x, x + 1)
print(f2(3)) # None
def f3(x): # return without a value - returns None
x = x + 1
return
print(f3(4)) # None
Function with Multiple Parameters
def hello_class(season, year):
'''writes a greeting for the Intro course'''
greeting = 'Welcome Intro class of '
print(greeting, season, year)
hello_class("Spring", 2023)
hello_class("Fall", 2022)
Calling a Function
- Writing and running the function does not activate it -- you must call it.
function_name(parameters_list)calls an already defined function.- A function cannot be called if the call is placed before the function definition.
def f(x, y):
'''adds two values'''
return x + y
f(2, 3) # 5 -- a "numeric" call
f('a', 'bcd') # 'abcd' -- + is a string operator too
Function calls can be operands in expressions:
x = 2 + f(5, 4) / f(-12, 10)
print(x)
The return statement stops execution. Any code after return is not reached:
def try_func():
print('I am printed')
return
print('I am not') # never executed
When Writing a Function, Consider:
- The input to the function
- The operations to be performed
- Which value to return
Functions Motivation
Programs can be conceived as series of smaller tasks. It is natural to define a function for each task.
Functions eliminate code repetition, enable better modularity, and ease maintenance of the code as it grows larger. Practically, it is a thinking exercise about identifying patterns in code and extracting them into functions.
More Function Examples
def my_func(): # no parameters
"""printing examples"""
print("*" * 10)
print('* SHALOM *')
print("*" * 10)
return
my_func()
def prod(x, y):
return x * y
prod(2, 5) # 10
prod('Iosi', 2) # 'IosiIosi'
def fahr2cels(deg):
return ((deg - 32) * (5 / 9))
f2c = fahr2cels(85) + 12
print(f2c)
def gurgle(sylab):
return (sylab * 5)
x = "The toddler just said :" + gurgle('ga')
y = "Le voisin dit :" + gurgle('bla')
print(x, y, sep='\n\n')
Main Ideas in This Lecture
- Basic data/values: numbers, characters
- Data structures: string, list, tuple (containers for basic data)
- Classes and their objects -- a taste of OOP ideas
- Python tools: arithmetic and comparison operators, built-in functions, function libraries
- Naming objects: variables, the assignment operator, binding/rebinding/unbinding
- Functions: gathering a block of statements for a defined task, defining and calling functions, using function calls as operands in expressions