Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
34 views

Python Bridging2023

This document provides an introduction to Python programming. It discusses installing the Python interpreter and integrated development environments (IDEs) like IDLE. It explains how to use the Python shell interactively and write Python scripts. The document also covers running Python scripts from the command line interface (CLI).

Uploaded by

t t
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Python Bridging2023

This document provides an introduction to Python programming. It discusses installing the Python interpreter and integrated development environments (IDEs) like IDLE. It explains how to use the Python shell interactively and write Python scripts. The document also covers running Python scripts from the command line interface (CLI).

Uploaded by

t t
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Python Programming

Bridging Course for MScAECON & MScDABE

J. LIU AEF HKBU


Learning Goals
1. Command-line Interface (CLI)
} Terminal (macOS) or Command Prompt (Windows)
} Basic Commands in CLI:
} Navigate the file system
} Create, Open, Rename, Move, Copy, and Delete Files/folders

2. Python Interpreter and IDEs


} Download and Install Python
} Python programming: switch between the Python Shell and CLI
} Python IDEs: Pycharm & Jupyter Notebook
} Manage python packages and environments

3. Python Programming
} Numbers, Strings, and Lists
} Dictionary, Arrays and Data Frames
} Flow control: For loop, While loop, If-else
} Python functions and modular programming
} Data exploration and visualization
J. LIU AEF HKBU
Command-line Interface
} Unlike graphic user interface (GUI), Command-line Interface (CLI) interacts
with the operating system using text-based commands.
} Terminal (macOS) or Command Prompt (Windows)

Prompt Prompt

~ is a shortcut for the home directory on It is always a good practice to run


Mac (i.e., /Users/jingliu). Command Prompt as administrator.

} A prompt is a sequence of characters to indicate the CLI’s readiness to


accept commands.
} It ends in $, %, # or >, indicating that you can type commands there.
} It includes the path of current working directory and hostname.

J. LIU AEF HKBU


Some Simple Commands and Shortcut

} Try below commands in your CLI.


} echo hello world display some text (i.e., “hello world”)
} date display the date of today
} (macOS) clear or (Windows) cls
} exit

} Some shortcut keys


} Control + C abort what you're doing, get back to normal prompt.
} (macOS) Command + Q or (Windows) Alt + F4 quit the CLI.
} same as exit

J. LIU AEF HKBU


Navigate the File System
} Most computers use a hierarchical file system. For example:
} /Users/jingliu/OneDrive - Hong Kong Baptist University (macOS)
} C:\Users\BIZtech\OneDrive - Hong Kong Baptist University (Windows)
In windows, use \ instead of /

} Navigate the file system with below commands


} (macOS) pwd (Windows) cd print current working directory (CWD)
} (macOS) ls (Windows) dir display all folders/files in CWD
} cd <path> change to another directory (either absolute or relative path)
} cd .. go up one layer (cd ../.. go up two layers)
} cd / go to the root of the file system
} cd (Tab) autocomplete commands
} cd ~ back to the home directory (only available on macOS)

J. LIU AEF HKBU


} /Users/jingliu/OneDrive - Hong Kong Baptist University (macOS)

print the path name of current working directory (CWD)


list all files in CWD

cd <relative path>

move one layer up from CWD


move one layer up again
cd <relative path>

cd <absolute path>

J. LIU AEF HKBU


} C:\Users\BIZtech\OneDrive - Hong Kong Baptist University (Windows)

print the path name of CWD

cd <absolute path>
Move one layer up from CWD
Move one layer up again
cd <relative path>
move two layers up
cd <relative path>
list all files in CWD

go to the root folder (C:\)


change to the G drive (no cd command)

J. LIU AEF HKBU


Create, Open, and Rename Files
} Create a new folder in CWD
} mkdir <folder> (use “<folder>” if the folder name contains space)

} Create a new empty file in CWD


} (macOS) touch <file> (e.g., touch test.txt)
} (Windows) type nul > <file> (e.g., type nul > test.txt)

} Open a file
} (macOS) open <file> (Windows) <file>

} Rename a file
} (macOS) mv <source file> <new file> rename (by moving)
} (Windows) ren <source file> <new file>
Note: Path name of the folders/files can be either relative or absolute
J. LIU AEF HKBU
Note: Path name of the files/folders can be either relative or absolute

