0% found this document useful (0 votes)
6 views14 pages

55284A - Introduction To Python - Chapter2

This lesson covers the fundamentals of defining and calling functions in Python, including parameters, default values, variable scope, and return values. It also discusses creating and importing modules, emphasizing the distinction between global and local variables, and how to manage them effectively. Additionally, the lesson provides examples of using function parameters to enhance code flexibility and maintainability.

Uploaded by

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

55284A - Introduction To Python - Chapter2

This lesson covers the fundamentals of defining and calling functions in Python, including parameters, default values, variable scope, and return values. It also discusses creating and importing modules, emphasizing the distinction between global and local variables, and how to manage them effectively. Additionally, the lesson provides examples of using function parameters to enhance code flexibility and maintainability.

Uploaded by

mhetre2017
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

LESSON 2: Functions and Modules

Topics Covered

Defining and calling functions.

Parameters
Th and arguments.
is
do
c
Default valuesufor
me parameters.
nt
be
lon
Variable scope.No ja gta gs to
un p NI
au nilka LK
t
Return values. h o riz
n t @ ANT
ed re ES
co diff.c HW
pie
Creating and importing modules.s a om AR
JA
llo GT
we AP
d! .

It is your duty as a magistrate, and I believe and hope that your feelings as a man will not revolt from the
execution of those functions on this occasion.
– Frankenstein, Mary Shelley
Th
is
do
cu
m
Introduction tb
en
elo
n
No agta gs to
j
un pn NI
uth ilkanbuilt-in
You have seen some of aPython’s LK functions. In this lesson, you will learn to write your own.
ori t@ ANT
ze
d c rediff ESH
op . WA
ies com
Defining Functions all
ow
R
JA
GT
ed AP
! .
We discussed functions a little in the last lesson, but let’s quickly review the syntax. Functions are defined in Python
using the def keyword. The syntax is as follows:

Th
def function_name():
is
oc d
umfunction is indented
# content of
en
t
do_something() belo
gs n
No jagpart
# This is no longer t t the function
of
un apni o NI
a u
do_something_else() th lk an LKA
t N
@ ori T
ze
d c rediff ESH
op .co WA
ies m R
all JA
ow exercise:
Here is a modified solution to the “Hello, You!” GT
ed AP
! .

Demo 7: functions/Demos/hello_you.py

1. def say_hello():
2. your_name
T = input("What is your name? ")
his
3. do
print("Hello, ", your_name, "!", sep="")
c um
4. en
tb
elo
5. def main(): jag ng
N s
6. say_hello()
7.
8. main()

Code Explanation

Th in the same way, but the meat of the program has been moved out of the main() function and
The code works is
do
cu This is common. Usually, the main() function handles the flow of the program, but the actual
into another function. me
“work” is done by other nfunctions
tb
elo in the module.
ja ng
No gt st
un apni o NI
The following expanded ademo
uth lkfurther
a LKillustrates how the main() function can be used to control flow.
ori nt@ ANT
ze
d c rediff ESH
op . WA
Demo 8: functions/Demos/hello_you_expanded.py ies com R
all JA
ow GT
ed AP
! .
1. def say_hello():
2. your_name = input("What is your name? ")
3. insert_separator()
4. print("Hello, ", your_name, "!", sep="")
5. Th
is
do
6. cu
def insert_separator():
me
7. nt
print("===")belo
n
8. No jagta gs to
u na p n N
9. uth ilkan ILKA
def recite_poem():
ori t NT
ze a @Monty
d c rediff ESH
10. print("How about Python poem?")
o . c WA
11. insert_separator() pie o
sa m R
llo Dad's JA GT
12. print("Much to his Mum and we dismay")
AP
d! .
13. print("Horace ate himself one day.")
14. print("He didn't stop to say his grace,")
15. print("He just sat down and ate his face.")
16.
17. def say_goodbye():
Th
i
sd
18. print("Goodbye!")
o cu
men
19. tb
elo
20. def main(): n
No agta gs to
j
21. u na
say_hello() p n N
uth ilkan ILKA
ori t N
22. insert_separator() ze @red TES
dc iff. HW
op
23. recite_poem()
ies com AR
all JA
24. insert_separator() ow GT
ed AP
25. say_goodbye() ! .
26.
27. main()

