Download lecture02

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
COMPSCI 107
Computer Science Fundamentals
Lecture 2 - Elements of Python
1
Getting user input
•
the “input” function prints a string and then returns
whatever the user types in.
e.g. text = input("What is your command? ")
•
After this the "text" variable the value of what was
typed in (as a string).
•
If you need to convert it to a number you must
then do something like:
int(text)
float(text)
2
Input example function
The whole program is lecture02a.py
1. def
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
get_command_from_user(commands):
"""Ask for a valid command from the user and return that command.
A command is only valid if it appears in the list of commands.
"""
while True:
command = input("What is your command? ")
command = command.lower()
if command in commands:
return command
print("I am sorry your excellency, ", end="")
print('I do not understand "{}".'.format(command))
3
Notes on lines 1 to 4
def get_command_from_user(commands):
"""Ask for a valid command from the user and return that command.
A command is only valid if it appears in the list of commands.
"""
•
Line 1 is the function header, it tells us it takes one
parameter which is called “commands”.
•
Lines 2 to 4 are the docstring for the function.
•
This explains what the function will do. The first
line summarises the function and should be
written as a direct command (imperative).
4
Notes on lines 5 to 7
while True:
command = input("What is your command? ")
command = command.lower()
•
Line 5 - this is the standard way to deal with a loop that
may loop forever, as we will see shortly the condition after
the “while” normally becomes False at some time. In this
case it is always True which means the loop goes on
forever (an infinite loop) we use another way of getting out
of this loop.
•
Line 6 - accepts input from the user.
•
Line 7 - converts the characters in the “command” string to
lower case. This produces a new string which is then
assigned back to the variable “command”. This is because
Python strings are immutable, they cannot change.
5
Notes on lines 8 & 9
if command in commands:
return command
•
The “in” operator returns True if the value of
“command” appears as an element in the list
“commands”, otherwise it returns False.
•
Line 9 is the way we use to get out of the infinite
loop in this case it also returns the value of
“command”.
•
Another way to break out of an infinite loop is with
the “break” keyword. This makes control jump to
the statement following the loop.
6
Notes on lines 10 & 11
print("I am sorry your excellency, ", end="")
print('I do not understand "{}".'.format(command))
•
end = “”
•
•
This means that when the output is printed it will be followed with an
empty string. Without this the print function output will be followed
by a newline character, which means it will move to a newline for
further output. This way we can keep the output on the same line.
Line 11
•
Note the use of single quotes for the string so that I could embed
double quotes in the output.
•
The format function operates on a string to format its value before
we print it. The {} in the string is replaced with the string value of the
variable “command”.
7
The main program
1.
2.
3.
4.
SESAME = "open sesame"
GIVE_ME = "give me your money"
TIME = "tell me the time"
QUIT = "quit"
6.
7.
8.
9.
10.
11.
my_commands = [
SESAME,
GIVE_ME,
TIME,
QUIT
]
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
command = ""
while command != QUIT:
command = get_command_from_user(my_commands)
if command == SESAME:
open_sesame()
elif command == GIVE_ME:
give_me_your_money()
elif command == TIME:
tell_time()
print("Goodbye")
8
Notes on lines 1-11
•
Names for variables in all capitals are by convention
constant values and shouldn’t be modified in your code.
•
The names SESAME, GIVE_ME, TIME, and QUIT are
used as constants here instead of retyping the
corresponding string values at multiple times in the
code. This saves mistakes due to mistyping.
•
The "my_commands" list shows that in between the "["
and "]" we can have lists which extend over multiple
lines.
9
Notes on lines 13-21
command = ""
while command != QUIT:
command = get_command_from_user(my_commands)
if command == SESAME:
open_sesame()
elif command == GIVE_ME:
give_me_your_money()
elif command == TIME:
tell_time()
•
•
This is a more traditional use for a while loop.
•
In this case a variable is set before entering the while loop "command".
•
The loop keeps repeating until "command" is equal to QUIT.
The "elif" keyword is short for "else if" and is like an "else"
followed by an "if" statement.
•
So only one of the function calls "open_sesame()",
"give_me_your_money()" or "tell_time()" is called.
10
Telling the time
•
If the user enters "tell me the time" the tell_time()
function is called.
import datetime # our first module import
def tell_time():
"""Tell the time."""
time_now = datetime.datetime.now().time()
print("The time is {}.".format(time_now))
11
Modules
•
Python programs consist of modules, you can think of a module as a file of
Python code.
•
To use one module from another you "import" the module.
•
You say "import filename" where filename is the Python file you want to
import but without the ".py" on the end.
•
Then to use any code or variables in the module you use the module name
followed by a "." followed by the name of the function or other Python
object in the module.
•
Things in modules are called attributes.
•
So "datetime.datetime.now()" accesses the datetime class in the datetime
module and calls the now function (actually method) from it.
12
Module example
A file called hi.py
# A small module for demonstation.
hello = "Welcome to COMPSCI 107."
def say_hello():
"""Welcomes a 107 student."""
print(hello)
Used by lecture02b.py
# lecture02b.py
import hi
hi.say_hello()
print(hi.hello)
13
Alternatively
You can import only specific parts of a module and
can then access them more conveniently.
Normally I don’t recommend this but it is acceptable.
It is good to know what module things come from
without having to scroll back to the import lines.
# lecture02c.py
from hi import say_hello
say_hello()
14
Python variables
lecture02d.py
•
Python variables are different from many other languages,
•
they aren’t names of boxes (addresses) in memory
•
they are more like labels attached to values
•
e.g.
see: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables
def compare_a_and_b(a,
print("The id of a
print("The id of b
if a == b:
print("a and b
if a is b:
print("a and b
b):
is", id(a))
is", id(b))
are equal to each other")
are names for the same object")
x = "CompSci107"
y = x
compare_a_and_b(x, y)
x = "".join(("CompSci", "107"))
compare_a_and_b(x, y)
15
Clean interfaces and
information hiding
•
One of the principles of good programming is to be
very clear about the connections between different
components in our programs.
•
This is why Python has modules. We have to explicitly
name the connections we want to use from another
module. The use of the dot notation "." with the module
name means the name is unique within our program.
•
Another way of reducing name conflicts is with the
concept of scope.
16
Scope
•
Scope refers to the area of a program where a
particular name refers to the same item (or object).
•
In the following example the "available_locally"
variable can only be accessed in the function and
the "available_globally" can be accessed (but not
modified in a function) anywhere in the module
(after the line it is assigned to).
•
Parameters in function definitions are also in the
local scope of the function.
17
# lecture02e.py
available_globally = 7 * 11 * 13
def demo():
available_locally = 11 * 13 * 17
print("in demo available_globally is", available_globally)
print("in demo available_locally is", available_locally)
demo()
print("outside demo available_globally is", available_globally)
print("outside demo available_locally is", available_locally)
•
and of course you can’t use the value of a variable
until you have assigned it a value
•
that is why we get the error from the last line
18
Scope help in Python
•
Python tries to help you use good style by not allowing you
to assign to a module global variable in a function unless
you explicitly use the "global" keyword. This is true if in any
part of the function you assign to the variable.
•
You can however get the value of the variable without
having to use "global".
•
It is generally not a good idea to use the same name both
in module global scope and in a function.
•
But you will see this for parameters, and this is
acceptable.
19
What is output by this
program?
# lecture02f.py
# followed by
def test1():
b = "local b"
print(a)
print(b)
a = "module global a"
b = "module global b"
test1()
print()
def test2(a):
b = "local b"
print(a)
print(b)
test2(a)
print()
def test3():
print(a)
print(b)
test2(b)
print()
test3()
print()
def test4(a):
print(a)
a = "local a"
print(a)
def test5():
global a # see what happens if you remove
print(a)
a = "local a"
print(a)
20
test4(a)
print(a)
print()
test5()
print(a)
Using "global"
•
"global" allows any references in a function to a variable to be
applied to the module global variable with that name.
•
Generally we don’t use "global". Shortly we will see that using
classes means you don’t need to.
•
For labs 1 and 2 you may use "global" for the text editor program
(there are other ways around this but it is acceptable for these 2
labs to use "global").
•
If you only use a global value but never assign to it you should
pass the global variable in as a parameter.
•
Similarly you could return values from the function and assign
the returned values to the module global variables.
21
Main program or import
•
Whenever you import a module all of the code outside
functions is executed at the time of import (sort of).
•
Sometimes we only want some of the "top level" code
to run. We can do this:
if __name__ == "__main__":
# The following only gets executed if the module is run as a program
# rather than being imported.
line_buffer = []
current_line = 0
•
__name__ holds the name of the module but it is
"__main__" if the module is being run as a program.
22
When you are working on
your lab/assignment work
•
We are using a system called CodeRunner which
runs your programs and checks whether they work
properly.
•
Do NOT just type your work into the CodeRunner
window, you should edit and run/test your code in
Idle or from the command prompt.
23