IT 116: Introduction to Scripting
Class 4
Tips and Examples
Review
New Material
Studying
Microphone
Homework 2
I have posted homework 2
here.
It is due this coming Sunday at 11:59 PM.
First Graded Quiz
The first graded quiz will be given on Tuesday next week.
The questions from the graded quiz are taken from the ungraded quizzes of the
previous week.
Unless I tell you otherwise, you should expect a graded quiz each week.
The quiz will be available on Gradescope on Tuesday.
The quiz will be available from the Gradescope web site but only
for the last 15 minutes of the class.
Once you start the quiz, you will have 15 minutes to finish it.
If you do not take the quiz when it is offered you cannot take it
at another time because Gradescope does not permit this.
If you fail to take the quiz but have a valid excuse, send me an
email.
Gradescope
In order to take the quiz on Gradescope, you need to
sign in to my Gradescope section.
Sometime during the next few days I will enter all your UMB email
addresses into Gradescope.
You will receive an email from Gradescope.
What happens next depends on whether you have already registered with
Gradescope.
If you are new to Gradescope
- Click the "Set your password" link
- Confirm your password
- Click Save
- You will then be taken to the page for your course
If you are already registered with Gradescope
- Click the link to the course
- At the login screen enter your UMB email
address and your Gradescope password
- If you have forgotten you password, click the "Forgot
your password"link
You will find more information about Gradescope
here.
Recorded Class Meetings
You will links to the recording of class meetings
here
.
You will also find this link on the class web page.
Zoom Office Hours
You will find the link to the Zoom Office Hours meetings
here
.
You will also find this link on the class web page.
Questions
Are there any questions before I begin?
Tips and Examples
Creating Directories with FileZilla
- You need to create a new directory for each Class Exercise and
homework assignment
- You can do this in FileZilla
- First connect to pe15.cs.umb.edu
- Then drill down to either the ex
or hw directory
- Right click on the directory
- This will bring up a menu that will let you create a
directory
- You can also move files and directories in FileZilla by clicking
and dragging
Keeping Your Scripts Organized
- Organization is an important part of IT work
- You should keep all the scripts in one directory
on your personal machine
- This will make it easier to move them to FileZilla
- I would suggest you create a python
directory in your Documents directory
Using FileZilla to Fix Problems
- You may receive an email from me saying I cannot find an assignment
- If you know you created it, it's probably in the wrong directory ...
- or the file has the wrong name
- Either way, you can use FileZilla to fix it
- If a file is in the wrong place click and drag it to the right directory
- If the file has the wrong name right click on it ...
- and select Rename
Use Flash Cards to Prepare for Graded Quizzes
- To studying for the graded quizzes you need to study the Class Quizzes for the
previous week
- The best way to do this is to use flash cards
- You take an index card and write the question on one side ...
- and the answer on the other
- You should make a set of flash cards for each class
- Label them with the Class Number
- And put a rubber band around them
- I did this when taking courses for my Masters degree
- I would go through them on my way to work on the T
- There are programs that you can use to create virtual flash cards
- But it is better if you write your own cards
- The simple act of writing each card, helps you remember the material
- You can also use flash cards in reverse
- Turn them over, read the answer and guess the question
- This can be helpful when studying for the midterm or final
Review
Output
- The output of Python scripts is a stream of text
- You can create output in Python using
print
- To print my name to the screen, I would write
print("Glenn Hoffman")
- This line of code is a Python
statement
- A statement is one or more lines of code that performs a complete action
- The interpreter runs your script statement by statement
print
is a
function
- A function is a series of Python statements which has a name and performs some
task
- To run a function you write the name of the function followed by parentheses
- The parentheses may be empty
- But they usually contain one or more values called
arguments
- Statements of this type are called
function calls
Literals
- A value that is written directly into the code is called a
literal
Strings and String Literals
- All computer programs use different types of values
- The values can be words, numbers or other things
- When the value is just text, not a number, it is called a
string
- When we write a string directly inside the code it is a
string literal
- You can use either single (') or double
(") quotes when writing a string literal
- But you must use the same type of quote at the end of a string ...
- that you used at the beginning
Characters
- Everything in a computer's memory is a
binary number
- Binary number are written in powers of 2
- And appear using the digits 1 and
0
- To represent a character in the computer's memory, we need a number
- We get that number from a table
- The table contains a unique number for each character
Unicode
- The table of numbers and characters that we use in Python is called Unicode
- Unicode represents all the characters in most world writing systems
- There are many ways to represent the numbers that make up Unicode
- These representations are called encodings
- Python uses the
UTF-8
encoding
Variables
- In programming we often need to store a value that we will use later
- To do this, we create a
variable
- A variable is a location in the computer's memory that has a name ..
- and holds a single value
- In a many computer languages you have to specify what kind of
value the variable will hold
- This has to be done before you can use a variable
- So if you declared the variable rate to be an
integer ...
- you could not store a string in it
- This is not true in Python
- You can store a string in a Python variable one moment
- Then store an integer in it at some time later
Creating Variables with Assignment Statements
- You create a variable by giving it its first value
- This is done with an
assignment statement
- An assignment statement has the general form
VARIABLE_NAME = VALUE
- To create the variable name, and give it my name as
a value, I would write
name = "Glenn Hoffman"
Attendance
New Material
Expressions
Variable Naming Rules
- Computer languages are different from human languages
- They have very rigid rules
- In a human language there are many ways of saying the same thing
- People learning a new language can make themselves understood ...
- even if their grammar is not perfect
- That's because people are flexible
- But computers are not as flexible as people
- When you write a Python program it has to be understood by the Python
interpreter
- The Python interpreter is a computer program
- And it only understands what it has been programmed to understand
- When you write a Python program you must follow certain rules
- Or your program will not work
- Here are Python's rules for the names of variables
- You cannot use words that have special meaning to Python
as variable names
- Variable names cannot have spaces
- The first character of a variable name must be a letter,
a through z
and A through Z,
or an underscore, _
- After the first character you can use letters, digits or
the underscore
- Uppercase and lowercase letters are different
- Words that have special meaning to Python are called
keywords
- You can find a list of Python keywords in interactive mode
$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> help
Type help() for interactive help, or help(object) for help about object.
>>> help()
Welcome to Python 3.5's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.5/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".
help> keywords
Here is a list of the Python keywords. Enter any keyword to get more help.
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
- Python is
case sensitive
- That means that uppercase letters and lowercase letters are
completely different
- So value and Value are
different variables
- Here are some examples legal variable names
rate
rate_1
Rate_1
_rate
- Here are some examples of illegal variable names
guns&roses # can't use symbols in variable names
guns and roses # can't use spaces in variable names
1st_try # can't start a variable name with a digit
- Although you can use UPPERCASE letters in variable names
- It is better to use only lowercase letters
- An underscore, _, can be used to separate words in a variable name
first_name = "Bob"
Choosing Good Variable Names
- Just because a variable name is legal doesn't mean its a good variable name
- Consider the following code
d = s * t
- Can you guess what this is calculating?
- How about this
distance = speed * time
- Both expressions use legal variable names
- But the second is more informative than the first
- It is more readable
- The code you write makes sense to you right now
- But will it still make sense a year from now?
- The name of a variable should always describe the value it holds
- So speed is a good variable name
- But xena_the_warrior_princess is not
- Sometimes you need more than one word to describe the value contained in a
variable
- When this happens, you should use the underscore character,
_, to separate words
- Like this
course_id
student_name
first_name
- Another way to combine multiple words in a variable name is to capitalize the
first letter of each new word
- Like this
courseId
studentName
firstName
- This technique is called camel case
- I prefer to use underscores since I think they are more readable
- But you are free to use either technique
- You must do something to make the start of each word in name stand out
- I don't want to see
courseid
studentname
firstname
- They are not easy to read
- This is much better
course_id
student_name
first_name
Printing Multiple Values
- The
print
function can accept more than one argument
>>> room_1 = 92
>>> print("My room number is", room_1)
My room number is 92
- Notice that we used both a string literal ...
- and a variable separated by a comma
- Also notice that Python automatically put a space between the string and the
value of the variable
- There is no limit to the number of arguments
print
will accept
>>> room_2 = 93
>>> print("My room number is", room_1, "and my friend is staying in", room_2)
My room number is 92 and my friend is staying in 93
- You can also give
print
no arguments
- In case it will print a blank line
$ cat print_01.py
# Prints three lines, one blank
print("Line 1")
print()
print("Line 2")
$ python3 print_01.py
Line 1
Line 2
Numeric Data Types and Literals
- A Python variable can hold many different types of values
- Strings
- Integers
- Decimals
- Each type of value is stored in the computer's memory in a different format
- So the binary number that represent the string "5"
- Is different from the binary number that represent the integer 5
- And the one that represent the decimal value 5.0
- The technical term for each of these different representations is a
data type
- Any Python variable can hold any kind of value
- Changing the data type of a value assigned to a variable causes no problems in
Python
- When a string is stored in memory, its data type is
str
- When an integer is stored in memory, it has the data type
int
- When a decimal is stored, it has data type
float
- Float is short for
floating point
- Whenever you assign a value to a variable
- Python can detect what data type it should use
- You can see this using the Python function
type
>>> type("5")
<class 'str'>
>>> type(5)
<class 'int'>
>>> type(5.0)
<class 'float'>
- The
type
function also works on variables
>>> score = 85
>>> type(score)
<class 'int'>
>>> score = 85.0
>>> type(score)
<class 'float'>
>>> score = "85"
>>> type(score)
<class 'str'>
- Notice that Python thinks that these three values all have different data types
- Even though we would think of them as all the same value
Why You Need to Know About Data Types
- It might seem that data types are an unneeded complication
- After all, you can give the
print
function any kind of
value you want ...
- and it will print the correct output
>>> value = "5"
>>> type(value)
<type 'str'>
>>> print(value)
5
>>> value = 5
>>> type(value)
<type 'int'>
>>> print(value)
5
>>> value = 5.0
>>> type(value)
<type 'float'>
>>> print(value)
5.0
- But there are many situations where the data type is important
- The data type of a value determines what you can do with it
- You can divide an
int
or a float
with another int
or a float
>>> 30 / 5
6
>>> 30.0 / 5.0
6.0
- But you can't divide strings
>>> "30" / "5"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'str'
- Or divide a string by an integer
>>> "6" / 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'
- Or add an integer to a string
>>> 5 + "6"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
- Or subtrack them
>>> 5 - "6"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'int' and 'str'
Conversion Functions
- Python has functions that will convert from one data type to another
int()
will try to convert a value into an integer
>>> int("5")
5
int()
will also work with decimals
>>> int(5.1)
5
- But there is a limit to what it can do
>>> int("five")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'five')
- To convert integers or decimals into a string use the
str()
conversion function
>>> str(5)
'5'
>>> str(5.35)
'5.35'
- There are conversion functions for all major data types
- A function gets the values it needs to do its job from its arguments
- But how does a Python script get values from the user?
- One way is to read input from the keyboard
- This is done with the
input
function
input
takes one argument
- The text that will
prompt
the user for a value
input
is used in an
assignment statement like this
VARIABLE_NAME = input(PROMPT)
- When the Python interpreter comes upon a statement using
input
it
- Prints the prompt
- Waits for the user to type something and hit Enter
- Assigns the text entered by the user to the variable
- The prompt string should make it clear what type of value is wanted
- Here is an example
>>> team = input("Please enter a team name: ")
Please enter a team name: Red Sox
>>> print("Go", team)
Go Red Sox
- Notice that there is a space at the end of the prompt string
- There should be a gap between the prompt and the value entered by the user
- The
input
function gets input from the user
- And turns it into a value that a Python program can use
- The value produced by
input
function is always a string
>>> number = input("Please enter a number: ")
Please enter a number: 55
>>> type(number)
<class 'str'>
- Remember, every value has a data type
- If we want the value we get from
input
to be a different
data type ...
- we have to use a conversion function
- To convert the value in number to an integer use
int
>>> number = int(number)
>>> type(number)
<class 'int'>
- To convert it to a decimal, we can use
float
>>> number = float(number)
>>> type(number)
<class 'float'>
- If you run a conversion function on a value that it can't handle ...
- you will get an error
>>> number = input("Please enter a number: ")
Please enter a number: fifty-five
>>> number = int(number)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'fifty-five'
- In the code above we used two assignment statements
- One to get a value from the user using
input
...
- and another to convert the value into the right data type
- We can combine both operations into a single assignment statement
>>> number = int(input("Please enter an integer: "))
Please enter an integer: 67
>>> type(number)
<class 'int'>
- Why does this work?
- The call to
input
is an expression
- The
int
function takes one argument and that argument can be any
expression
- We can nest as many function calls as we like
- As long as each returns a value of the proper data type
Studying
Class Exercise
Class Quiz