Th
Code Explanation
is
do
cu
me
The preceding code willntrender
be the following:
lon
N ja g g s
What is your name? Nat
===
Hello, Nat!
===
How about a Monty Python poem?
===
Much to his
T Mum and Dad's dismay
his
do
Horace ate himself one day.
c um
He didn't stop to esay
nt his grace,
b elo
He just sat down ng his face.
jag ate
No and tap s to
un NI
=== au nilkan LK
tho
t@ ANT
Goodbye! re riz ES
ed
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d! .
Not All Modules are Programs

Not all Python modules are programs. Some modules are only meant to be used as helper files for other programs. Sometimes these modules
are more or less generic, providing functions that could be useful to many different types of programs. And sometimes these modules are written
to work with a specific program. Modules that aren’t programs probably wouldn’t have a main() function.

T
Variable hScope
is
do
c um
en
tb
elo
n
No agta gthe
Question: Why j
doesn’t s t say_goodbye() function use the user’s name (e.g., print("Goodbye,",
oN
u
your_name))? na p n
uth ilkan ILKA
ori t N
ze @red TES
dc
op iff .co HWA
Answer: It doesn’t know what ieyour_name
sa m Ris.
llo JA
we GT
d! AP
.
Variables declared within a function are local to that function. Consider the following code:

Demo 9: functions/Demos/local_var.py

Th
1. is
def set_x():
d oc
um
2. x = 1 en
tb
3. elo
n
No agta gs to
j
4. def get_x():u
na p n N
uth ilkan ILKA
5. print(x) ori t N
ze @red TES
6. dc iff. HW
op
ies com AR
7. def main(): all JA
ow GT
ed AP
8. set_x() ! .
9. get_x()
10.
11. main()

Th
is
Code Explanationdo
cu
me
nt
be
lon
jagerror
Run this and you’ll Nget an gssimilar to the following:
NameError: name 'x' is not defined

That’s because x is defined in the set_x() function and is therefore local to that function.

A good Python IDE, like Visual Studio Code, will let you know when it detects such an error. In VS Code, a squiggly
underline will appear beneath the undefined variable. Depending on how your settings are configured, you may be
able to hoverThover
is the variable to see the error:
do
cu
me
nt
be
lon
No ja gta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
llo GT
we AP
d! .

Th
is
do
cu
men
tb
elo
Global Variables No agta gs to
j n
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
Global variables are defined outside co ofdiaff.cfunction
HW as shown in the following demo:
pie o AR
sa m JA
llo GT
Demo 10: functions/Demos/global_var.py we AP
d! .

1. x = 0
2.
3. def set_x():
4. Th= 1
x is
do
cu
5. m
print("from set_x():", x)
en
tb
6. elo
ja ng
7. N ou
def get_x(): g tap s to
na nil NI
ka
print("fromuthget_x():",
LK x)
8.
ori n t AN
ze @red TES
dc
op iff.co HWA
9.
10. def main(): ies m R
all JA
ow GT
11. set_x() ed AP
! .
12. get_x()
13.
14. main()

Th
is
Code Explanationdo
cu
m en
tb
elo
jag ng
N s
x is first declared outside of a function, which means that it is a global variable.

Question: What do you think the get_x() function will print: 0 or 1?

Answer: It will print 0. That’s because the x in set_x() is not the same as the global x. The former is local
to theTset_x() function.
his
do
cu
me
nt
Global variables, by default,be can be referenced but not modified within functions:
lon
No ja gta gs to
un pn N
uth ilkan Iwithin
When a variable isareferenced LK a function, Python first looks for a local variable by that name. If it
ori t@ ANT
doesn’t find one, then it looksze re
for da ES variable.
global
dc
op iff.co HWA
ies m R
When a variable is assigned withinala J
lowfunction, itAwill
GT be a local variable, even if a global variable with the same
ed AP
name already exists. ! .

To modify global variables within a function, you must explicitly state that you want to work with the global variable.
That’s done using the global keyword, like this:
Th
is
do
cu
Demo 11: functions/Demos/global_var_in_function.py
me
nt
be
lon
1. x = 0 No agta gs to
j
un p NI
au nilka L
2. tho nt@ KAN
riz re TE
ed SH
3. def set_x(): co diff.c
pie om WAR
4. global x sa JA
llo GT
we AP
5. x = 1 d ! .
6.
7. def get_x():
8. print(x)
9.
10. Th
def main():
is
do
11. set_x() cu
m en
12. get_x() tb
elo
ja ng
13. Nou g tap s to
na n N
14. main() uth ilkan ILKA
ori t N
ze @red TES
dc iff. HW
op
ies com AR
all JA
Code Explanation ow GT
ed AP
! .

