Quick viewing(Text Mode)

Lecture #1 Introduction to Python Introduction Python Is a High-Level

Lecture #1 Introduction to Python Introduction Python Is a High-Level

Lecture #1 Introduction to Python

Introduction Python is a high-level general-purpose , 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 2019 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. 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 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 it is available under an open source license although the language is copyrighted.

The latest generation of Python is Python 3. There has been some discussions about the future Python 4. However, nothing is released by Python.org as of the day this lecture is written. This lecture and all its sample codes are designed based on Python 3.

Getting Python Most Windows users starts the learning journey with downloading and installing the Python interpreter which is a program that reads Python codes and converts the Python codes to machine codes at the runtime. However, the Python codes will remain being a text-based contents stored in a text file.

Python source codes Python intepreter Operating system

Linux users probably do not need to go through the installation , because most 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 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 July 2020, the latest stable release is Python 3.8.3, which was released on 13 May 2020. The file name is python-

Python Programming – Penniel P. Wu, PhD. 1 3.8.3.exe for Microsoft Windows users. By the way, this is the primary source, and the entire Python platform can be installed in a USB drive. • ActivePython (http://www.activestate.com/activepython/downloads). • Portable Python (http://www.portablepython.com/). This is a Python package preconfigured to run directly from any USB storage device, enabling users 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 An “interpreter” of a programming language is a program that reads and converts a sequence python of instructions in a “script” (a text file containing the source codes) into machine codes for the interpreter computer to execute the instructions on the fly. One major difference between Python and , C++, Java, and C# are 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”). An “interpreter” only reads the script file and convert the source codes to machine codes at the runtime, but it does not produce any individually executable program.

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. Only when the Python script is present, the program is ready to be called for execution.

Python C, C++, Java, and C#

Source Interpreter Source Compiler Executable Code Code

Output Executable Output

On the C, C++, Java, and C# side, once compiled, the source code is no longer needed. The compiled code is the program. 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 as shown below. 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.

>>> print("Hello, World!") Hello, World!

The Python interpreter is a console application, which means it only runs in a -line interface (CLI) environment such as the “Command Prompt” of a Windows operating system or a terminal emulator of the Linux operating system, as shown below.

Windows Command Prompt Terminal emulator

Python Programming – Penniel P. Wu, PhD. 2

The prompt (or 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 ~]$

By typing \ (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 \ [liveuser@localhost ~]$ cd / [liveuser@localhost /]$ C:\>

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. [Details about using Python 3 in Linux platform are available at the https://docs.python.org/3/tutorial/interpreter.html site.]

[liveuser@localhost ~]$ python3 Python 3.8 (default, Sep 16 2019, 09:25:04) [GCC 4.8.2] on linux Type "", "copyright", "credits" or "license" for more information. >>>

Interestingly, users of Microsoft Windows operating systems need to add the of the Python directory in the “PATH” 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:\Python\” is not added to the “PATH” environment variable. The following demonstrates how to manually configure the path settings (assuming the path is “C:\python\”). 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:\python;

Python Programming – Penniel P. Wu, PhD. 3 The following is another way to set the path. It uses the DOS “set” command.

C:\>set path=%path%;C:\python;

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.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 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 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”.

input Python Prompt Python Intepreter 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:\python\ 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 Programming – Penniel P. Wu, PhD. 4 Python values, Python is designed to operate on data. A single piece of data can be called a value. A value is expressions and one of the fundamental things, such as a letter, a number, or a word, that a program statements manipulates. The following demonstrates how to assign a value, 5, to a variable named “x”. Consequently, “x” represents a value: 5. In other words, “x” is said to be the “identifier” of the variable. By the way, “>>>” is the Python prompt which is designed as an interactive interface that take an individual Python statement from the user, and then display output.

>>> x = 5

Below is an example that instructs the Python interpreter to display a letter on the screen as a value.

>>> 'a' 'a'

Values and other Python code components are used to form “expression” and “statements”. An “expression” is a combination of explicit values, constants, variables, operators, and/or functions to indicate a state or a condition. In the following example, (5 > 3) is an expression which will be evaluated to be true.

>>> (5 > 3) True

In terms of programming, a “statement” is an instruction for the computer program to perform an action, while an “expression” is any section of the code that evaluates to a value. In other words, a statement is a complete line of code that performs some action, while an expression is a combination of values, variables, operators, and calls to functions. In the following example, only 5 + 3 is a Python expression, it instructs the Python interpreter to perform an addition operation.

>>> print(5 + 3) 8

In Python, a statement can be an individual instruction given to the interpreter to produce a value as result. In the above example, print(5+3) is the statement. It is a combination of an expression, 3 + 5, and a call to a Python-provided function name “print()”. Altogether, the statement instructs the Python interpreter to perform an addition operation of two operands: 5 and 3, then, it calls the “print()” function to display the calculated result on the screen (or other standard output device). The outcome, 8, will be displayed afterwards.

A Python statement can also be a syntactic unit of a program when a sequence of statements is organized into a Python-specific code block, as shown below.

>>> if (5>3): print("Correct!") else: print("Incorrect!")

Correct! >>>

Programmers can organize Python statements with logical sequence to a Python “script”. A Python script is a program written consists of a sequence of one or more statements. Below is a sample script. It uses the “input()” function to take user entries from keyboard, then uses the “int()” function to convert the user entries to integers. In Python, user entries are treated as “string literals” (or “texts” or combination of characters). A later section will discuss how to executable a Python script.

x = int(input("Enter an integer: ")) y = int(input("Enter an integer: "))

Python Programming – Penniel P. Wu, PhD. 5 if (x>=y): print(x, "is greater.") else: print(y, "is greater.")

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)

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 >>> w=37.4

In terms of programming, a “string” literal refers to a sequence of characters (or a combination of characters). A string is a piece of “text-based value” and does not represent any unit no matter what it looks to human eyes. A “number”, on the other hand, represent some “units”; therefore, it is numerical value. In Python, a “string literal” must be enclosed by a pair quotes, either single or double quotes.

Literal Type string number Example "482" 482

Meaning A combination of three individual 400 + 80 + 2 units character: 4, 8, and 2.

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 and 37.4 of the above statements are numbers (which indicates “units”), while “21” and ‘37.4’ in the following are “strings” (combinations of characters) 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. By the way, the “type()” function can return the data type of a value.

>>> x=21 >>> type(x)

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.

Python Programming – Penniel P. Wu, PhD. 6 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. The following demonstrates how to let 5 raise to the third power.

>>> 5**3 125

푛 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 1.7320508075688772

1 Since 0.5 = , the following returns the same result. 2

>>> 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.

Python Programming – Penniel P. Wu, PhD. 7 Windows 7/8 Linux >>> y*2 >>> y*2 8.7 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, or i=√−1. Interestingly, in math, √−1 is not computable because it is not a real number. By the way, in Python, the imaginary unit, i, is represented by the letter j.

>>> (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”. In some programming language, such as C++, the operation of 22/7 will return 0 due to the regulation of data type [Note: In a data type sensitive language, operation of an integer and another integer will produce an integer]. 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 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”. It is necessary to note that a “blank space” is also character. A “blank space” take memory space, and is designed to show a blank space on screen.

Python Programming – Penniel P. Wu, PhD. 8

>>> 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 As stated previously, in terms of programming, a “statement” is the instruction written by writing Python elements of a programming language to perform some action. A Python program is formed by statements a sequence of one or more statements. Each statement is either a single line of code 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.

>>> 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:

Python Programming – Penniel P. Wu, PhD. 9 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 repetition structure because it is a single statement that will be executed repeatedly. 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 “to 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" "is fun"), 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.

>>> print("Python" "3" "is fun") Python3is fun

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 “int()” function can also convert a string literal to integer.

>>> x = "21" >>> int(x) 21

Python Programming – Penniel P. Wu, PhD. 10 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 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 (:), Python interpreter expects the next line to be indented. However, Python does not specify the number of blank spaces 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!

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

Python Programming – Penniel P. Wu, PhD. 11 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 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 >>> 1 + 2 + 3 + 4 \ 45 ... + 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" + " " + \ ... "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

Python Programming – Penniel P. Wu, PhD. 12 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("" ... "" ... "

Welcome to CIS247!

" ... "")

Welcome to CIS247!

In the following example, the instructor uses commas to add a blank space between every two lines.

>>> print("", ... "", ... "

Welcome to CIS247!

", ... "")

Python Programming – Penniel P. Wu, PhD. 13

Welcome to CIS247!

In the following example, the instructor uses the (“\n”), which is one of the escape sequences, to insert a newline in the text at this point.

>>> print("\n" ... "\n" ... "

Welcome to CIS247!

\n" ... "\n")

Welcome to CIS247!

Python, as a user-friendly language, allows users to declare a variable to continuously store the output of expressions. In the following example, “s” is a variable, (3 + 5) is an expression that will produce a value 8, “str()” is a function that can converts a numerical value (such as 8) to a string literal, and “\n” is an “escape sequence” that means “add a newline” which is functionally equivalent to an [Enter] key. In Python, the plus sign (+) can be used as the “addition” operator that performs an addition calculation. It can also be used as the “concatenation” operator which combines two values (of same data type or of different data types) to a single string literal. By the way, an escape sequence is a sequence of characters that is used in a programming language to represent some language-specific feature.

>>> s = str(3 + 5) + "\n"

addition concatenation

Below is another statement that will perform a “concatenation” operation by adding the result of the partial statement, str(3 > 5) + "\n", to the end of the value that is currently stored in the “s” variable. The, assign the value produced by the statement, s + str(3 > 5) + "\n", to the “s” variable as its new value. By the way, all the three plus signs (+) are concatenation operators.

>>> s = s + str(3 > 5) + "\n"

The following performs an operation of (3 - 5), converts the output (-2) to a string literal, and then assigns the string literal to the “s” variable. The concatenation assignment (+=) operator concatenates the value of the right operand and assigns the value to that “s” variable. In other words, the following is functionally equivalent to: s = s + str(3 - 5).

>>> s += str(3 - 5)

The following demonstrates how to use the “print()” function to display the cumulated values of the “s” variable.

>>> print(s) 8 False -2

Python The term “scripting” refers to the arrangement of series of statements with logical flow and Scripting 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 enough to create and edit the script.

Python Programming – Penniel P. Wu, PhD. 14

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. The statement, i = i + 1, means adds 1 to the “i” and then assign the results of the addition operation to “i”. Consequently, “i” stores the updated value.

i = 5 print(i) i = i + 1 print(i) i = i - 3 print(i)

Throughout this course, the students will frequently display the output in a GUI () which is a rectangular “message box”. Below is the GUI version of the above code, in which “s” is a string variable. The instructor uses the “s” variable to repeatedly store the updated value of the “i” variable using the “addition assignment”, +=. The “addition assignment”, +=, will add the new content as additional line(s) of the old content. Since the “i” variable is declared as int type (integer data type), while “s” is declared a string type, it is necessary to use the “str()” converter to convert the value of “i” variable from int type to string type. By the way, the “message box” code is created by the instructor as the “template code”.

s = "Results:\n" # declare s as string

i = 5 s += str(i) + "\n"

i = i + 1 s += str(i) + "\n"

i = i - 3 s += str(i) + "\n"

###### Message Box Code ###### from tkinter import *

root = Tk() root.('Message Box') Label(root, justify=LEFT, text = s).grid(padx=10, pady=10)

root.mainloop()

Python Programming – Penniel P. Wu, PhD. 15

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 \ $ cd ~ C:\>cd cis247 $ cd cis247 C:\>cis247\python test.py $ 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 $ python test.pty 5 5 6 6 3 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 “”, 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 else:

Python Programming – Penniel P. Wu, PhD. 16 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:\Python\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 5 formula to converts a temperature degree in Fahrenheit to Celsius is: C = (F-32) × , where F 9 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 A Python “module” is a Python source file that provides definition of functions, variables, or module in classes. Similar to a Python script, Python modules are reusable Python codes created by Python? 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. • file name of both modules and scripty must end with the “.py” extension;

Python Programming – Penniel P. Wu, PhD. 17 • 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 scripts 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. 18 What is a A “Python library” is a collection of useful Python codes, modules, and/or packages, to Python library? 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 /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)

root.mainloop()

Python Programming – Penniel P. Wu, PhD. 19

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 In programming, outputs of a data to the screen or a message box (as the one created by the display issue 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 table lists some commonly used converters.

Function Description int(x) Converts x to an integer.

float(x) Converts x to a floating-point number.

str(x) Converts object x to a string representation.

chr(x) Converts an ASCII code (an integer) to a character.

unichr(x) Converts an integer to a character.

ord(x) Converts a single character to its ASCII code (an integer value).

Python Programming – Penniel P. Wu, PhD. 20

The following demonstrates how to convert the integer, 78, to a letter, ‘N’.

>>> chr(78) 'N

The following convert a single character, ‘G’, to its ASCII code, 71.

>>> ord('G') 71

Comment in In programming, a “comment” is an annotation, programmer's notes, or text-based Python 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.

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 Python 3 comes with an online helper, the “help()” utility, which is a built-in function help 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()

Python Programming – Penniel P. Wu, PhD. 21 Welcome to Python 3.8's 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) ......

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 As stated previously, as of February 2018, there are currently two major versions of Python Python 2 used in the industry: Python 2 and Python 3. Although Python 2 is probably more popular and programmers 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.

Python Programming – Penniel P. Wu, PhD. 22 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 2.x Python 3 >>> 1 / 2 >>> 1 / 2 0 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 1. If the Python software is installed in C:\python39 directory, which of the following can Questions 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'

Python Programming – Penniel P. Wu, PhD. 23 C. 8 D. '8'

5. When using the Python prompt as an electrical calculator, which of the following 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 >>> 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. 24

Lab #1 Introduction to Python

Preparation #1: (For Linux user, skip preparation #1 and #2. But read Appendix B) 1. In a Windows machine, hold the windows key ( or ) and then press E to launch the “Windows Explorer”.

2. On the toolbar click “View”.

3. Be sure to check the “File name extension” option if it is not checked.

4. 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.8.3.

5. Click the downloaded .exe file (e.g. python-3.8.3.exe) to launch the installation wizard.

6. In the following screen, be sure to write or copy the directory path (e.g. C:\users\user\AppData\Local\Programs\Python\Python38-32) on a piece of paper for later use. Your path may be different from the given example.

Write this path on a paper

Check these boxes

Python Programming – Penniel P. Wu, PhD. 25 7. Ensure that the “Install launcher for all users (recommended)” and the “Add Python 3.8 to PATH” checkboxes at the bottom are checked. Then, click “Install Now”.

8. till the “Setup Progress” page pops up.

9. Wait till the installation completes, and then click Close.

10. Use Windows Explorer (not Internet Explorer) to navigate to the directory you wrote down previously (e.g. C:\Users\user\AppData\Local\Programs\Python\Python38-32). The path must be correct. Your path will be different from the given example.

11. Find and double-click the python.exe file. A pop-up window will appear display messages similar to the following. By the way, “>>>” is the Python prompt. If you see the python prompt (>>>), your installation and configuration complete successfully.

Microsoft Windows [Version 10.0.16299.192] (c) 2018 Microsoft Corporation. All rights reserved.

C:\Users\user>python Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>

12. Press Ctrl+Z and then press [Enter] to Python. It will also close the Command Prompt window.

Python Programming – Penniel P. Wu, PhD. 26 13. On the Windows desktop, click the Windows menu and find the “Python 3.8” folder. Then, expand the folder. Verify the “Python 3.8 (32-bit)” and “IDLE (Python 3.8 32-bit)” options are available.

Preparation #2: Testing the Python Interpreter (Windows users only) 1. On the Windows desktop, type cmd in the search box to find the “Windows Command Prompt” (not Python prompt), as shown below. Then, click the “Command Prompt” link to launch it.

2. Wait till a pop-up window similar to the following appears. Notice that your prompt will be different from the given example which is “C:\Users\user>”.

3. In the prompt, 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.

Python Programming – Penniel P. Wu, PhD. 27 C:\Users\user>cd c:\cis247 C:\cis247>

5. Type python and press [Enter] to test the path configuration. If configured correctly, you should see the Python prompt (>>>). Otherwise, you simply forgot to check the “Add Python 3.8 to PATH” box during one of the previous steps.

Correct Incorrect Microsoft Windows [Version 10.0.17763.557] Microsoft Windows [Version 10.0.17763.557] (c) 2018 Microsoft Corporation. All rights (c) 2018 Microsoft Corporation. All rights reserved. reserved.

C:\Users\user>python C:\Users\user>python Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 'python' is not recognized as an internal or 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on external command, win32 operable program or . Type "help", "copyright", "credits" or "license" for more information. C:\Users\user> >>>

6. If correctly configured, press Ctrl+Z and then press [Enter] to exit the Python prompt. You should now return to the Windows Command Prompt.

C:\cis247>

7. 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

8. Click Yes to confirm.

9. In the Notepad window, enter the following Python statements. Be careful, it is case-sensitive.

print("Hello world!")

10. In the Notepad toolbar, click “File” and then “Save” to save the file. You can close the Notepad window now.

11. Type python lab1_0.py and press [Enter] to compile it. A sample output looks:

C:\cis247>python lab1_0.py Hello World!

12. Close the Windows Command Prompt.

Preparation #3: Using Idle’s Python Prompt (Windows users only) 1. Click Windows menu, find and expand the “Python 3.8” folder. Then, click “IDLE (Python 3.8 32-bit)”.

2. Wait till the Idle window appears, similar to the following.

Python Programming – Penniel P. Wu, PhD. 28

3. In the prompt, type print("Hello World!") and press [Enter]. The output will appear in the next line.

>>> print("Hello World!")

Preparation #4: Using Idle to Create, Save, and Run Python Script File (Windows users only) 1. In the Idel window, click “File”, and then “New File”.

2. In the newly popped-up editing window, type the following Python statement.

print("Welcome to Python!!")

3. Click “Run” and then “Run Module”.

4. Click OK to save the script file.

Python Programming – Penniel P. Wu, PhD. 29 5. Save the file as “lab1_0.py” to the “C:\cis247” directory.

6. If the following window appears for confirmation, click Yes.

7. The output is displayed in the Idle’s Python prompt.

Learning Activity #1: Windows OS Users Linux Users 1. Be sure to complete Preparation #1 and #2 before proceeding to 1. Be sure to read Appendix B before the next steps. proceeding to the next step.

2. Launch the Windows Command Prompt. 2. Boot into Linux, and then open a Terminal Emulator. 3. In the prompt, type cd c:\cis247 and press [Enter] to change to the “cis247” directory. 3. Type cd ~/cis247 and press [Enter] to change to the “~/cis247” C:\Users\user>cd c:\cis247 directory.

4. Under the “cis247” directory, type python (or python3 for Linux $ cd ~/cis247 user) and press [Enter] to launch the Python interpreter. “>>>” is the Python prompt. 4. In the shell prompt, type python3 and press [Enter]. C:\cis247>python Python 3.8.3(v3.7.2:37dagde53fg8s9, Sep 1 2018, $ python3 02:16:59) [MSC v.1900 32 bit (Intel)] on win32 Python 3.8.3(v3.7.2:37dagde53fg8s9, Sep 1 2018, 02:16:59) [GCC 7.1.1 20180802 Type "help", "copyright", "credits" or "license" for (Ubuntu 7.1.1-7)] on Linux more information. 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

Python Programming – Penniel P. Wu, PhD. 30

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

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).

Python Programming – Penniel P. Wu, PhD. 31

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, “s” is a string variable that stores the results, and “+=” is the “addition assignment” which can “append” new “text” to the “s” variable.

s = "Results:\n" # declare s as string

#example 1 x=21 s += str(x) + "\n" # + is concatenation

#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:

Python Programming – Penniel P. Wu, PhD. 32 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 Windows Command Prompt (or a Linux Terminal emulator).

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

Python Programming – Penniel P. Wu, PhD. 33 12. Type "tree" == "Tree" and press [Enter] to check if these 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”.

>>> "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

Python Programming – Penniel P. Wu, PhD. 34 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)

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.

Python Programming – Penniel P. Wu, PhD. 35 >>> 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

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. From the Windows desktop, click the “Start” menu ( ), and then scroll up and down to find the “Python 3.x” folder. Expand the Python folder to find the “IDLE (Python 3.8 32-bit)” link.

12. Click the “IDLE (Python 3.8 32-bit)” link to launch the IDLE.

13. On the toolbar, click “File” and “New File” to launch the editor.

Python Programming – Penniel P. Wu, PhD. 36

14. In the editor’s work area, type in the following 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()

15. On the toolbar of the editor, click “Run”, and then “Run Module”.

16. Click OK to save the file, as shown below.

Python Programming – Penniel P. Wu, PhD. 37

17. Be sure to save the file as lab1_3.py under the “cis247” directory.

18. A sample output looks:

19. 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 interpreter.

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:

Python Programming – Penniel P. Wu, PhD. 38 ... 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) ... 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 +

Python Programming – Penniel P. Wu, PhD. 39 ... 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 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"

Python Programming – Penniel P. Wu, PhD. 40

#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):

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. (See Appendix of Lab #1 for details)

2. Open a Windows Command Prompt (or Terminal Emulator for Linux user).

3. Change to the “cis247” directory, and then launch the Python interpreter.

4. In the “cis247” directory, use Notepad (or “gedit” for Linux user) to create a new file named lab1_5.py with the 5 following Python code. This script is an implementation of C=(F-32)× 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:

Python Programming – Penniel P. Wu, PhD. 41 and

6. Capture a screen shot similar to the above and paste it to a Microsoft Word document named “lab1.doc” (or .docx). [Feel free to convert the Word document to a .pdf file.]

Submittal 1. Upon the completion of learning activities, 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 or .pdf)

2. Upload it to Question 11 as response (available at http://cypresscollege.blackboard.com) as response.

Programming Exercise #1_1: 1. Create a Python source file named “ex1_1.py” that will include the following two lines. Be sure to replace YourNameHere with your full name.

# Student: YourNameHere # Programming Exercise: 1_1

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 then rename it to ex1.doc. Copy and paste the source code to the template. Capture a screen shot similar to the above figure(s) and paste it to a Microsoft Word document named ex1.doc (or ex1.docx). [Feel free to convert the Word document to a .pdf file.]

Programming Exercise #1_2: 1. Create a Python source file named “ex1_2.py” that will include the following two lines. Be sure to replace YourNameHere with your full name.

# Student: YourNameHere # Programming Exercise: 1_2

2. Next to the above lines, write a Python code that “imports” both the “MessageBox.py” and “InputBox.py” files to create an input box that asks the user to enter her/his fullname. Then, display a message “Welcome, fullname to Python Programming!” similar to the following. Be sure to replace fullname with the user’s full name.

Python Programming – Penniel P. Wu, PhD. 42 and

3. Capture a screen shot similar to the above figure(s) and paste it to a Microsoft Word document named ex1.doc (or ex1.docx). [Feel free to convert the Word document to a .pdf file.]

Submittal (Please read the instructions carefully) 1. Create a .zip file named “ex1.zip” containing ONLY the following self-executable files and Word document. Be sure to copy and paste your source codes to the Word document. • ex1_1.py • ex1_2.py • ex01.doc (or .docx, or .pdf) [You may receive zero point if this Word document is missing]

2. Upload the zip file as response of Question 12.

Grading criteria: You will earn credit only when the following requirements are fulfilled. No partial credit is given. • You successfully submit both source file and executable file. • Your source code must be fully functional and may not contain syntax errors in order to earn credit. • 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.

Python Programming – Penniel P. Wu, PhD. 43 Appendix A: 1. Use the text editor (such as “Notepad” or “gedit”) to create a new file named “InputBox.py” with the following content. [By the way, you can download a zipped file containing these two files at http://students.cypresscollege.edu/cis247/files/inout.zip]

####File name: InputBox.py import tkinter from tkinter import *

root = Tk() e1 = Entry(root, width=55) l1=Label(root, justify=LEFT) result = ""

def ShowDialog(s):

root.title("Input Box")

l1.grid(row=0, column=1, sticky=W, padx= 10, pady=5) l1['text'] = s

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') f.write(e1.get()) f.close() e1.delete(0, END) l1['text'] = "" 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.

Python Programming – Penniel P. Wu, PhD. 44 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 version of Ubuntu (As of July 2019, it is 19.04). The file name is similar to “ubuntu- 19.04.1-desktop-amd64.iso”, and the file size is approximately 1.5GB.

3. Use a browser to visit the https://rufus.ie/ site.

4. Download the latest version of “Rufus” (as of July 2019, it is Rufus 3.5 and the file name is “rufus-3.5.exe”).

5. Insert the “non-persistent” USB drive to a port. Record its drive name (such as. “E”).

6. Launch Rufus. A window similar to the following appears.

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.

Python Programming – Penniel P. Wu, PhD. 45

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”.

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.8.3(v3.7.2:37dagde53fg8s9, Sep 1 2018, 02:16:59) [GCC 7.1.1 20180802 (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

Python Programming – Penniel P. Wu, PhD. 46 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.

Python Programming – Penniel P. Wu, PhD. 47 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”).

2. Copy the entire “python-32” directory to the USB flash drive and rename it to “python”.

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 “runpython.bat”.

F:\>notepad runpython.bat

5. Click Yes to confirm.

6. Enter the following DOS command.

path=%path%;%CD%python;

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:\python” path is appended, as shown below.

F:\>runpython.bat F:\>path=C:\Windows\system32;...... ;F:\python;

9. Type python 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.8.3(v3.7.2:37dagde53fg8s9, Sep 1 2018, 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.

Python Programming – Penniel P. Wu, PhD. 48