IT 116: Introduction to Scripting
Class 4
Today's Topics
Tips and Examples
Review
New Material
Reading Assignment
You should read Chapter 2, Input, Processing and Output, from our
textbook, Starting Out with Python,before next weeks's class.
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.
If you miss the graded quiz on Tuesday you can take it on Thursday.
If you miss it on both Tuesday and Thursday you will get a 0 on the quiz.
Tips and Examples
Using the Unix mv
Command 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 the Unix
mv
command to fix it
mv
can do two things
- Move a file from one directory to another
- Change the name of a file
- Let's say you have a script in the wrong directory
$ ls
ex2 ex2.py ex3
- The script ex2.sh should be inside the ex2 directory
- To move it there, enter
mv ex2.py ex2
- Let's say you have a script with the wrong name
ex.sh
- To change the name, enter
mv ex.sh ex3.sh
Checking Class Exercises
- If the output looks like the output in the Class Exercise page, then your script is OK
- If you cannot finish the exercise in class you may do so at home
- If I have not checked your exercise in class I will do so later by running a script
- If you do not have a script file or there is a problem, you will also get an email
- If you receive no email, then your script is good
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 flashcards
- But it is better if you write your own cards
- The simple act of writing each card, helps you remember the material
Review
Basic Unix Commands
The nano
Text Editor
nano
is a simple text editor created as part of the GNU project
- In
nano
you run a command by holding down the Control key while pressing a letter key
- You will see things like like Control A
- This means hold down the Control key while pressing the A key
- Some of the basic
nano
commands appear at the bottom of the page
- The ^ in this list of commands stands for the Control key
- So ^O means Control O
- When you want to save a file you press Control O
- And the name of the file will appear at the bottom of the screen
- You need to hit Enter to accept that name and complete the save process
- Control X will quit
nano
- I have created a web page with instructions for using
nano
here
- There is a link to it on the class web page
The Hierarchical Filesystem
- Unix uses a hierarchical filesystem
- Which means that all files are kept in directories (folders)
- And directories live inside other directories
- There is one special directory at the top called
root
- But it is written as /
- You must be in the right directory when doing work for this course
- If you are unsure of where you are in the filesystem use
pwd
- Use the
cd
command with no argument to go back to your home directory
cd
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
- In Python, string literals must be enclosed in either single quotes, '
- Or double quotes, "
- 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 are written using 1s and 0s
- The binary number is translated into the characters using a table where each character has its own number
Unicode
- The table of numbers and characters that we use in Python is called Unicode
- Unicode represents all the characters in most world languages
- 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 with a name that stores a value
- In a many computer languages, such as Java, you have to specify what king 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"
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
Choosing Good Variable Names
- Just because a variable name is legal doesn't mean it's 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 which 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 numbers that represent the string "5" are different from the numbers that represent the integer 5
- And those 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, it's 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
but you don't need to remember that
- 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'
- The this applies to the other arithmetic operations like addition
>>> 5 + '6'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
- and subtraction
>>> 5 - '6'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'int' and 'str'
Conversion Functions
- To deal with situations like the one above 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')
>>> int(5.1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.1')
- 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
- How does a Python program get values from the user?
- One way is to read input from the keyboard
- This is done with the
input
function
input
has 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 gets to an assignment 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 to be some other 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'
- You will also get an error if you try to convert a string with a decimal point into an integer
>>> number = input("Please enter a number: ")
Please enter a number: 5.5
>>> number = int(number)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.5'
- In the code above we used two assignment statements
- One to get input 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
- That means it can be turned into a value
- 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
Attendance
Class Quiz