Now, the set_x() function explicitly references the global variable x, so the code will print 1.

Naming global variables?


Th
is
do
cu
men
tb
elo
jag ng
N s
Naming global variables?

Some developers feel that any use of global variables is bad programming. While we won’t go that far, we do have two recommendations:
1. Prefix your global variables with an underscore10 (e.g., _x). That makes it clear that the variable is global and minimizes the chance
of it getting confused with a local variable of the same name. It is also a convention that lets developers know that those variables are
not meant to be used outside the module (i.e., by programs importing the module).

2. When possible, rather than using global variables, design your code so that values can be passed from one function to another using
This (see next section).
parameters
do
cu
men
tb
elo
n
Function Parameters
No jagta gs to
u p N
nil na
ILK
ka uth
ori nt@ ANT
ze
d c rediff ESH
Consider the insert_separator() op function
. inAthe hello_you_expanded.py file that we saw earlier:
W
ies com R
all JA
ow GT
ed AP
! .
def insert_separator():
print("===")

What if we wanted
Th to have different types of separators? One solution would be to create multiple functions, like
is
do
insert_large_separator() and insert_small_separator(), but that can get pretty tiresome and hard to
cu
me
maintain. A better solution is to use function parameters using the following syntax:
nt
be
lon
No jagta gs to
un p NI
au nilka LK
tho nparam2, A
def function_name(param1, riz t@re NTparam3): ES
ed d HW
do_something(param1, param2, co iff. param3)
pie c o AR
sa m JA
llo GT
we AP
d! .
Here is our “Hello, You!” program using parameters:

Demo 12: functions/Demos/hello_you_with_params.py

