Functions in Python
A function lets us create a set of instructions that we can run when needed.
Functions are essential in Python and in many other programming languages. They help us create meaningful programs, because they allow us to decompose a program into manageable parts, and they promote readability and code reuse.
Here is an example function called hello that prints "Hello!":
def hello():
print('Hello!')
This is the function definition. Thereis a name (hello) and a body, the set of instructions, which is the part that follows the colon. It's indented one level on the right.
To run this function, we must call it. This is the syntax to call the function:
hello()
We can execute this function once, or multiple times.
The name of the function, hello, is very important. It should be descriptive, so anyone calling it can imagine what the function does.
A function can accept one or more parameters:
def hello(name):
print('Hello ' + name + '!')
In this case we call the function by passing the argument
hello('Roger')
We call parameters the values accepted by the function inside the function definition, and arguments the values we pass to the function when we call it. It's common to get confused about this distinction.
An argument can have a default value that's applied if the argument is not specified:
def hello(name='my friend'):
print('Hello ' + name + '!')
hello()
#Hello my friend!
Here's how we can accept multiple parameters:
def hello(name, age):
print('Hello ' + name + ', you are ' + str(age) + ' years old!')
In this case we call the function passing a set of arguments:
hello('Roger', 8)
Parameters are passed by reference. All types in Python are objects, but some of them are immutable, including integers, booleans, floats, strings, and tuples. This means that if you pass them as parameters and you modify their value inside the function, the new value is not reflected outside of the function:
def change(value):
value = 2
val = 1
change(val)
print(val) #1
If you pass an object that's not immutable, and you change one of its properties, the change will be reflected outside.
A function can return a value, using the return statement. For example in this case we return the name parameter name:
def hello(name):
print('Hello ' + name + '!')
return name
When the function meets the return statement, the function ends.
We can omit the value:
def hello(name):
print('Hello ' + name + '!')
return
We can have the return statement inside a conditional, which is a common way to end a function if a starting condition is not met:
def hello(name):
if not name:
return
print('Hello ' + name + '!')
If we call the function passing a value that evaluates to False, like an empty string, the function is terminated before reaching the print() statement.
You can return multiple values by using comma separated values:
def hello(name):
print('Hello ' + name + '!')
return name, 'Roger', 8
In this case calling hello('Syd') the return value is a tuple containing those 3 values: ('Syd', 'Roger', 8).
Objects in Python
Everything in Python is an object.
Even values of basic primitive types (integer, string, float..) are objects. Lists are objects, as are tuples, dictionaries, everything.
Objects have attributes and methods that can be accessed using the dot syntax.
For example, try defining a new variable of type int:
age = 8
age now has access to the properties and methods defined for all int objects.
This includes, for example, access to the real and imaginary part of that number:
print(age.real) # 8
print(age.imag) # 0
print(age.bit_length()) #4
# the bit_length() method returns the number of bits necessary to represent this number in binary notation
A variable holding a list value has access to a different set of methods:
领英推荐
items = [1, 2]
items.append(3)
items.pop()
The methods depend on the type of value.
The id() global function provided by Python lets you inspect the location in memory for a particular object.
id(age) # 140170065725376
Your memory value will change - I am only showing it as an example.
If you assign a different value to the variable, its address will change, because the content of the variable has been replaced with another value stored in another location in memory:
age = 8
print(id(age)) # 140535918671808
age = 9
print(id(age)) # 140535918671840
But if you modify the object using its methods, the address stays the same:
items = [1, 2]
print(id(items)) # 140093713593920
items.append(3)
print(items) # [1, 2, 3]
print(id(items)) # 140093713593920
The address only changes if you reassign a variable to another value.
Some objects are mutable, while others are immutable. This depends on the object itself.
If the object provides methods to change its content, then it's mutable. Otherwise it's immutable.
Most types defined by Python are immutable. For example an int is immutable. There are no methods to change its value. If you increment the value using
age = 8
age = age + 1
#or
age += 1
and you check with id(age), you will find that age points to a different memory location. The original value has not mutated, we just switched to another value.
Loops in Python
Loops are one essential part of programming.
In Python we have 2 kinds of loops: while loops and for loops.
while loops in Python
while loops are defined using the while keyword, and they repeat their block until the condition is evaluated as False:
condition = True
while condition == True:
print("The condition is True")
This is an infinite loop. It never ends.
Let's halt the loop right after the first iteration:
condition = True
while condition == True:
print("The condition is True")
condition = False
print("After the loop")
In this case, the first iteration is run, as the condition test is evaluated to True. At the second iteration, the condition test evaluates to False, so the control goes to the next instruction after the loop.
It's common to have a counter to stop the iteration after some number of cycles:
count = 0
while count < 10:
print("The condition is True")
count = count + 1
print("After the loop")
for loops in Python
Using for loops we can tell Python to execute a block for a pre-determined amount of times, up front, and without the need of a separate variable and conditional to check its value.
For example we can iterate the items in a list:
items = [1, 2, 3, 4]
for item in items:
print(item)
Or, you can iterate a specific amount of times using the range() function:
for item in range(04):
print(item)
range(4) creates a sequence that starts from 0 and contains 4 items: [0, 1, 2, 3].
To get the index, you should wrap the sequence into the enumerate() function:
items = [1, 2, 3, 4]
for index, item in enumerate(items):
print(index, item)
Break and continue in Python
Both while and for loops can be interrupted inside the block, using two special keywords: break and continue.
continue stops the current iteration and tells Python to execute the next one.
break stops the loop altogether, and goes on with the next instruction after the loop ends.
The first example here prints 1, 3, 4. The second example prints 1:
items = [1, 2, 3, 4]
for item in items:
if item == 2:
continue
print(item)
items = [1, 2, 3, 4]
for item in items:
if item == 2:
break
print(item)