Move, Copy and Delete Files


} Move a file into another folder
} (macOS) mv <source file> <destination folder>
} mv <file 1> <file 2> <destination folder> copy two files
} (Windows) move <source file> <destination folder>

} Copy files/folders
} (macOS) cp <source file> <destination folder>
} cp <file 1> <file 2> <destination folder> copy two files
} cp *.* <destination folder> copy all types of files
} (Windows) copy <source file> <destination folder>

} Delete files/folders
} (macOS) rm <file> delete <file>
} (macOS) rm –r <folder> delete <folder> and all files/folders in it
} (Windows) del <file> delete <file>
} (Windows) rmdir /s <folder> delete <folder> and all files/folders in it
J. LIU AEF HKBU
Go to the folder

Create a folder named new_folder


Create a new file new_file.txt
Open it
Rename it as new_file123.txt

Copy test.txt and put it into new_folder

Delete new_file123.txt

Delete new_folder (alternatively, use rm –rf)


Go to the folder

Create a new folder named new_folder

Create a new file new_file.txt


Open it
Rename it as new_file123.txt

Copy test.txt, put into new_folder

Delete new_file123.txt

Delete new_folder
Exercise 1 (20 mins)
} Open the CLI, create folders and files by completing the below steps.
1. Create a folder (my_folder) at a place you can easily find, navigate to it. (mkdir, cd)
2. Within the work_folder, create an empty txt file test1.txt and a new folder sub_folder.
(touch/type, mkdir)
3. Navigate to sub_folder and create another empty file test2.txt. (cd, touch/type)
4. Copy test1.txt from my_folder to sub_folder, and rename the copy as test1_copy.txt.
(cp/copy, mv/ren)
5. Move test1.txt from my_folder to sub_folder as well. (mv/ move)
6. Check the list of files in sub_folder. (ls/dir)

my_folder my_folder

test2.txt

test1.txt sub_folder sub_folder


test1_copy.txt

test2.txt
test1.txt

J. LIU AEF HKBU


Online Resources

} Mac Terminal User Guide


} https://support.apple.com/en-hk/guide/terminal/welcome/mac

} Windows Commands
} https://docs.microsoft.com/en-us/windows-
server/administration/windows-commands/windows-commands

} PowerShell: cross-platform command-line interface


} https://docs.microsoft.com/en-
us/powershell/scripting/overview?view=powershell-7.2

J. LIU AEF HKBU


Python Interpreter and IDEs

J. LIU AEF HKBU


Install Python
} Download Python from: https://www.python.org/
} Download and install the latest versions (either Python 3.10 or 3.11)

Add to PATH variable


(Windows) so that you
can find it easily in CLI

J. LIU AEF HKBU


In windows Command Prompt, you may
use python if python3 is not found.

Python Interpreter
} Open your CLI and check if the Python interpreter is properly
installed in your computer, with below commands:
} python3 --version
} where python3
} which python3 (only for macOS)

J. LIU AEF HKBU


Python IDLE
} Python IDLE (Integrated Development and Learning Environment),
automatically installed with the interpreter, provides both shell and
code editing functions.
} Python Shell is an interface to interact with Python Interpreter.
A Python Shell

Prompt

} With a Code Editor, you can write a python script: open a new file editing
window (File -> New File), type in Python codes and save it as test.py in
your work folder.
J. LIU AEF HKBU
In windows Command Prompt, you may
use python if python3 is not found.

Python Programming in CLI


} Run the python script test.py in CLI
} python3 “/Users/jingliu/OneDrive - Hong Kong Baptist University/Bridging_python/test.py”

the absolute path (macOS)


} python3 test.py

the relative path (if you are already in Bridging_python folder)

} Switch CLI as a Python shell


} Python3 invoke the python interpreter
} Then you can use CLI as a python shell.
} exit() return to a normal command prompt
} or Ctrl & D (macOS), Ctrl & Z (Windows)

J. LIU AEF HKBU


PyCharm
} PyCharm is a free open-source IDE (Integrated Development
Environment) with a smart Python editor providing quick code
navigation, code completion, unit testing and debugger.

} Download PyCharm (make sure Python is already installed).


} URL: https://www.jetbrains.com/pycharm/

Select the free


Community version
(Note the difference between intel
and Apple Silicon for macOS)

J. LIU AEF HKBU


Always a good practice to Run
PyCharm as Administrator

PyCharm Setup and Basics

Create a
new project

J. LIU AEF HKBU


PyCharm Setup and Basics
} Create a project with system interpreter.

Specify the project


folder name as
pythonProject, which
is used to save all data
and python files

Use Python interpreter


installed in the default
system.

J. LIU AEF HKBU


Create a Python script test.py
in the Project Folder, and write
some codes.

J. LIU AEF HKBU


Run a Python Script in Python Console
Write some python codes

Right click your mouse and try