1. Th
def say_hello(name):
is
do
2. cu
print('Hello, ', name, '!', sep='')
m en
3. tb
elo
n
4. No agta gs to
j
def insert_separator(s):
un pn NI
au s, ilsep="") LK
5. print(s, s, tho kant
riz @ ANT
6. ed re ES
co diff.c HW
pie o AR
7. def recite_poem(): sa m JA
llo GT
8. print("How about a Monty wPython ed AP
poem?")
! .
9. insert_separator("-")
10. print("Much to his Mum and Dad's dismay")
11. print("Horace ate himself one day.")
12. print("He didn't stop to say his grace,")
13. print("He
T just sat down and ate his face.")
his
14. do
cu
en m
15. def say_goodbye(name):
t be
lo
ng ', name, '!', sep='')
16. ja
print('Goodbye,
N s g
17.
18. def main():
19. your_name = input('What is your name? ')
20. insert_separator("-")
21. say_hello(your_name)
22. insert_separator("=")
23. recite_poem()
Th
is
24. do
insert_separator("=")
cu
25. me
say_goodbye(your_name)
n tb
26.
elo
n
No jagta gs to
27. main() un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
Code Explanation sa JA
llo GT
we AP
d! .
Now that insert_separator() takes the separating character as an argument, we can use it to separate lines
with any character we like.

We have also modified say_hello() and say_goodbye() so that they receive the name of the person they are
addressing as
Th an argument. This has a couple of advantages:
is
do
cu
me
1. We can move your_name nt = input('What is your name? ') to the main() function so we can pass
be
your_name into both l o
say…
n functions.
No jagta gs to
un pn
au ilka NILK
2. We can move the call thoto insert_separator()
n A out of the say_hello() function as the separator doesn’t
riz t@re NTE
have anything to do with saying ed d
“hello.” S H
co if
pie f.com WAR
sa JA
llo GT
we AP
d! .
Parameters vs. Arguments

The terms parameter and argument are often used interchangeably, but there is a difference:
Parameters are the variables in the function definition. They are sometimes called formal parameters.
Arguments are the values passed into the function and assigned to the parameters. They are sometimes called actual parameters.
Th
is
do
cu
m en
tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d! .

Using Parameter Names in Function Calls


Th
is
do
When calling a function, you can specify the parameter by name when passing in an argument. When you do so,
cu
m
it’s called passing in a ekeyword
nt argument. For example, you can call the following divide() function in several
be
ways: l o
N jag ngs
def divide(numerator, denominator):
return numerator / denominator

divide(10, 2)
divide(numerator=10, denominator=2)
divide(denominator=2, numerator=10)
divide(10,
T denominator=2)
his
do
cu
men
tb
As you can see, using keyword elo arguments allows you to pass in the arguments in an arbitrary order. You can
n
No jagta gs to
combine non-keyworduarguments with keyword arguments in a function call, but you must pass in the non-keyword
na pnilk NIL
arguments first. u t ho a n KA
riz t@re NTE
ed SH
co diff.c
pie om WAR
Later, we’ll see that a function can be swritten
all to require
JA keyword arguments.
ow GT
ed AP
! .

Exercise 6: A Function with Parameters

T15
histo 25 minutes
do
cu
me
nt
be
lon
In this exercise, you No agta agsfunction
willj write for adding two numbers together.
un pn to NI
au il LK
tho kant AN
r
1. Open functions/Exercises/add_nums.pyize @ T in your editor and review the code.
d c rediff ESH
op .co WA
ies m R
2. Now, run the file in Python. The output all should Jlook
AG like this:
ow TA
ed P.
!

3 + 6 = 9
10 + 12 = 22

3. Ththe two crazy add…() functions with an add_nums() function that accepts two numbers, adds them
Replace is
do
together, andcoutputs
um the equation.
en
tb
elo
n
No jagta gs to
un pn NI
au il LK
tho kant
Exercise Code: functions/Exercises/add_nums.py
riz @ ANT
ed re ES
co diff.c H
pie om WAR
1. def add_3_and_6(): s all JA
ow GT
2. total = 3 + 6 e d! AP
.
3. print('3 + 6 = ', total)
4.
5. def add_10_and_12():
6. total = 10 + 12
7. Th
print('10 + 12 = ', total)
is
do
8. cu
men
9. def main(): tb
elo
ja ng
10. N g
add_3_and_6() s
11. add_10_and_12()
12.
13. main()

Code Explanation

Th adds 3 and 6. The second function adds 10 and 12. These functions are only useful if you want to
The first function
is
d
add those specificocnumbers.
um
en
tb
elo
n
No jagta gs to
Solution: functions/Solutions/add_nums.py
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
1. def add_nums(num1, num2): co diff.c
pie om WAR
2. total = num1 + num2 s a JA
llo GT
we A
3. print(num1, '+', num2, ' = d', ! total) P.
4.
5. def main():
6. add_nums(3, 6)
7. add_nums(10, 12)
8. Th
is
do
9. main() cu
men
tb
elo
n
No agta gs to
j
Code Explanation u na p n N
uth ilkan ILKA
ori t N
ze @red TES
dc iff HW
The add_nums() function is flexible op and.creusable.AR It can add any two numbers.
ies om
all JA
ow GT
ed AP
Default Values ! .

Parameters that do not have default values require arguments to be passed in. You can assign default values to
parameters using the following syntax:

Th
is
do
def function_name(param=default):
c um
en
do_something(param)
t be
lon
No jagta gs to
un p NI
au nilka LK
For example, the following thcode
ori n
would
t Amake
N the “=” sign the default separator:
ze @red TES
dc
op iff.co HWA
ies m R
all JA
ow GT
def insert_separator(s="="): ed AP
! .
print(s, s, s, sep="")

When an argument is not passed into a parameter that has a default value, the default is used.

Th
is
See functions/Demos/hello_you_with_defaults.py
do to see a working demo.
cu
me
nt
be
lon
N ja g gs
Exercise 7: Parameters with Default Values

15 to 25 minutes

Th
is you will write a function that can add two, three, four, or five numbers together.
In this exercise, do
cu
me
nt
be
1. Open functions/Exercises/add_nums_with_defaults.py
lon in your editor.
No ja gta gs to
un p NI
2. Notice the add_nums() au nilfunction LK takes five arguments, adds them together, and outputs the sum.
tho kant
riz @ ANT
ed red ES
3. Modify add_nums() so thatcoitpcaniffaccept .co HWallARof the following calls:
ies m
all JA
ow GT
ed AP
! .
add_nums(1, 2)
add_nums(1, 2, 3, 4, 5)
add_nums(11, 12, 13, 14)
add_nums(101, 201, 301)

Th
is
do
cu
4. For now, it’s okayme for the function to print out 0s for values not passed in, like this:
nt
be
lon
No agta gs to
j
1 + 2 + 0 + 0un+ p
au 0 n= il 3NILK
tho kant
1 + 2 + 3 + 4 + 5 riz=e 15 @ ANT
d c rediff ESH
11 + 12 + 13 + 14 + 0 o=pie 50.com WAR
sa JA
101 + 201 + 301 + 0 + 0 = ll603 ow GT
ed AP
! .

Exercise Code: functions/Exercises/add_nums_with_defaults.py

Th
is
1. do
def add_nums(num1, num2, num3, num4, num5):
c u
me
2. nt + num2 + num3 + num4 + num5
total = num1be
lon
3. jag '+',
print(num1,
N gs num2, '+', num3, '+', num4, '+', num5, ' = ', total)
tap ou to
n naN
4. uth ilkan ILKA
ori t N
5. def main(): ze @red TES
dc
6. add_nums(1, 2, 0, 0, op 0)f.co HWA
if
ies m R
a JA
7. add_nums(1, 2, 3, 4, 5) llow GT
AP
ed
! .
8. add_nums(11, 12, 13, 14, 0)
9. add_nums(101, 201, 301, 0, 0)
10.
11. main()

Th
is
do
cu
en m
tb
Solution: functions/Solutions/add_nums_with_defaults.py
elo
ja ng
N g s
1. def add_nums(num1, num2, num3=0, num4=0, num5=0):
2. total = num1 + num2 + num3 + num4 + num5
3. print(num1, '+', num2, '+', num3, '+', num4, '+', num5, ' = ', total)
4.
5. def main():
6. add_nums(1, 2)
7. add_nums(1,
T 2, 3, 4, 5)
his
8. do
add_nums(11, 12, 13, 14)
c um
en
9. t b 201, 301)
add_nums(101,
elo
n
10. No jagta gs to
un p NI
11. main() au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
Code Explanation sa JA
llo GT
we AP
d! .
We have given the last three parameters default values of 0, making them optional. The first two parameters don’t
have default values, so they are still required.

Returning Values
Th
is
do values. The add_nums() function we have been working with does more than add the
Functions can return cu
m
numbers passed in, it ealsont prints them out. You can imagine wanting to add numbers for some other purpose than
be
printing them out. Or you lon want to print the results out in a different way. We can change the add_nums()
might
No agta gs to
j
function so that it just uadds
na the pn numbers together and returns the sum. Then our program can decide what to do
ilka NILK
uthat the
with that sum. Take a look ori n
following
t A N code:
ze @red TES
dc
op iff.co HWA
ies m R
Demo 13: functions/Demos/add_nums_with_return.py all JA
ow GT
ed AP
! .
1. def add_nums(num1, num2, num3=0, num4=0, num5=0):
2. total = num1 + num2 + num3 + num4 + num5
3. return total
4.
5.
T
his
def main():
do
cu = add_nums(1, 2)
6. result m en
be t
7. print(result) lo
jag ngs
resultNo= add_nums(result,
t t
un apni o NI
8. 3)
au lka LK
9. print(result) tho n A
riz t@re NTE
e dc d S4)
op iff.co HWA
10. result = add_nums(result,
ies m R
11. print(result) all JA
ow GT
12. result = add_nums(result, 5) e d! AP
.
13. print(result)
14. result = add_nums(result, 6)
15. print(result)
16.
17. Th
main()
is
do
cu
men
tb
elo
Code Explanation jag ng
N s
The add_nums() function now returns the sum to the calling function via the return statement. We assign the
result to a local variable named result. Then we print result and pass it back to add_nums() in subsequent
calls.

Note that once a function has returned a value, the function is finished executing and control is transferred back to
the code that invoked the function.

Th
Importing iModules
sd
oc
um
As we saw, part of theebeauty
nt
be of writing functions is that they can be reused. Imagine you write a really awesome
lon
function. Or even better,
No jaagtamodule gs with a whole bunch of really awesome functions in it. You’d want to make those
p to
functions available to uother
na modules
n N so you (and other Python developers) could make use of them elsewhere.
uth ilkan ILKA
ori t@ NT
ze
d c rediff ESH
Modules can import other modulesopusing WA
. o import
ies cthem R
keyword as shown in the following example:
all JA
ow GT
ed AP
Demo 14: functions/Demos/import_example.py ! .

1. import add_nums_with_return
2.
3. total = add_nums_with_return.add_nums(1, 2, 3, 4, 5)
Th
is
4. do
print(total)
cu
m en
tb
elo
ja ng
Code Explanation oN g t st
un apni o NI
au lka LK
tho n A
riz t@re NTE
Now, the add_nums() functionedfrom co d SH
add_nums_with_return.py
if is available in import_example.py;
pie f.com WAR
sa JA
llo GT
we
however, it must be prefixed with “add_nums_with_return.” AP (the module name) when called.
d! .

The main() Function

It is common for a module to check to see if it is being imported by checking the value of the special __name__ variable. Such a module will only
run its main() function if __name__ is equal to '__main__', indicating that it is not being imported. The code usually goes at the bottom of the
Th like this:
module and looks
is
do
cu
me
if __name__ == '__main__':
nt
main() be
lon
No jagta gs to
un p NI
au nilka L
tho before
Note that those are two underscores nt@andKA NT name and before and after main.
after
r i z r E
ed atehttps://bit.ly/python_main.
A short video explanation of this is available
co d iff. SHW
pie c o AR
sa m J
Another way to import functions from another l low moduleAG isTto
ed APuse the following syntax:
! .

from module_name import function1, function2

For example:Thi
sd
oc
um
en
tb
Demo 15: functions/Demos/import_example2.py
elo
ja ng
N g s
1. from add_nums_with_return import add_nums
2.
3. total = add_nums(1, 2, 3, 4, 5)
4. print(total)

When you use this approach, it is not necessary to prefix the module name when calling the function. However, it’s
Th
possible to haveis naming conflicts, so be careful.
do
cu
me
nt
be
Another option, which is helpful lon for modules with long names, is to create an alias for a module, so that you do not
ja g
N
have to type its full name:
ou g tap s to
na n N
uth ilkan ILKA
ori t@ NT
ze
d c rediff ESH
op .co WA
import add_nums_with_return as ies anwr m R
all JA
ow GT
ed AP
! .
total = anwr.add_nums(1, 2, 3, 4, 5)

Using aliases is also a way of preventing naming conflicts. If you import do_this from foo and do_this from
bar, you can use an alias to call one of them do_that:
Th
is
do
cu
me
nt
from foo import do_this be
lo
jag ngs
from bar importNodo_this tap asto do_that
un NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
llo GT
Module Search Path we AP
d! .
The Python interpreter must locate the imported modules. When import is used within a script, the interpreter
searches for the imported module in the following places sequentially:

1. The current directory (same directory as the script doing the importing).
Th
2. is of standard modules.11 3.
The library do
cu
me
nt
The paths defined in besys.path, which you can see by running the following code at the Python shell:
lon
No agta gs to
j
un p NI
au nilka LK
>>> import sys t h ori n t AN
ze @red TES
dc
>>> sys.path op iff.co HWA
ies m R
all JA
ow GT
ed AP
! .
This will output a list of paths, which are searched in order for the imported module.

pyc Files
Th
Files with a .pycis extension are compiled Python files. They are automatically created in a __pycache__ folder
do
c
the first time a file isum
imported:
en
tb
elo
ja ng
N g s
These files are created so that modules you import don’t have to be compiled every time they run. You can just
leave those files alone. They will automatically be created/updated each time you import a module that is new or
has been changed.
Th
is
do
cu
me
Methods vs. Functions nt
be
lon
No ja gta gs to
You have already seen unsome p built-in NI functions, like print() and input(). You have also written some of your
au nilka LK
own, like insert_separator() tho nt@
and A
divide().
N In the upcoming lessons, you will learn to use many more of
riz red TES
Python’s built-in functions. You will e d coalsoiflearn about methods, which are similar to functions, except that they are
H
p e f.com WAR
called on an object using the syntax iobject_name.method_name().
sa JA
llo GT
we AP
d! .
An example of a simple built-in function is len(), which returns the length of the passed-in object:

>>> len('Webucator')
9 Th
is
do
cu
en m
tb
An example of a method ofelaonstring object is upper(), which returns the string it is called upon in all uppercase
letters: No agta gs to
j
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
>>> Webucator'.upper() sa JA
llo GT
'WEBUCATOR' we AP
d! .

Again, you will work with many functions and methods in upcoming lessons.

Conclusion
T his
do
In this lesson, you chave
um learned to define functions with or without parameters. You have also learned about
en
variable scope and how ttobeimport
lon modules.
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz r e TE
ed SH
co diff.c
pie om WAR
10. https://www.python.org/dev/peps/pep-0008/#global-variable-names
sa JA
llo GT
we AP
d! .

11. https://docs.python.org/3/tutorial/modules.html#standard-modules

Th
is
do
cu
men
tb
elo
jag ng
N s

You might also like