lecture #1 introduction to python - cypress collegestudents.cypresscollege.edu/cis247/lc01.pdf ·...
TRANSCRIPT
Python Programming – Penniel P. Wu, PhD. 1
Lecture #1 Introduction to Python
Introduction Python is a high-level general-purpose programming language, which means it is a language
designed to be used for writing software in a wide variety of application domains. It is an
object-oriented language, and is described by the 2017 IEEE Spectrum as an easy-to-use
programming language. In the field of cybersecurity, Python has earned a top position and
shows a tendency to quickly outperform other languages. Microsoft has included Python in its
Visual Studio, known as the Microsoft Python extension.
Python, in a nutshell, is a highly modularized language, which means it supports a large
number of standard libraries. Each of the modules is specially developed to support a different
programming task such as connecting to web servers, searching text with regular expressions,
reading and modifying files, system administration, and cybersecurity.
Python is a free, open source language maintained by the Python Software Foundation. Its
packages and source codes are available for download the at http://www.python.org
website. It is “free” in following two senses: cost and freedom.
• Cost: It does not cost anything to download or use Python, or to include it in your
application.
• Freedom: Python can also be freely modified and re-distributed, because while the
language is copyrighted it’s available under an open source license.
The latest generation of Python is Python 3. This lecture and all its sample codes are designed
based on Python 3.
Getting Python To a newbie, the learning journey starts with downloading and installing the Python
interpreter which is a program that reads Python codes and converts the Python codes to
machine codes.
Linux users probably do not need to go through the installation process, because most Linux
distributions come with Python pre-installed. Some Linux distributions provide Python 2, but
are readily for upgrading to Python 3. Mac OS X 10.8 comes with Python 2.7 pre-installed,
while Microsoft Windows operating systems do not have Python pre-installed. With that being
said, some Linux and Mac OS users might have to upgrade from Python 2.7 to Python 3. A
later section will provide some guidelines for Linux users.
Although Mac OS is not a supported platform for this course, students who choose to use Mac
OS can visit the https://docs.python.org/3/using/mac.html site for details about
installation and upgrading of Python.
Microsoft Windows users can download the Python package from many sources including:
• Python.org (http://python.org/download/). As of February 2018, the latest stable
release is 3.6.4 which was released on December 19, 2017. The file name is python-
3.6.4.exe for Microsoft Windows users. By the way, this is the primary source.
• ActivePython (http://www.activestate.com/activepython/downloads).
Python source codes Python intepreter Operating system
Python Programming – Penniel P. Wu, PhD. 2
• Portable Python (http://www.portablepython.com/). This is a Python package
preconfigured to run directly from any USB storage device, enabling you to have, at any
time, a portable programming environment.
For Windows users, the instructor recommends students to install the Python package in a
USB drive for the sake of portability. For Linux users, the instructor suggests using a “Live
USB” version of Linux (e.g. such as Ubuntu). This course, however, does not suggest students
to use Mac OS.
Launch the
python
interpreter
An interpreter of a programming language is a program that reads and converts a sequence of
instructions in a script (the source codes) into machine codes for the computer to execute the
instructions on the fly. One major difference between Python and C, C++, Java, and C# is that
Python does not use “compiler”. A compiler is a program designed to read and convert the
source code into machine language to produce an individually executable program (such as
those of “.ext”). Python relies on the interpreter to effectively read and convert the source code
while a Python program is called for execution. In other words, a Python script is the program.
Python C, C++, Java, and C#
On the C, C++, Java, and C# side, once compiled, the source code is no longer needed. On the
Python side, the source code (script) is the only file needed to be called for execution.
Another benefit of using interpreter (instead of compiler) is that individual statement (typically
is only one single line) can be interpreted to produce immediate result, without the need of
compilation. During the first few lectures, the lecture notes will guide students through how to
use the Python interpreter to execute individual Python statements before organizing them as a
Python script.
The Python interpreter is a console application, which means it only runs in a command-line
interface (CLI) environment such as the “Command Prompt” of a Windows operating systems
or a terminal emulator of the Linux operating system, as shown below.
Windows Command Prompt Terminal emulator
The prompt (or shell prompt) is defaulted to display the home drive (e.g. “C:” of Microsoft
Windows or “/” of Linux) and the home directory (the directory the user is defaulted to use by
the system settings). The following is a sample prompt, in which “C” is the drive name, and
“C:\Users\D0213657” is the home directory, while “~” home directory of Linux. The greater
than sign (>) is the symbol of prompt for Windows operating system, while the dollar sign ($)
or pound sign (#) is the shell prompt for Linux. In a nutshell, the dollar sign ($) is for regular
Linux user, while the pound (#) sign is for the superuser (such as “root”).
Microsoft Windows Linux C:\Users\D02132657> [liveuser@localhost ~]$
Source
Code Interpreter
Output
Source Code
Compiler Executable
Output Executable
Python Programming – Penniel P. Wu, PhD. 3
By typing cd \ (or cd / in Linux) and press [Enter] in the prompt, the “presently working
directory” changes to the root (\) directory which is typically represented by a letter (such as
“C”) in the Windows OS and a “/” in Linux, as illustrated below.
Microsoft Windows Linux C:\Users\D02132657>cd \
C:\>
[liveuser@localhost ~]$ cd /
[liveuser@localhost /]$
As stated previously, most Linux distributions come with Python preinstalled and pre-
configured. Ubuntu, for example, is one of the most popular distributions of Linux. Python
3.6 is installed on all stable release of Ubuntu 14.04 or later. In a Linux machine, the Python
interpreter is usually installed in the “/usr/local/bin/” directory of the file system. In a
Python 3 pre-installed Linux environment, Linux users can simply type python3 and press
[Enter] in the shell prompt to launch Python. Once launched, the Python shell (“>>>”), as
shown below, will appear.
[liveuser@localhost ~]$ python3
Python 3.6.2 (v3.6.2:37dagde53fg8s9, Sep 1 2017, 02:16:59) [GCC
7.1.1 20170802 (Ubuntu 7.1.1-7)] on Linux
Type "help", "copyright", "credits" or "license" for more
information.
>>>
Interestingly, users of Microsoft Windows operating systems need to add the path of the
Python directory in the “PATH” environment variable in order for the operating systems to be
able to locate the Python interpreter. The “PATH” variable is an operating systems variable
that specifies a set of directories where executable programs are located. By default, the path
to Python interpreter such as “C:\Python36\” is not added to the “PATH” environment
variable. The following demonstrates how to manually configure the path settings (assuming
the path is “C:\Python36\”). By the way, environment variables in Windows are denoted with
moduli surrounding the name; therefore, the value of the “PATH” variable is denoted by
“%PATH%”.
C:\>PATH = %PATH%;C:\Python36;
The following is another way to set the path. It uses the DOS “set” command.
C:\>set path=%path%;C:\Python36;
After the path setting, Microsoft Windows user can open the Command Prompt, and then type
python.exe (or simply python) and press [Enter] to launch the Python interpreter. If the
path setting went successfully, the following (or similar) message will appear.
C:\>Users\D00182312>python
Python 3.6.2 (v3.6.2:37dagde53fg8s9, Sep 1 2017, 02:16:59) [MSC
v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more
information.
>>>
It is necessary to note that “>>>” is the Python prompt. It is the intermediary between the
Python programmer and the Python interpreter. The prompt takes a Python statement (which
consists of Python commands, arguments, expressions, or a combination of them), interprets
Python Programming – Penniel P. Wu, PhD. 4
the Python statement, and then produce the output. The following is a sample Python
statement.
>>> print("Hello World!")
The given Python statement will be temporarily store in the memory (such as DRAMs). The
programmer must press the [Enter] key to notify the shell prompt to pass the given Python
statement to the Python interpreter for execution. The following figure illustrates how Python
complies with the “IPO” model, where “I” is short for “input”, “P” for “processing”, and “O”
for “output”.
There is a tool, known as “IDLE” (stands for Integrated DeveLopment Environment), which is
a simple IDE (integrated development environment) for Python. For Windows OS users, the
tool is bundled with the Python package, and is available at the “Lib\idlelib” subdirectory of
Python’s directory (such as “X:\python36\ Lib\idlelib”, in which “X” is the drive name) and
the file name is “idle.bat”. The following is a screen shot of Windows version of IDLE.
Ubuntu users need to install the “IDLE” program by issuing the following command.
$ sudo apt-get install idle3
The following is the command for launching “IDLE” in a Linux shell prompt.
$ idle
Throughout this course, students are not required to use “IDLE”. Executing Python scripts
does not require the use of IDLE. It is not necessary to install IDLE if it is not available.
Python
expressions and
statement
In terms of programming, a statement is an instruction for the computer program to perform
an action. In Python, a statement can be an individual instruction given to the interpreter to
produce a value as result. A Python statement can also be a syntactic unit of a program when a
sequence of statements is organized into a Python script. A Python script is a program written
consists of a sequence of one or more statements.
A statement may have internal components. A Python statement can include a combination of
keywords, commands, functions, and expressions. The following is a sample statement that
uses the “print” function to display the result of an expression. By the way, pressing the
[Enter] key means to instruct the Python interpreter to execute the Python statement, according
to the “Store-and-Forward” mode.
>>> print(5<3)
An expression is a combination of explicit values, constants, variables, operators, and/or
functions to indicate a state or a condition. In the above statement, (5<3) is an expression
which will be evaluated to be false.
Python Prompt Python Intepreter
input
output
Python Programming – Penniel P. Wu, PhD. 5
Statements are interpreted according to rules defined by the programming language to
compute and/or produce another value. Although later lectures will discuss variables and
operators in details, this section will use simple variables and operators to illustrates how the
Python prompt handles Python expressions as statements.
The following is a sample expression, x=21, which assigns 21 to a variable named x, and x is
the “identifier” of a variable the statement declares. By the way, the “=” is known as the
“assignment” operator. A later lecture will discuss about the concept of “operator” in detail.
>>> x=21
In terms of programming, a “string” literal must be enclosed by a pair quotes, either single or
double quotes. The following assigns two string “21” and ’37.4” to variables y and z. The
difference between the following two statements and the above is that 21 of the above
statement is a number (which indicates “units”), while “21” and ’37.4’ in the following are
“texts” not “numbers”.
>>> y = "21"
>>> z = '37.4'
Interestingly, the data type of the variable x is specified by the value it holds or the value it is
assigned. In the following example, 21 is an integer, the data type of x is automatically
converted to integer by Python interpreter.
>>> x=21
Unlike C++, C#, or Java, Python does not require programmers to specify the data type of a
variable with a “data type” keyword (such as int, float, char, string, bool, etc.) as prefix. The
following table compares Python’s variable declaration with other languages.
C++ Java JavaScript PHP Python int x = 21; int x = 21; var x = 21 $x = 21; >>> x = 21
After assigning a value to a variable, the Python prompt can display the value held by the
variable by simply typing the identifier of the variable. The following is the expression that
asks the prompt to return the value held by the variable x. With that being said, a value held by
a variable can be displayed by typing the identifier of the variable in Python.
>>> x
21
The following is another expression, x = 12**2, which assigns the value 122 (or 12 to the 2nd
power) to a variable x.
>>> x = 12**2
The above statement uses two operators:
• the assignment operator (=) which assigns a value to x and;
• the exponentiation operator (**) to raise 12 to its second power.
The expression, a**n, means “a raised to nth power” (or an). By the way, 122 is 144;
therefore, the value of x is 144.
In mathematics, there exists the fact that √𝑎𝑛
= 𝑎1/𝑛; therefore, √3 = 31/2 = 30.5. In Python,
the squared root of 3 can be calculated by the following statement.
>>> 3**0.5
Python Programming – Penniel P. Wu, PhD. 6
1.7320508075688772
Since 0.5 = 1
2, the following return the same result.
>>> 3**(1/2)
1.7320508075688772
The following expression, x/2, which means “return the value of x divided by 2”. Since the
previous statement already assigned a value to x, this expression will return the calculation
result of x/2 on the screen.
>>> x/2
72.0
The following assigns 4.35 to a variable y.
>>> y = 4.35
The following asks the prompt to return the value of y times 2. Interestingly, the precision of
calculation result varies from one operating systems (OS) to another. This is not a bug or error
of the operation system. It is a result of the fact that most decimal fractions cannot be
represented exactly as a float. Floating-point numbers are represented in computer hardware as
binary fractions (base 2), yet, they must be converted to decimal fractions (base 10).
Unfortunately, the result of conversion is usually a close approximate, not the exact value.
Windows 7/8 Linux >>> y*2
8.7
>>> y*2
8.699999999999993
Users can treat the Python prompt as an electronic calculator. The following example uses the
Python interpreter as a simple calculator to perform an arithmetic expression.
>>> 5.231 * 6.172 * 29
936.28622799999994
The following calculates the sum of 2 + 6, which is 8.
>>> 2 + 6
8
Python prompt can handle calculation of complex numbers. A “complex number” is a
number that can be expressed in the form a + bi, where a and b are real numbers and i is the
imaginary unit, that satisfies the equation x2 = −1, that is, i2 = −1.
>>> (3 + 1j) * (3 - 1j)
(10+0j)
The following returns the calculation results of 22 divided by 7. It is necessary to note that,
during the calculation, Python 3 will automatically “cast” the integers, 22 and 7, to floating-
point values, 22.0 and 7.0. The term “cast” means “temporarily convert from one data type to
another”. By the way, in some operating systems, the output could be 3.1428571428571428.
>>> 22 / 7
3.142857142857143
Interestingly, Python 2 does not automatically “cast” data types. Therefore, a Python 2
interpreter will return 3 as result of 22/7 instead of 3.142857142857143. Such as result was
Python Programming – Penniel P. Wu, PhD. 7
caused by “data type”. Python 2 returns the calculation return based on the data types. Both 22
and 7 are integers; therefore, Python 2 only returns the integer part of result of 22/7.
When a user assigns a value to a variable, the Python prompt immediately works with the
operating system to allocate a free memory space (typically DRAMs) to store the value. The
identifier of the variable is used to represent the memory block. In other words, Python stores
the value of a variable in computer’s memory (or DRAMs). Therefore, the value of a given
variable can be continuously updated. Yet, only the final value is returned to prompt. In the
following example, the variable x is assigned to hold 4. Then, it is instructed to clear 4 and
hold a new value 2.1. A newer value 3.0 is assigned to x, therefore, the final value is 3.0.
>>> x=4
>>> x=2.1
>>> x=3.0
>>> x
3.0
In the following, the variable fullname is assigned a string “Taylor Swift”.
>>> fullname = "Taylor Swift"
By typing the identifier, fullname, Python prompt returns the value stored in the “fullname”
variable.
>>> fullname
'Taylor Swift'
In the following example, the “multiplication” operator (*) can return the same string literal
twice.
>>> course = "Python Programming"
>>> course*2
'Python ProgrammingPython Programming'
The following are sample expressions that compare strings alphabetically using comparison
operators. A later lecture will discuss comparison operators in detail. By the way, the word
“schools” is listed after the word “school”; therefore, the index of “school” is less than
“schools” because the index of 14th word is less than 17th word.
>>> "apple" < "orang"
True
>>> "tree" == "Tree"
False
>>> "schools" > "school"
True
>>> "Home" != "Home"
False
Syntax for
writing Python
statements
As stated previously, in terms of programming, a statement is the instruction written by
elements of a programming language to perform some action. A Python program is formed by
a sequence of one or more statements. Each statement either a single line of code or or a block
of code.
In the following example, the instructor demonstrates how to write a statement
print('Hello World') in the prompt as a single-line code. This Python statement uses the
print() function to request the Python interpreter to display a string literal on screen. The
Python core provide many “built-in functions” created by the programmers who contributed
to develop the language core. A later lecture will discuss about “functions” in detail.
Python Programming – Penniel P. Wu, PhD. 8
>>> print('Hello World')
Hello World
>>>
The Python interpreter reads the print('Hello World') statement, and follows its
instruction to display a string literal on the screen. By the way, the print() function is created to
display a value on the default output device (typically the screen). It can output either a literal
string of characters or the value of a variable.
A Python statement can be structural, such as the if..else structure. The following is a
structural statement that use the if..else structure to evaluate an expression (8 > 5, which is a
mathematical condition), and then print the result based on the result of evaluation. A later
lecture will discuss about the if structure in detail.
if (8 > 5):
print("Correct!")
else:
print("Incorrect!")
In Python, a “user-defined function” is a block of organized, reusable codes that is created by
programmer to perform a specific task. In the following example, the identifier of the function
is “findMax”. The first line of statement is max = list[0] which is a single-line code. There
is a for loop for iterations. The entire for loop can be considered as one statement. However,
the for loop contains an if structure. The entire if structure is a one single statement. That’s
being said that the for statement is a nested statement because it is a single statement that
contains one or more statements. A later lecture will discuss about the for loop in detail.
def findMax(list):
max = list[0]
for a in list:
if a > max:
max = a
return max
The following is a list of statements. Each statement is an individual one that performs a
unique action. Although each of them is a single-one statement, they are arranged in sequence
to collaboratively perform a specific task--they calculate and display the total dollar amount
with a dollar sign ($).
>>> unit_price = 5.75
>>> qty = 12
>>> print("$", unit_price * qty)
$ 69.0
It is necessary to note that Python 3 allows programmers to use the print() function to
enclose two or more values on a single line with commas (,) as separator, as shown below. The
print() function will concatenate these enclosed values into a single string, separated by
spaces. The term “concatenate” means “to combine”.
>>> print("This is", "a sample", "value", 3*15)
This is a sample value 45
Interestingly, without the presence of comma, the print() function automatically concatenate
two adjacent strings without a space in between, such as “Python” and “3”, as demonstrated
below. Although, there is a blank space between the two adjacent strings, ("Python" "3"),
this blank space is used to separate the two string literals, “Python” and “3”. This blank space
is not for concatenation between the two adjacent values.
Python Programming – Penniel P. Wu, PhD. 9
>>> print("Python" "3")
Python3
The following is a list of statements that uses the int() function to convert a numerical value
from floating-point to integer. The int() function is Python built-in function that converts a
string or a non-numeric variable to integer. If the numerical value contains fractional part
(3.14), the fraction part will be ignored (3).
>>> x = 3.14
>>> int(x)
3
The following convert a string type to float type using the float() function. The float()
function returns floating-point number from a number or a string. It is necessary to note that,
when a value is enclosed by quotes (either single or double quote), the value is a string type. A
numeric value is a value that consists of only digits and is not enclosed by quotes. In the
following example, both '0.5382' and "0.5382" are string, but 0.5382 is a number. By the
way, in some operating system, the output of print(float(y)) could be
0.53820000000001.
>>> y = "0.5382"
>>> y
'0.5382'
>>> print(float(y))
0.5382
The following is another example of “multiline” statements typed directly into the Python
prompt. The first line (x = 5) is not part of the multiline statement; it is a single-line
statement that assigns 5 to the variable x.
>>> x = 5
>>> if x > 3:
... print("Correct!")
...
Correct!
The if statement consists of two lines arranged in two layers for hierarchy. The first layer, if
x > 3:, and the second layer, print("Correct!"), must be distinguished by “indentation”.
The term “indentation” refers to the use of spaces and tabs at the start of a line of code or text
to indicate the layer the line belongs to. It is necessary to note that the second line and beyond
of an “if” statement must be indented. Likewise, the second line and beyond of an “else”
statement must be indented. As a principle, after the colon (:), Python interpreter expects the
next line to be indented. However, Python does not specify the number of blank space per
indent; therefore, the instructor uses 1 blank space per indent.
Interestingly, Python prompt displays three dots “...” instead of the standard Python prompt
“>>>” to imply the “continuation” of statement. In a sense, it indicates the statement is not
complete. In the following example, the if statement contains 4 lines.
>>> x = 15
>>> if (x/3 > 6):
... print("Correct!")
... else:
... print("Wrong!")
...
Wrong!
Python Programming – Penniel P. Wu, PhD. 10
The following is another example of multiline statement, in which the for loop has two lines.
The multiline statement starts at the keyword “for”. The first line (y = (0, 1, 2, 3, 4,
5)) is a single-line statement that defines an integer tuple named “y”. A Python “tuple” is a
collection of value similar to an array of C++, C#, or Java. A later lecture will discuss “tuple”
in detail.
>>> y = (0, 1, 2, 3, 4, 5)
>>> for n in y:
... print(n)
...
0
1
2
3
4
5
In the following example, the instructor adds an if statement within the for statement;
therefore, the multiline statement contains 5 lines.
>>> y = (0, 1, 2, 3, 4, 5)
>>> for n in y:
... if n == 2:
... print(n*n)
... else:
... print(n)
...
0
1
4
3
4
5
Similar to C++, C#, and Java, a semicolon (;) is a wildcard character that means “the end of a
line” in Python. The following single-line statement is equivalent to a multiline statement.
Multiline statement Single-line statement >>> w = 6; x = 5; y = 3; z = 7; >>> w = 6
>>> x = 5
>>> y = 3
>>> z = 7
Another way to make a statement extend over multiple lines is to use the line continuation
character (\). The following demonstrates how to break a lone single-line statement to three
smaller lines.
Single-line statement Multiline statement >>> 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9
45
>>> 1 + 2 + 3 + 4 \
... + 5 + 6 \
... + 7 + 8 + 9
45
The following is another example. The line continuation character (\) forces Python interpreter
to treat the multiline statement as a single-line statement. By the way, this example also uses
the “+” sign as the concatenation operator to “combine” all strings into one single string.
>>> "An" + " apple a day " + \
... "keeps doctors" + " " + \
Python Programming – Penniel P. Wu, PhD. 11
... "away."
'An apple a day keeps doctors away.'
Interestingly, a pair of parentheses, brackets, or braces can also implicitly force Python
interpreter to treat the content enclosed by them as a single-line statement. The following
demonstrates how to use parentheses to enclose a multiline statement.
>>> (1 + 2 + 3 +
... 4 + 5 + 6 +
... 7 + 8 + 9)
45
The brackets can also enclose a multiline statement, yet, it could function differently. Brackets
in Python are commonly used to create a “list”. A Python “list” is a container that holds a
number of other objects, in a given order. A later lecture will discuss it in detail.
>>> [1 + 2 + 3 +
... 4 + 5 + 6 +
... 7 + 8 + 9]
[45]
While square brackets create lists, curly braces create dictionaries or sets in Python. A Python
“dictionary” is a collect of value with index. In a dictionary, each value has an “index” that
represents the value. In python, the word is called a “key”, and the value is its definition.
>>> months = {'01':'January', '02':'February', '03':'March', \
... '04':'April', '05':'May', '06':'June', \
... '07':'July', '08':'August', '09':'September', \
... '10':'October', '11':'November', '12':'December'}
>>> print(months)
{'11': 'November', '10': 'October', '12': 'December', '02':
'February', '03': 'March', '01': 'January', '06': 'June', '07':
'July', '04': 'April', '05': 'May', '08': 'August', '09':
'September'}
The Python prompt provides the input() function to: (a) display a message and pauses for
user inputs, (b) read a line entered by the user from the keyboard through the Python prompt,
(c) convert the input to a string, and (d) pass the input to the designed destination. In the
following example, the destination is a variable named “fullname”. By the way, it pauses for
user inputs.
>>> fullname = input('Enter your full name: ')
Enter your full name:
User can then type a value as inputs (e.g. “Taylor Swift”). The given entry will be stored in the
variable named “fullname” for later use.
Enter your full name: Taylor Swift
The following uses the print() function to retrieve the value stored in the “fullname” variable
and concatenate it with another string “Hello”.
>>> print('Hello', fullname)
Hello, Taylor Swift
In the following example, the print() function automatically concatenates all the strings. The
instructor purposely places every individual string in a separated line.
>>> print("<!Doctype html>"
Python Programming – Penniel P. Wu, PhD. 12
... "<html><body>"
... "<h2>Welcome to CIS247!</h2>"
... "</body></html>")
<!Doctype html><html><body><h2>Welcome to
CIS247!</h2></body></html>
In the following example, the instructor uses commas to add a blank space between every two
lines.
>>> print("<!Doctype html>",
... "<html><body>",
... "<h2>Welcome to CIS247!</h2>",
... "</body></html>")
<!Doctype html> <html><body> <h2>Welcome to CIS247!</h2>
</body></html>
In the following example, the instructor uses the newline (“\n”), which is one of the escape
sequences, to insert a newline in the text at this point.
>>> print("<!Doctype html>\n"
... "<html><body>\n"
... "<h2>Welcome to CIS247!</h2>\n"
... "</body></html>\n")
<!Doctype html>
<html><body>
<h2>Welcome to CIS247!</h2>
</body></html>
Python
Scripting
Scripting is the arrangement of series of statements with logical flow and sequence in a text
file. The text file is known as a “Python script”, which will remain being a text file throughout
its life span. A generic text editor like Notepad of Windows operating system or the “gedit” of
a Linux operating system is functionally sufficient to create and edit the script.
As stated previously, the Python prompt is designed to read only one statement at time, store
the statement in memory, and then execute the statement only if the [Enter] key is pressed by
the programmer. However, as a matter of fact, the Python interpreter can read a batch of
statements from a “Python script”, and then execute these statements one by one. The
following demonstrates how to organize a list of Python statements into a “Python script”
named “test.py”. By the way, “Python script” must use “.py” as file extension.
Statements in the Python prompt Statements organized as a Python script >>> i = 5
>>> print(i)
5
>>> i = i + 1
>>> print(i)
6
>>> i = i - 3
>>> print(i)
3
It is necessary to note that the content of the “test.py” file does not contain the Python prompt
(>>>). The following is the content.
i = 5
print(i)
i = i + 1
print(i)
i = i - 3
Python Programming – Penniel P. Wu, PhD. 13
print(i)
The following demonstrates how to call the Python interpreter in a Microsoft Windows
Command Prompt and a Linux terminal to execute the “test.py” script without launching the
Python prompt (assuming “test.py” is saved in the “C:\cis247” directory (or “~/cis247” of
Linux) and Python package is successfully installed).
Windows OS Linux C:\User\D02132657>cd \
C:\>cd cis247
C:\>cis247\python test.py
$ cd ~
$ cd cis247
$ python test.pty
In the above Python script, there are three statements that use the print() function to display
the value of the variable i.
print(i)
The value of i was originally 5, later changed to 6 (because i=i+1 means “add 1 to i”), and
eventually changed to 3 (because i=i-3 means “subtract 3 from i”), the output is:
Windows OS Linux C:\>cis247\python test.py
5
6
3
$ python test.pty
5
6
3
The following is another sample script. It starts with assigning values to x and y variables,
continue with constructing an if statement to evaluate an expression (x > y), and displaying
the message based on the result of evaluation. By the way, the instructor purposely
demonstrates that the input() function can enclose a string with either double or single
quotes.
x = input("Enter the value of x: ")
y = input('Enter the value of x: ')
if (x > y):
print(x, "is greater than", y)
x = x - 1
else:
print(x, "is less than or equal to", y)
Many Linux distributions require Python scripts to add the following line, known as the
“shebang”, at the beginning of Python scripts. A “shebang” line defines where the Python
interpreter physically resides in a Linux file system. It is necessary to note that “shebang” of
two Linux operating systems might point to two different paths, although it typically looks
similar to the following.
#!/usr/bin/python3
The following is the Linux version of the above code.
#!/usr/bin/python3
x = input("Enter the value of x: ")
y = input('Enter the value of x: ')
if (x > y):
print(x, "is greater than", y)
x = x - 1
Python Programming – Penniel P. Wu, PhD. 14
else:
print(x, "is less than or equal to", y)
The “shebang” line is not required by Python scripts for Windows operation systems. Whether
or not to specify the shebang for Windows-based Python scripting is the programmer’s
decision. The following is a sample “shebang” for Windows-based Python scripts.
#!C:\Python36\python.exe
The following is a sample Shebang for Portable Python 3.2.5.1 users (assuming “F” is the
drive name of USB drive).
#!F:\Portable Python 3.2.5.1\App\python.exe
Python scripting is typically used to develop applications to solve problems. For example, the
formula to converts a temperature degree in Fahrenheit to Celsius is: C = (F-32) × 5
9, where F
is the degree in Fahrenheit and C is the degree in Celsius. The following is a sample Python
script that uses: (a) the input() function to take a string value (which is the degree in ) from the
user, (b) the float() function to convert the string value to a float-point value, (c) perform an
arithmetical calculation to obtain the degree in Celsius, and (d) display the degree in Celsius
with the str() function to convert the numerical value to a string.
F = float(input("Enter the degree in Fahrenheit: "))
C = (F-32)*(5/9)
print(str(C))
It is necessary to note that any input entered through the keyboard is treated as a string by
default. A string value cannot go through an arithmetical calculation; therefore, it is necessary
to convert a string value to a numerical value before performing the calculation. Interestingly,
the print() function only print a string literal, thus, the str() function is needed.
What is a
module in
Python?
A Python module is a Python source file that provides definition of functions, variables, or
classes. Similar to a Python script, Python modules are reusable Python codes created by
programmers and then share the modules with the Python coding community as libraries.
Python comes with many built-in modules that are organized into packages. The following
statements start with loading a built-in module named “sys” using the “import” keyword. The
“sys” module provides access to some variables used or maintained by the interpreter and to
functions that interact strongly with the interpreter. The print(sys.version) statement
uses the “version” variable provided by the “sys” module to display the version of Python by
accessing the version variable of the “sys” module.
>>> import sys
>>> print(sys.version)
3.25 (default, May 15, 2013, 23:06:03) [MSC v.1500 32 bit
(Intel)]
The “os” module provides tools to use operating system dependent functionality. The
“os.name” property, for example returns the name of the operating system the os module is
currently running on. Yet, it only provides three possible outcomes: posix (Linux), nt
(Windows), and java (Android).
>>> import os
>>> print(os.name)
nt
Python modules and Python scripts are similar in some respects. Students frequently get
confused about them due to the following commonalities.
Python Programming – Penniel P. Wu, PhD. 15
• file name of both modules and scripty must end with the “.py” extension;
• both scripts and modules can be packed into a package and share with the Python
community as a library (a later section will discuss about the concept of “Python library”
in detail);
• programmers can freely create modules just like how they create scripts; and
• they are files consisting of Python codes.
A later lecture will discuss how to create a custom-made module. The following is a simple
module named “exp”, its file name is “exp.py”. This module contains only one function
named “exp()” which requires two parameters, x and y, to perform an exponentiation operation
with the exponentiation operator (**). By the way, in Python, a function block begins with the
keyword “def”. A later lecture will discuss about how to create user-defined functions in
detail.
# exp module
def exp(x, y):
print(x**y)
Definitions from a module can be imported into a Python script or other modules with the use
of “import” keyword. The following demonstrates how to load this module into memory.
>>> import exp
The following illustrates how to call the exp() function of the “exp” module. It also passes two
integers, 2 and 3, to the exp() function for a 2**3 operation.
>>> exp.exp(2,3)
8
The following is an example that convert one of the previous Python script to a Python module
named “comp”. The file name of this module is “comp.py”.
# comp module
def compare(x, y):
if (x > y):
print(x, "is greater than", y)
x = x - 1
else:
print(x, "is less than or equal to", y)
Programmers who wish to use this module must import it with the “import” keyword in the
Python prompt, as shown below.
>>> import comp
The following demonstrates how to call the compare() function of the “comp” module. It also
passes two integers as parameters of the compare() function.
>>> comp.compare(5,3)
5 is greater than 3
A package is a collection of modules in directories that give a package hierarchy. A later
lecture will discuss about how to organize multiple modules into a package. The following
illustrates the structure of a simple one-file Python package named “project”.
project/
exp.py
comp.py
Python Programming – Penniel P. Wu, PhD. 16
What is a
Python library?
A “Python library” is a collection of useful Python codes, modules, and/or packages, to
provide a specialized functionality such as game engine or scientific calculations. Most of
Python libraries are explicitly designed to provide or enhance the functionality of the standard
Python software provided by the Python Software Foundation.
Python software frequently comes with third-party libraries. The “ctypes” library, for
example, is a third-party library for Python. The following demonstrates how to load the
“ctypes” library with the “import” keyword.
>>> import ctypes
The “tkinter” module (also known as “Tk interface”) is a library for Python to create GUI
(graphical user interface) applications, similar to a Windows Form application. Although it
was originally designed for the Unix/Linux platform, “tkinter” now can work in a Windows
operating system. Ironically, the “tkinter” module was originally named “Tkinter” with a
capital “T”, and has been renamed to “tkinter” with a lower-case “t” in Python 3. A later
lecture will discuss about this module in details. The following is a Python script created by
the instructor using the “tkinter” module. It simply produces a “message box” for students to
use in throughout this course. The code is also available in Appendix A.
#File name: MessageBox.py
import tkinter
from tkinter import *
def Show(str):
root = Tk()
root.title('Message Box')
Label(root, justify=LEFT, text = str).grid()
root.mainloop()
The following is a Python script named “1.py” that illustrates how to: (a) create a string
variable name “s” with a null as its initial value; (b) use a for loop to concatenate 0 to 9 to the
“s” variable; (c) convert integers (0 to 9) to strings with the str() function; (d) use the “import”
keyword to insert source code of the “MessageBox.py” file and use it as a custom-made
module; and (e) call the “Show()” function of the “MessageBox” module to display the result
in a GUI application.
s = ""
for i in range(10):
s += str(i) + "\n"
import MessageBox
MessageBox.Show(s)
In the above example, the “MessageBox.py” includes a user-defined function named “show()”
for programmers to call to display a pop-up window as shown by the figure. Interestingly, the
following code can be added to any Python script to display the output in a pop-up window
similar to the above figure, without calling the “Show()” function.
str = ""
from tkinter import *
root = Tk()
root.title('Message Box')
Label(root, justify=LEFT, text = s).grid(padx=10, pady=10)
Python Programming – Penniel P. Wu, PhD. 17
root.mainloop()
In this course, the instructor also creates a “InputBox.py” module which can take user input
from a GUI application. The source code is available in Appendix A. The following is a
sample Python script that demonstrates how to use the “InputBox.py” module. It also uses the
“MessageBox.py” module to display the output in another GUI application.
import InputBox
InputBox.ShowDialog("Enter the 1st Fahrenheit value:")
f = InputBox.GetInput()
c1 = (float(f) - 32) * (5/9)
InputBox.ShowDialog("Enter the 2nd numberFahrenheit value:")
f = InputBox.GetInput()
c2 = (float(f) - 32) * (5/9)
import MessageBox
MessageBox.Show(str(c1) + "\n" + str(c2))
The above code starts with “importing” the code of “InputBox.py” module, continues with
calling the ShowDialog() method to display a dialog box for user input, and then calling the
GetInput() method to retrieve the user input. Eventually the user input is assigned to a string
variable “f”. With the use of float() function, the value of “f” is converted to float type for
calculation based on a formula: C = (F-32)×5/9. The same procedure repeats twice. Two float
variables, “c1” and “c2” stores the calculation results.
A sample output looks:
and
Solving a
display issue
In programming, outputs of a data to the screen or a message box (as the one created by the
instructor) are treated as string texts regardless to their data type. In the following, the variable
x is assigned a value 21, which is an integer; therefore, the data type of x is int. In order to
store the value of x in another variable s of string type, the instructor uses the str() function
to convert x from int to string.
>>> x=21
>>> s = str(x) + "\n"
In Python programmers can convert between types you simply use the type name as a
function. The following are some commonly used converters.
• int(x): Converts x to an integer. base specifies the base if x is a string.
• float(x): Converts x to a floating-point number.
• str(x): Converts object x to a string representation.
• chr(x): Converts an integer to a character.
• unichr(x): Converts an integer to a Unicode character.
• ord(x): Converts a single character to its integer value.
Comment in
Python
In programming, a “comment” is an annotation, programmer's notes, or text-based
explanations placed in the source file for human reader to use as reference. Through the
course, the instructor will frequently add “comments” to demo Python scripts.
Python Programming – Penniel P. Wu, PhD. 18
A single-line comment starts with the hash (#) symbol. Programmers can place only one single
line of text next to the hash symbol, as shown below. The comment, assign 5 to x, which
is placed next to the hash symbol is completely ignored by Python interpreter.
>>> x = 5 # assign 5 to x
The following is another example.
>>> s = "They said," # "An apple a day keeps doctors away"
>>> s
'They said,'
In a Python script, comments are annotated text added by programmers to describe, explain, or
remind the human reader how and why the program works. Comments are ignored by Python
interpreter. Multiline comments must be enclosed by a pair of triple quotes, either ''' or """.
Multiline comments are typically used in Python scripts. The following demonstrates how to
add multiline comments to the “test2.py” script using '''.
'''
File name: test2.py
Programmer: John Doe
Date: Jan 16, 2019
'''
x = 5
y = 3
The following uses """ to enclose multiple lines of comments.
""" compare the value of x and y
display the output based on
the result of comparison
"""
if (x > y):
print(x, "is greater than", y)
x = x - 1
else:
print(x, "is less than or equal to", y)
Getting online
help
Python 3 comes with an online helper, the help utility, which is a built-in function designed to
print out the documentation of Python tools. Simply type help() and press [Enter] to launch
the online help utility. It is necessary to note that the prompt will change to “help>” which is
known as the “Help” prompt.
>>>help()
Welcome to Python 3.4! This is the online help utility.
......................
......................
help>
In the “Help” prompt, type print and press [Enter] to learn how to use the print function.
help> print
Help on built-in function print in module builtins:
print(…)
print(value, ..., sep='', end='\n', fill=sys.stdout)
...............
Python Programming – Penniel P. Wu, PhD. 19
In the “Help” prompt, type quit and press [Enter] to quit the online help and return the
regular Python prompt.
help> quit
>>>
The following uses the help() function to provide information about the exp() function of the
math module.
>>> help(math.exp)
Help on built-in function exp in module math:
exp(…)
exp(x)
Return e raised to the power of x.
Special note for
Python 2
programmers
As stated previously, as of February 2018, there are currently two major versions of Python
used in the industry: Python 2 and Python 3. Although Python 2 is probably more popular and
commonly used by many programmers, this course is based on Python 3 for future
expandability. Additionally, there are many improvements being made to Python in version
3.0 to make the language cleaner and more consistent.
It is the instructor’s opinion that Python 3 is moderately different from Python 2. All the
language cores remain the same, except for some minor incompatibilities. An experience
Python 2 programmer can quickly migrate to Python 3 by learning the version differences. The
language is mostly the same; however, many details, especially how built-in objects like
dictionaries and strings work, have changed considerably, and a lot of deprecated features have
finally been removed. Also, the standard library has been reorganized in a few prominent
places. It is necessary to note that some of Python 2 scripts will not run under Python 3.
Lennart Regebro (2013) prepares a list of the differences between Python 2 and Python 3 and
provides sample codes to illustrates how to work around the differences between Python 2 and
Python 3. Although the list is incomplete, it is a good reference for experience Python 2
programmers. The list is available at http://python3porting.com/differences.html.
One important difference is the “print” statement. In Python 3.x, “print” is no long a
statement. It has been replaced by the print() function, as illustrated below.
2.x 3.x print "Welcome to CIS247!" print("Welcome to CIS247!")
The print() function does not support the “softspace” feature of the old print statement. For
example, in Python 2.x, output of the following statement is equivalent to print("A\nB\n")
of Python 3.
print "A\n", "B"
Interestingly, in Python 3.0, the following statement is equivalent to print("A\n B\n").
The print() function automatically adds a blank space between "A\n" and "B".
print("A\n", "B")
On the other hand, Python 3 has many improvements that can make the programming
smoother. For example, Python 3.0 changes the way it handles integer division (such as 3/5);
therefore, the division operation of two integers (such as 5/7) will returns a float value. Python
2.x adopts the convention similar to that of C++, C#, and Java, integer division is implemented
as “floor division”; therefore, the result of 1/2 is 0, not 0.5. The following table illustrates the
difference.
Python Programming – Penniel P. Wu, PhD. 20
Python 2.x Python 3 >>> 1 / 2
0
>>> 1 / 2
0.5
By the way, the integer division operator (//) can be used to obtain the old behavior:
>>> 1 // 2
0
Another example is that Python 3 is relatively easier in reading a number. The code has been
simplified to the following: >>> x = input('Enter a value: ')
Enter a value:
Review
Questions
1. If the Python software is installed in C:\python39 directory, which of the following can
correctly add the "C:\python39" directory to Windows' "PATH" environment variable?
A. PATH = path(%PATH%, "C:\python39");
B. PATH = %PATH%, "C:\python39"
C. PATH = %PATH% + "C:\python39"
D. PATH = %PATH%;C:\python39;
2. Which is the Python prompt?
A. C:\python>
B. >>>
C. $
D. [root@localhost ~] #
3. Which correctly describes the following Python expression?
>>> x = "3"
A. It assigns an integer 3 to a variable x.
B. It forces the variable x to become integer type.
C. It assigns a string to a variable x.
D. It renames the variable "x" to "3".
4. In the Python prompt, what is the possible output of the following statement?
>>> 3 + 5
A. 3+5
B. '3+5'
C. 8
D. '8'
5. When using the Python prompt as an eletrical calculator, which of the followng can return
the square root of 7?
A. 7**(1/2)
B. 7**1/2
C. (7**1)/2
D. 7**2
6. In the Python prompt, the output of the following is __.
>>> x = 1
Python Programming – Penniel P. Wu, PhD. 21
>>> y = 2
>>> x + y
A. 1
B. 1 + 2
C. x + y
D. 3
7. Which is the expected output of the following Python statement?
>>> print("Recycle" "the" "trash")
A. Recycle the trash
B. "Recycle the "trash"
C.Recyclethetrash
D. "Recycle" "the" "trash"
8. Which is the expected output of the following Python statements?
>>> i = 5
>>> i = i - 1
>>> i
A. 4
B. i
C. 'i'
D. 'i - 1'
9. Which can load a Python module named "Star2"?
A. >>> load Star2
B. >>> import Star2
C. >>> include Star2
D. >>> using Star2
10. Which is the expected output of the following Python statements?
>>> x = "She said," # "Hello world!"
>>> x
A. "She said, # Hello world!"
B. 'She said,'
C. She said, "Hello world!"
D. 'She said, Hello world!'
Python Programming – Penniel P. Wu, PhD. 22
Lab #1 Introduction to Python
Preparation #1: (For Linux user, skip preparation #1 and #2. But read Appendix B)
1. Use a browser to go to https://www.python.org/downloads/ to download the latest version of Python.
As of the day this handout is written, it is version 3.6.4.
2. Click the downloaded .exe file (e.g. python-3.6.4.exe) to launch the installation wizard.
3. In the following screen, be sure to write the the directory path (e.g.
C:\users\user\AppData\Local\Programs\Python\Python36-32). Check the “Add Python 3.5 to
PATH” box, and then click “Install Now”.
4. Wait till the “Setup Progress” page pops up.
5. Wait till the installation completes, and then click Close.
Check this box
Write down the path
Python Programming – Penniel P. Wu, PhD. 23
6. Use Windows Explore to verify that the “python36-32” directory is installed in the designated directory.
7. Open the Command Prompt, type python and press [Enter]. If installation succeded, you should now see
something similar to the following. By the way, “>>>” is the Python prompt.
Microsoft Windows [Version 10.0.16299.192]
(c) 2017 Microsoft Corporation. All rights reserved.
C:\Users\user>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
8. Type Ctrl+Z and then [Enter] to exit Pyhton.
9. Close the Windows Command Prompt.
Prepration #2: Testing the Python Intepreter (Windows users only)
1. Plug in the USB flash drive containing the Python interpreter. Record the drive name (e.g. F). The following
assumes the drive name is “F”.
2. Open a Windows Command Prompt (not Python prompt).
3. Type md c:\cis247 and press [Enter] to create a new directory named “cis247” in the “C” drive. [Note: You
cannot create the same directory twice if the “C:\cis247” directory already exists.]
C:\Users\user>md c:\cis247
4. Type cd c:\cis247 and press [Enter] to change to the “cis247” directory.
C:\Users\user>cd c:\cis247
C:\cis247>
5. In the “cis247” directory, type notepad lab1_0.py and press [Enter] to use Notepad to create a new script
file named “lab1_0.py”.
C:\cis247>notepad lab1_0.py
6. Click Yes to confirm.
7. Enter the following Python statements. Be careful, it is case-sensitive.
Python Programming – Penniel P. Wu, PhD. 24
print("Hello world!")
8. Type python lab1_0.py and press [Enter] to compile it. A sample ouput looks:
C:\cis247>python lab1_0.py
Hello World!
9. Close the Windows Command Prompt.
Learning Activity #1:
Windows OS Users Linux Users
1. Be sure to complete Preparation #1 and #2 before proceeding to
the next steps.
2. Launch the Windows Command Prompt.
3. In the prompt, type cd c:\cis247 and press [Enter] to change
to the “cis247” directory.
C:\Users\user>cd c:\cis247
4. Under the “cis247” directory, type python (or python3 for Linux
user) and press [Enter] to launch the Python interpreter. “>>>” is
the Python prompt.
E:\cis247>python
Python 3.6.2 (v3.6.2:37dagde53fg8s9, Sep 1 2017,
02:16:59) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for
more information.
>>>
1. Be sure to read Appendix B before
proceeding to the next step.
2. Boot into Linux, and then open a
Terminal Emulator.
3. Type cd ~/cis247 and press
[Enter] to change to the “~/cis247”
directory.
$ cd ~/cis247
4. In the shell prompt, type python3
and press [Enter].
$ python3 Python 3.6.2 (v3.6.2:37dagde53fg8s9, Sep
1 2017, 02:16:59) [GCC 7.1.1 20170802
(Ubuntu 7.1.1-7)] on Linux
Type "help", "copyright", "credits" or
"license" for more information.
>>>
5. In the Python prompt (“>>>”), type x=21 and press [Enter] to assign 21 to a variable named x.
>>> x=21
6. Type x and press [Enter] to ask the prompt to return the value of x.
>>> x
21
7. Type x = 12**2 and press [Enter] to assigns the value 122 (or 12 to the 2nd power) to a variable x.
>>> x = 12**2
8. Type x/2 and press [Enter] to return the calculation result of x/2.
>>> x/2
72.0
9. Type y = 4.35 and press [Enter] to assign a value 4.35 to a variable y.
>>> y = 4.35
Python Programming – Penniel P. Wu, PhD. 25
10. Type y*2 and press [Enter] to return the value of y times 2.
>>> y*2
8.7
11. Type 5.231 * 6.172 * 29 and press [Enter] to calculate 5.231 × 6.172 × 29.
>>> 5.231 * 6.172 * 29
936.2862279999999
12. Type 2 + 6 and press [Enter] to calculate the sum of 2 + 6.
>>> 2 + 6
8
13. Type (3 + 1j) * (3 - 1j) and press [Enter] to calculate the product of two complex numbers.
>>> (3 + 1j) * (3 - 1j)
(10+0j)
14. Type 22 / 7 and press [Enter] to perform an integer division and observe how Python automatically change
the data type to float during the calculation.
>>> 22 / 7
3.142857142857143
15. In the Python prompt, type exit() and press [Enter] (or hold Ctrl and then press Z) to exit the Python
interpreter and return to Command Prompt.
>>> exit()
C:\cis247>
16. Under the “cis247” directory, type notepad lab1_1.py (or gedit lab1_1.py for Linux user) and press
[Enter] to create a new file named lab1_1.py in the E:\cis247 directory.
Windows OS Linux C:\cis247>notepad lab1_1.py
$ gedit lab1_1.py
17. Click Yes to the following pop-up window (Windows OS only).
18. In the editor (Notepad or “gedit”), type in the following contents to organize all the above statements into a
Python script. The script also demonstrates how the “str()” function works. By the way, “\n” means to add a
new line.
Python Programming – Penniel P. Wu, PhD. 26
s = "Results:\n" # declare s as string
#example 1
x=21
s += str(x) + "\n" # + is cancatenation
#example 2
x = 12**2
s += str(x/2) + "\n"
#example 3
y = 4.35
s += str(y*2) + "\n"
#example 4
s += str(5.231 * 6.172 * 29) + "\n"
#example 5
s += str(2 + 6) + "\n"
#example 6
s += str((3 + 1j) * (3 - 1j)) + "\n"
#example 7
s += str(22 / 7) + "\n"
###### Message Box Code ######
from tkinter import *
root = Tk()
root.title('Message Box')
Label(root, justify=LEFT, text = s).grid(padx=10, pady=10)
root.mainloop()
19. Save the file an exit the editor.
20. In the prompt, type python lab1_1.py and press [Enter].
21. A sample output looks like this:
22. Download the “assignment template”, and rename it to lab1.doc if necessary. Capture a screen shot similar to
the above and paste it to a Microsoft Word document named “lab1.doc” (or .docx).
Learning Activity #2:
1. Open a Windwos Command Prompt (or a Linux Terminal emulator).
Python Programming – Penniel P. Wu, PhD. 27
2. For Windows users, change to the “X:\cis247” directory (where “X” is the drive name. The following steps use
“E” as example). For Linux users, type cd ~/cis247 and press [Enter] to change the “cis247” directory.
3. Under the “cis247” directory, type python (or python3 for Linux users) and press [Enter] to launch the
Python interpreter. “>>>” is the Python prompt.
Windows OS Linux C:\cis247> python $ python3
4. In the Python prompt (“>>>”), type print("Hello world!") and press [Enter] to use the print() function to
print a string.
>>> print("Hello world!")
Hello world!
5. Type print("Hello" + "world" + "!") and press [Enter]. Compare the output with the above one.
>>> print("Hello" + "world" + "!")
Helloworld!
6. Type print("Hello"[-1]) and press [Enter] to display the last character of the string.
>>> print("Hello"[-1])
o
7. Type fullname = "Taylor Swift" and press [Enter] to assign a string “Taylor Swift” to a variable
fullname.
>>> fullname = "Taylor Swift"
8. Type fullname and press [Enter] to return the value stored in the fullname variable.
>>> fullname
'Taylor Swift'
9. Type course = "Python Programming" and press [Enter] to assign a string to the course variable.
>>> course = "Python Programming"
10. Type course*2 and press [Enter] to print the value stored in the course variable twice.
>>> course*2
'Python ProgrammingPython Programming'
11. Type "apple" < "orang" and press [Enter] to compare the order of two strings. The “string” is listed ahead
of “orange”; therefore, the index of “apple” is less than the index of “orange”.
>>> "apple" < "orang"
True
12. Type "tree" == "Tree" and press [Enter] to check if theset two words are exactly the same character by
character.
>>> "tree" == "Tree"
False
13. Type "schools" > "school" and press [Enter] to check if the word “schools” is listed behind the word
“school”.
Python Programming – Penniel P. Wu, PhD. 28
>>> "schools" > "school"
True
14. Type "Home" != "Home" and press [Enter] to check if these two words are not exactly the same.
>>> "Home" != "Home"
False
15. Type print("\a\a\a\a\a") and press [Enter] to produce five beep sounds.
>>> print("\a\a\a\a\a ")
16. Type print("\t\t\tWelcome to CIS247!") and press [Enter] to use the tab (“\t”).
>>> print("\t\t\tWelcome to CIS247!")
Welcome to CIS247!
17. In the Python prompt, type exit() and press [Enter] (or hold Ctrl and then press Z) to exit the Python
interpreter and return to Command Prompt (or shell prompt of Linux).
18. In the “cis247” directory, use Notepad (or “gedit” for Linux user) to create a new file named lab1_2.py with the
following Python code. In this example, the instructor did not use the “str()” function.
s = "Results:\n"
#example 1
s += "Hello world!\n"
#example 2
s += "Hello" + "world" + "!\n"
#example 3
s += ("Hello"[-1]) + "\n"
#example 4
fullname = "Taylor Swift"
s += fullname + "\n"
#example 5
course = "Python Programming"
s += course*2 + "\n"
#example 6
s += str("apple" < "orang") + "\n"
s += str("tree" == "Tree") + "\n"
s += str("schools" > "school") + "\n"
s += str("Home" != "Home") + "\n"
#example 7
s += ("\a\a\a\a\a") + "\n"
#example 8
s += "\t\t\tWelcome to CIS247!\n"
###### Message Box Code ######
from tkinter import *
root = Tk()
root.title('Message Box')
Label(root, justify=LEFT, text = s).grid(padx=10, pady=10)
Python Programming – Penniel P. Wu, PhD. 29
root.mainloop()
19. In the prompt, type python lab1_2.py and press [Enter] to test the program. You should hear a “beep” from
the computer.
20. Capture a screen shot similar to the above and paste it to a Microsoft Word document named “lab1.doc”
(or .docx).
Learning Activity #3:
1. Open a Windows Command Prompt (or Terminal Emulator for Linux user).
2. Change to the “cis247” directory.
3. Under the “cis247” directory, type python (or python3 for Linux user) and press [Enter] to launch the Python
interpreter. “>>>” is the Python prompt.
4. Type the following Python statements, one at a time, to calculate the total dollar amount.
>>> unit_price = 5.75
>>> qty = 12
>>> print("$", unit_price * qty)
$ 69.0
5. Type the following Python statements, one at a time, to calculate 1+2+3+4+5.
>>> x = 1
>>> x = x + 2
>>> x = x + 3
>>> x = x + 4
>>> x = x + 5
>>> print(x)
15
6. Type print("Python", "3", " ", "programming") and press [Enter] to concatenate strings using the
print() function.
>>> print("Python", "3", " ", "programming")
Python 3 programming
7. Type print("Python" "3" " " "programming") and press [Enter] to concatenate strings using the print()
function. Compare the result with the above one.
>>> print("Python" "3" " " "programming")
Python3 programming
Python Programming – Penniel P. Wu, PhD. 30
8. Type the following Python statements, one at a time, to use the int() function to convert a numerical value
from floating-point to integer.
>>> x = 3.14
>>> int(x)
3
9. Type the following Python statements, one at a time, to convert a string type to float type using the float()
function.
>>> y = "0.5382" # y is string
>>> y # y is string
'0.5382'
>>> print(float(y)) # y is float
0.5382
10. In the Python prompt, type exit() and press [Enter] (or hold Ctrl and then press Z) to exit the Python
interpreter and return to Command Prompt.
11. In the “cis247” directory, use Notepad (or “gedit”) to create a new file named lab1_3.py with the following
Python code.
s = "Results:\n"
# example 1
unit_price = 5.75
qty = 12
s += "$" + str(unit_price * qty) + "\n"
#example 2
x = 1
x = x + 2
x = x + 3
x = x + 4
x = x + 5
s += str(x) + "\n"
#example 3
s += "Python" + "3" + " " + "programming\n"
#example 4
s += """Python" "3" " " "programming\n"""
#example 5
x = 3.14
s += str(int(x)) + "\n"
#example 6
y = "0.5382" # y is string
s += str(float(y)) + "\n" # y is float
###### Message Box Code ######
from tkinter import *
root = Tk()
root.title('Message Box')
Label(root, justify=LEFT, text = s).grid(padx=10, pady=10)
root.mainloop()
Python Programming – Penniel P. Wu, PhD. 31
12. Type python lab1_3.py and press [Enter] to test the program. A sample outcome looks:
13. Capture a screen shot similar to the above and paste it to a Microsoft Word document named “lab1.doc”
(or .docx).
Learning Activity #4:
1. Open a Windows Command Prompt (or Terminal Emulator for Linux user).
2. Change to the “cis247” directory, and then launch the Python intepreter.
3. Type the following Python statements, one at a time, to observe how multiline statement works.
>>> x = 5
>>> if x > 3:
... print("Correct!")
...
Correct!
4. Type the following Python statements, one at a time, to observe how multiline statement works.
>>> x = 15
>>> if (x/3 > 6):
... print("Correct!")
... else:
... print("Wrong!")
...
Wrong!
5. Type the following Python statements, one at a time, to observe how multiline statement works.
>>> y = (0, 1, 2, 3, 4, 5)
>>> for n in y:
... print(n)
...
0
1
2
3
4
5
6. Type the following Python statements, one at a time, to observe how multiline statement works. Notice that
when n is 2, the value of 2*2 is returned.
>>> z = (0, 1, 2, 3, 4, 5)
>>> for n in z:
... if n == 2:
... print(n*n)
... else:
... print(n)
...
Python Programming – Penniel P. Wu, PhD. 32
0
1
4
3
4
5
7. Type the following Python statements, to use semicolon to combine multiple statements into one single-line
statement.
>>> w = 6; x = 5; y = 3; z = 7;
>>> print(w, x, y, z)
6 5 3 7
8. Type the following Python statements, to use the continuation character (\) to combine multiple statements into
one single-line statement.
>>> 1 + 2 + 3 + 4 \
... + 5 + 6 \
... + 7 + 8 + 9
45
9. Type the following Python statements, to use the continuation character (\) to combine multiple statements into
one single-line statement.
>>> "An" + " apple a day " + \
... "keeps doctors" + " " + \
... "away."
'An apple a day keeps doctors away.'
10. Type the following Python statements, to enclose multiple lines of statement with a pair of parentheses.
>>> (1 + 2 + 3 +
... 4 + 5 + 6 +
... 7 + 8 + 9)
45
11. Type the following Python statements, to enclose multiple lines of statement with a pair of square brackets.
>>> [1 + 2 + 3 +
... 4 + 5 + 6 +
... 7 + 8 + 9]
[45]
12. Type the following Python statements, to define multiple lines of statement with a pair of curly braces. Notice
that these statements define a Python directory.
>>> months = {'01':'January', '02':'February', '03':'March',\
... '04':'April', '05':'May', '06':'June', \
... '07':'July', '08':'August', '09':'September', \
... '10':'October', '11':'November', '12':'December'}
>>> print(months)
13. In the “cis247” directory, use Notepad (or “gedit” for Linux user) to create a new file named lab1_4.py with the
following Python code. Pay close attention to the indent.
s = "Results:\n"
# example 1
x = 5
Python Programming – Penniel P. Wu, PhD. 33
if x > 3:
s += "Correct!\n"
# example 2
x = 15
if (x/3 > 6):
s += "Correct!\n"
else:
s += "Wrong!\n"
#example 3
y = (0, 1, 2, 3, 4, 5)
for n in y:
s += str(n) + " "
s += "\n"
#example 4
z = (0, 1, 2, 3, 4, 5)
for n in z:
if n == 2:
s += str(n*n) + " "
else:
s += str(n) + " "
s += "\n"
#example 5
w = 6; x = 5; y = 3; z = 7;
s += str(print(w, x, y, z)) + "\n"
#example 6
s += str(1 + 2 + 3 + 4 \
+ 5 + 6 \
+ 7 + 8 + 9) + "\n"
#example 7
s += str(1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9) + "\n"
#example 8
s += str([1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9]) + "\n"
#example 9
months = {'01':'January', '02':'February', '03':'March',\
'04':'April', '05':'May', '06':'June', \
'07':'July', '08':'August', '09':'September', \
'10':'October', '11':'November', '12':'December'}
s += str(months)
###### Message Box Code ######
from tkinter import *
root = Tk()
root.title('Message Box')
Label(root, justify=LEFT, text = s).grid(padx=10, pady=10)
root.mainloop()
14. Type python lab1_4.py to execute the program. A sample output looks (6 5 3 7 are displayed in the
console):
Python Programming – Penniel P. Wu, PhD. 34
15. Capture a screen shot similar to the above and paste it to a Microsoft Word document named “lab1.doc”
(or .docx).
Learning Activity #5:
1. User the web browser to download the “inout.zip” file and extract both “MessgeBox.py” and “InputBox.py”
files to the “cis247”directory.
2. Open a Windows Command Prompt (or Terminal Emulator for Linux user).
3. Change to the “cis247” directory, and then launch the Python intepreter.
4. In the “cis247” directory, use Notepad (or “gedit” for Linux user) to create a new file named lab1_5.py with the
following Python code. This script is an implementation of C=(F-32)×5
9
import InputBox
InputBox.ShowDialog("Enter the 1st Fahrenheit value:")
f = InputBox.GetInput()
c1 = (float(f) - 32) * (5/9)
InputBox.ShowDialog("Enter the 2nd numberFahrenheit value:")
f = InputBox.GetInput()
c2 = (float(f) - 32) * (5/9)
import MessageBox
MessageBox.Show(str(c1) + "\n" + str(c2))
5. Type python lab1_5.py to execute the program. A sample output looks:
and
6. Capture a screen shot similar to the above and paste it to a Microsoft Word document named “lab1.doc”
(or .docx).
Submittal
1. Upon the completion of learning activities, use Windows Compressed (zipped) Folder or Winzip to compress
the following files and name the zipped file lab1.zip:
• lab1_1.py
• lab1_2.py
• lab1_3.py
• lab1_4.py
• lab1_5.py
• lab1.doc (or .docx)
Python Programming – Penniel P. Wu, PhD. 35
2. Upload it to Question 11 as response (available at http://cypresscollege.blackboard.com) as response.
Programming Exercise #01:
1. Create a Python source file named “ex01.py” that will include the following two lines. Be sure to replace
YourNameHere with your full name.
# Student: YourNameHere
# Programming Exercise: 01
2. Next to the above lines, use the “Message Box Code” (as shown it in learning activity #1~4) to write a
functioning Python code that will produce the following outputs. Be sure to replace YourNameHere with your
full name. [Hint: use “\n” to insert blank lines]
3. Download the “programming exercise template”, and rename it to ex01.doc. Capture a screen shot similar to the
above figure(s) and paste it to a Microsoft Word document named ex01.doc (or ex01.docx).
4. Compress both ex01.py and ex01.doc (or ex01.docx) to a .zip file named ex01.zip.
5. Upload the ex01.py file as response of Question 12.
Note: Your code must be fully functional to earn the credit. No partial credit is given. You will receive zero points if
either .py or .doc (or .docx) file is not submitted.
Appendix A:
1. Use the text editor (such as “Notepad” or “gedit”) to create a new file named “InputBox.py” with the following
content:
####File name: InputBox.py
import tkinter
from tkinter import *
root = Tk()
e1 = Entry(root, width=55)
result = ""
def ShowDialog(s):
root.title("Input Box")
root.geometry("355x100+30+30")
Label(root, justify=LEFT, text = s).grid(row=0, column=1, sticky=W, padx= 10,
pady=5)
e1.grid(row=1, column=1, padx= 10, pady=5)
button1 = Button(root, text=" OK ", command = button1_Click)
button1.grid(row=2, column=1, sticky=E, padx= 10, pady=5)
root.mainloop()
def button1_Click():
f = open('tttemp', 'w')
Python Programming – Penniel P. Wu, PhD. 36
f.write(e1.get())
f.close()
e1.delete(0,END)
root.quit()
def GetInput():
f = open('tttemp', 'r')
result = f.read()
f.close()
import os
os.remove('tttemp')
return result
2. Use the text editor (such as “Notepad” or “gedit”) to create a new file named “MessageBox.py” with the
following content:
#File name: MessageBox.py
import tkinter
from tkinter import *
def Show(str):
root = Tk()
root.title('Message Box')
Label(root, justify=LEFT, text = str).grid()
root.mainloop()
3. Keep both “MessageBox.py” and “InputBox.py” files. You will frequently use them throughout this course.
Appendix B: Installing Live USB Ubuntu
1. In a Windows 10 machine, use a web browser to visit the https://www.ubuntu.com/download/desktop site.
2. Download the latest .ISO versio of Ubuntu (As of Feburary, 2018, it is 17.10.1). The file name is similar to
“ubuntu-17.10.1-desktop-amd64.iso”, and the file size is approximately 1.5GB.
3. Use a browser to visit the https://rufus.akeo.ie/ site.
4. Download the latest version of “Rufus” (as of Jan 2018, it is Rufus 2.18 and the file name is “rufus-2.18.exe”).
5. Insert the “non-persisten” USB drive to a port. Record its drive name (such as. “E”).
6. Launch Rufus. A window similar to the following appears.
Python Programming – Penniel P. Wu, PhD. 37
7. Verify that the “Device” column is pointed to the correct drive (such as. “E”).
8. Click the “folder” icon and locate the Ubuntu ISO file” (e.g. ubuntu-17.10.1-desktop-amd64.iso).
9. Click Start.
10. Click OK on the following warning windows.
and
11. Wait till the writing completes. Capture a screen shot similar to the following and named it “ex01.png”. Upload
only this file to Question 12 of Assignment.
12. Use the newly re-created “non-persistent” USB drive to boot into Linux.
13. After the desktop is fully loaded, click “Try Ubuntu”.
Python Programming – Penniel P. Wu, PhD. 38
14. In the Ubuntu desktop, press Ctrl + Alt + T to launch the “Terminal” which is a command-line interface
containing the prompt. The following is a sample shell prompt with a prompt sign ($).
ubuntu@ubuntu:~$
15. In the prompt, type python3 and press [Enter] to launch python.
ubuntu@ubuntu:~$ python3
Python 3.6.2 (v3.6.2:37dagde53fg8s9, Sep 1 2017, 02:16:59) [GCC 7.1.1 20170802
(Ubuntu 7.1.1-7)] on Linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
16. Press Ctrl-Z to exit Python and return to Linux shell prompt.
17. With access to Internet, type sudo apt-get install python3-tk and press [Enter] to install the “tk”
module.
$ sudo apt-get install python3-tk
18. Type gedit lab1_0.py and press [Enter] to use the “gedit” to create a new file named “lab1_0.py”, with the
following content.
s = "Hello world!"
###### Message Box Code ######
from tkinter import *
root = Tk()
root.title('Message Box')
Label(root, justify=LEFT, text = s).grid(padx=10, pady=10)
root.mainloop()
19. Exit the “gedit” and return to the shell prompt.
20. Type python3 lab1_0.py and press [Enter]. If all configuration are done successfully, you should now see a
pop-up window similar to the following.
21. Proceed to learning activity #1.
Appendix C: Copy entire Python directory to a USB flash drive (For Windows users only)
1. Plug in the USB drive. Record the assigned drive name (e.g. “F”).
Python Programming – Penniel P. Wu, PhD. 39
2. Copy the entire “python-32” directory to a USB flash drive and rename it to “python36”.
3. Open the Command Prompt, type X: and press [Enter] to change to the flash drive (replace “X” with the correct
drive name). The following uses “F” as example.
C:\Users\user>F:
F:\>
4. Type notepad runpython.bat and press [Enter] to use Notepad to create a batch file named “setup.bat”.
F:\>notepad runpython.bat
5. Click Yes to confirm.
6. Enter the following DOS command.
path=%path%;%CD%python36;
7. Save the file and exit Notepad. You should now return to the Command Prompt.
F:\>
8. Type runpython.bat to set the path. Depending on the current settings of the machine, the output varies.
However, make sure the X:\python36 path is appended, as shown below.
F:\>runpython.bat
F:\>path=C:\Windows\system32;........;F:\python36;
9. Type python (or python3 for Linux user) and press [Enter] to test the settings. The installation succeeds if
something similar to the following appears. Notice that “>>>” is the Python prompt.
F:\>python
Python 3.6.2 (v3.6.2:37dagde53fg8s9, Sep 1 2017, 02:16:59) [MSC v.1900 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
10. Press Control + Z and then [Enter] to terminate the python interpreter and return to the Command Prompt.
F:\>
11. Close the Windows Command Prompt.