• Execute Line in Python console (run
a line only)
• Execute Selection in Python console
(select multiple lines first)
• Run file in Python Console (run the
entire python file)

J. LIU AEF HKBU


Run a Python Script in Terminal

A more effective way


to run python codes
(grey now), need to
add configuration first.

Run the entire python


script in terminal

J. LIU AEF HKBU


Run Configurations
} PyCharm uses run/debug configurations to run, debug, and test your
code. A configuration is a set of properties that define what to
execute and what environment should be used.

Run the python script

J. LIU AEF HKBU


Run button is green now

A temp configuration is generated


automatically, you may save it as
permanent one.

Output returned when running a python script

J. LIU AEF HKBU


} Alternatively, you can add a new Run Configuration manually (e.g.,
test_manual).
} Click “Run Configurations..” and then the “+” button below

Select the path


to your python
script

Make sure the


project folder is
set as working
directory

J. LIU AEF HKBU


} After adding the Run Configuration…

Choose the config and


press the green button
to run the script

J. LIU AEF HKBU


} TODO

TODO function help list all


the things we need to do in
the project.

J. LIU AEF HKBU


Exercise 2 (30 mins)
} In PyCharm, create a project folder named pythonProject in
your work folder, using the Python interpreter installed in your
system environment.

} Open exercise2.py and let’s start coding!


} Download the python script exercise2.py from student codes.
} You may need to move the script into your project folder first.

} We will cover below topics:


} Using python as a calculator: numbers, strings, lists
} Python flow control: for loop, while loop, if-else statement
} Python functions and modular programming

J. LIU AEF HKBU


Exercise 3 (30 mins)
} A clinic has three doctors: Alice, Richard and Jane. Assume you were hired
to write a program to automate two tasks: (1) check the availability of a
doctor, (2) check total payment given a specific doctor and number of
session booked by a client.

} Create a module named consultation.py with two functions.


} check_doctor() function returns a sentence about whether the parameter (doctor)
value a client passed in is in the doctor list or not.
} First create a list (doctor_lst) with three names: Alice, Richard, Jane.
} Use if .. in .. statement to check whether the doctor is in the clinic or not.
} Use print function to return the output for each condition.
} check_bill() function takes two parameters (doctor, session), and return the total
payment a client need to pay.
} The three doctors charge $200, $300, and $400 per session respectively.
} If a wrong name is inputted, return “Please check the name of Doctor again.”

} Import the module in another python script and test those functions.

J. LIU AEF HKBU


Manage Python Packages & Virtual
Environments

J. LIU AEF HKBU


Python Packages
} A Python Package is a directory of modules (e.g., pandas, matplotlib)
created by thirty-parties for various purposes.

} pip3 is the official package manager and pip command for Python3.
Try below commands in CLI.
} pip3 --version check pip version
} pip3 list check installed python packages
} pip3 install <package> install a package
} pip3 uninstall <package> uninstall a package
} pip3 install --upgrade <package> upgrade a package
} pip3 freeze > requirement.txt record an environment’s package list in a
txt file requirement.txt for future use.

Without pip3, use python3 –m pip

} pip documentation: https://pip.pypa.io/en/stable/cli/

J. LIU AEF HKBU


Manage Packages with pip
} Install a python package in CLI.
} You may work in the terminal provided in PyCharm as well.

Install pandas using pip3 in CLI

J. LIU AEF HKBU


Manage Packages in PyCharm

Go to Python Packages tab, type the package


name (e.g., matplotlib) in the search box Click install button

J. LIU AEF HKBU


Virtual Environments
} A virtual environment is a tool that create a separate and
isolated environment for each project.
} There are various packaging tools (virtualenv, venv, pipeenv,
conda) you can use to create a virtual environment in a CLI.
} A more convenient approach is to use the menu tabs in graphic
user interfaces (GUI) such as PyCharm or Anaconda Navigator.

J. LIU AEF HKBU


Virtual Environments in CLI
} Install the tool virtualenv in CLI.
} pip3 install virtualenv install the module
} virtualenv --version check the version

} Create a virtual environment named my_env1 in CWD.


} virtualenv my_env1 create an isolated environment
} virtualenv my_env1 --system-site-packages inherit global site-packages
from the operation system
Without virtualenv, use python3 -m venv

} Activate the virtual environment my_env1.


} (macOS) source my_env1/bin/activate
} (Windows) my_env1\Scripts\activate

J. LIU AEF HKBU


Virtual Environments in CLI
} After activating the virtual environment my_env1:
} Active environment name is displayed in brackets before CWD.

} Check packages installed in the activated virtual environment


} pip3 list
} Install packages you need without interfering with other projects.
} pip3 install <package>
} pip3 install –r requirement.txt
install packages as listed in a txt file (note this is a relative path)

} Deactivate/Leave the current virtual environment.


} deactivate
} remove the virtual environment installed in the CWD.
} rm –r my_env1
J. LIU AEF HKBU
Print the current working directory
Navigate to work folder

Create a virtual environment named my_env1

Activate my_env1
Check python packages installed in my_env1

install pandas in my_env1


Install packages listed in txt file

Check packages installed in my_env1 again

Freeze the list of packages in my_env1


and save it in a txt file at CWD.

Go back to system environment


Remove my_env1 from CWD
Virtual Environments in PyCharm
Create a new project folder named pythonProject1

Create a new
environment using
different tools

Decide whether to
inherit packages
from the global
system , same as A virtual environment
virtualenv venv -- named venv (default name)
system-site-
packages

J. LIU AEF HKBU


Virtual Environments in PyCharm

Under the project folder pythonProject1, there is


a virtual environment named venv.

Check the terminal, you are now in a virtual


environment venv already, are there any
packages installed?

J. LIU AEF HKBU


Exercise 4 (20 mins)
} Open your CLI, manage python packages and environments by
completing below tasks:
1. Check the list of python packages installed in default system
environment.
2. Install three python packages (pandas, numpy, matplotlib) in your
default system environment using pip3.
3. Record python packages installed in system environment into
requirement3.txt. Save the txt file in your work folder.
4. Navigate to your work folder and create two virtual environment named
venv1 and venv2 respectively.
q venv2 inherits python packages installed in global system, while venv1 doesn’t.
5. Activate each environment one by one and check python packages
installed there. Any difference?
6. For venv1, install the python packages listed in requirement3.txt.

J. LIU AEF HKBU


Jupyter Notebook
} Jupyter Notebook is a web-based interactive development
environment which supports various programming languages.
} It encourages an execute-explore workflow, instead of the typical edit-
compile-run workflow as in PyCharm.
} It also provides integrated access to your operating system’s shell and file
system.

J. LIU AEF HKBU


Install and Launch Jupyter Notebook

} Install Jupyter Notebook in the CLI


} pip3 install notebook, or
} pip3 install jupyter installs the Jupyter system, including the
notebook, qtconsole, and IPython kernel.

} Launch Jupyter Notebook from CLI


} jupyter notebook
(better navigate to project folder first before launching it)

J. LIU AEF HKBU


Add Virtual Environment to Jupyter Notebook
} First, activate your virtual environment (e.g., venv).
} Second, install IPython kernel there, which is the Python execution
backend for Jupyter.
} pip3 install ipykernel

} Third, add the active environment (venv) to Jupyter Notebook.


} ipython kernel install --user --name=venv
Installed kernelspec venv in /Users/jingliu/Library/Jupyter/kernels/venv

} After launching jupyter notebook, switch kernel to venv for use.


} jupyter notebook

} Check all virtual environments for Jupyter Notebook and remove a


environment (e.g., venv) from Jupyter Notebook at the CLI.
} jupyter kernelspec list
} jupyter kernelspec uninstall venv
J. LIU AEF HKBU
Exercise 5 (30 mins)
} Launch Jupyter Notebook in a virtual environment env_jn.
} Add the virtual environment env_jn to jupyter notebook.
} Switch kernel to env_jn after launching jupyter notebook.
} Open exercise5.ipynb, which can be downloaded from student_codes.

Note this step is optional, you can use Jupyter Notebook with the default
python environment.

} Let’s start python programming in Jupyter Notebook!


} Markdowns, Headings, Comments
} Built-in modules, third-party packages
} Arrays, Dictionary and Data frames
} Data exploration with pandas and matplotlib
} Save your work in a readable format
J. LIU AEF HKBU
Recap

} Softwares
} Command-line interfaces
} Python Interpreter and IDLE
} Python IDEs: PyCharm, Jupyter Notebook

} Techniques
} Interact with your computer using commands
} Install and manage python packages using pip3
} Manage virtual environments using virtualenv
} Python programming

J. LIU AEF HKBU


Online Resources
} The Python Standard Library
} https://docs.python.org/3.10/library/index.html

} Python Package Index (PyPI) is a public repository of open-source


licensed packages created by other Python users.
} https://pypi.org/

} For all third-party packages, always a good practice to check the


documentation from the official website
} e.g. https://pandas.pydata.org/ for pandas

} Stack Overflow is a Q&A website for professional and enthusiast


programmers.
} https://stackoverflow.com/

J. LIU AEF HKBU

You might also like