from __init__ import install_dependencies
await install_dependencies()
To access the course homepage, visit:
If you have not yet registered the course, visit the static site:
- For your first lab session, access
Lab0
Course Materials
- For your first lecture session, access
Lecture1
Introduction to Computer Programming
Notebooks¶
Lecture and lab materials are written in the form of Jupyter notebooks, which provide an interactive literate programming experience, which is a significant benefit in making programs easy to understand:
- Jupyter notebooks allow programs to be mixed with other contents, including figures, videos, and formatted textual explanations.
- The notebooks can also be opened in a Jupyter server, which enables users to edit and run the programs in addition to other contents.
How to run notebook cells?¶
If you already have your notebook opened in a Jupyter server, let’s run some code. Otherwise, jump to the next section to learn how to fetch and open notebooks.
To run a cell, select the cell and press Shift + Enter. The cell prompt with change from [ ]
to [*]
. When the run completes, the asterisk will be changed to a number like [1]
. Try running the following cell to import the Mathematical Animation Engine (Manim).[2]
import os
if not os.getenv(
"NBGRADER_EXECUTION"
): # Skip the code or auto-grading may take too long to complete.
import manim
After the import is complete, run the following cell to create an animation:
%%manim -qm --progress_bar=none --disable_caching --flush_cache -v ERROR Welcome
class Welcome(manim.Scene):
def construct(self):
self.play(manim.Write(manim.Text("Welcome to CS1302!")))
As you can see, the code creates a scene that displays the message Welcome to CS1302!
with a writing animation.[3] To verify that the program runs live, feel free to modify the message to anything you want.
How to fetch and open notebooks?¶
To fetch the notebooks, follow the links to the notebooks on the course homepage such as the one in Table 1.
After clicking a notebook link, you may be asked to
- login with your CityU account if you are not yet logged into Canvas, and
- specify a server option if you do not yet have a running Jupyter server.
Select the Default
option from the list of available Jupyter servers, and click Start to begin your session.
What are the other server options?
The course’s programming environment is conveniently accessible via a JupyterHub server, allowing remote access without the need to install any special software, thanks to Project Jupyter. This means you can easily write and run programs on your mobile devices using just a web browser. Each student will have their own Jupyter server with individual computing resources including CPU, memory, and GPU.
- Each server runs the Ubuntu operating system in a container. See the Dockerfile for details.
- The GPU resources are useful for customized AI applications.
- You can switch between the
Default
and other server options at any time by restarting your server and selecting the desired option. Restarting the server is simple and can be done by- selecting
Hub Control Panel
under theFile
menu, and - click
Stop My Server
and thenStart My Server
.
- selecting
If the server is spawned successfully, the JupyterLab interface should appear.
Troubleshooting
In case the jupyterlab interface fails to show, refresh the page or restart your browser for the javascript to load completely in your browser. If the server fails to spawn, which is very likely if you try to spawn a GPU server, you can restart after clicking the Home
link.
You may occasionally run into issues. There are thousands of open issues reported to the JupyterLab repository, where you may find related issues and a kludge (temporary workaround):
As you start your programming journey, you will inevitably encounter software bugs, especially in highly sophisticated software such as JupyterLab. Be aware of their existence, and develop a positive attitude towards bugs, as well as cultivate a proper skill set to inspect and debug them effectively.
As an example to inspect a computer program, we will explain how the notebook link works. First, run the following code to start the notebook link generator app.
from notebook_link_generator import setup_notebook_link_widget
display_widget = setup_notebook_link_widget(canvas_id="60298")
display(display_widget)
Change the Notebook path
above to Lecture1/Introduction_to_Computer_Programming.ipynb
and observe the live update to the generated link.
Now, run the following two cells to see how a notebook link is generated stey-by-step:
%load_ext divewidgets
%%optlite -r
from urllib.parse import quote
# Course parameters
course_id = "cs1302_24a"
notebook_path = "Lecture1/Introduction_to_Computer_Programming.ipynb"
canvas_id = "60298"
# Base URLs
notebook_repo = f"https://github.com/dive4dec/{course_id}"
course_server = "https://dive.cs.cityu.edu.hk"
course_homepage = f"https://canvas.cityu.edu.hk/courses/{canvas_id}"
# Notebook URL generation
# 1. Construct the URL for git-pull service to clone or pull the notebook repository
gitpull_url = (
f"{course_server}/{course_id}/hub/user-redirect/git-pull?"
+ f"repo={quote(notebook_repo)}"
+ f"&urlpath={quote(f'lab/tree/{course_id}/{notebook_path}')}"
)
# Construct the LTI (Learning Tools Interoperability) launch URL for JupyterHub
lti_url = (
f"{course_server}/{course_id}/hub/lti/launch?" + f"custom_next={quote(gitpull_url)}"
)
# Construct the LTI external tool URL to open the notebook
notebook_url = (
f"{course_homepage}/external_tools/retrieve?display=borderless&"
+ f"url={quote(lti_url)}"
)
notebook_url
After running the code, you can:
- see the generated notebook link for
Lecture1/Introduction_to_Computer_Programming.ipynb
in the output cell; - inspect parts of the code in the input cell by placing the cursor there and press Shift + Tab; and
- visualize the execution step-by-step by clicking Next > (< Prev) to go the the next (previous) line.
What does the notebook link do?
The notebooks reside in a GitHub repository. Accessing a notebook link will
- use LTI Authenticator to launch the JupyterHub as an LTI external tool from the course homepage, and
- use NbGitPuller to git-pulls all the files in the repository, merge them with any existing files stored under the course folder
cs1302_24a
in your home directory without overwriting your changes, and open the notebook path specified in the JupyterLab interface.
Assignments¶
How to complete an assignment?¶
The notebooks can be edited in JupyterLab to include your answers for submission. If this is your first time using JupyterLab, take a look at the official video tutorial:
How to use JupyterLab?
Official video tutorial on Jupyter
For more advanced features:
- Checkout the
Help
menu itemsShow Keyboard Shortcuts
to try some of the shortcuts to see their effect, andJupyter Reference
to open the user guide in a new tab.
- Try also the MyST Markdown syntax to format your notes.
An alternative interface: VSCode
You may also use a highly customizable editor Visual Studio Code (VS Code) to open a notebook:
- Click
File
->New Launcher
->VS Code
. - Click the menu icon on the left and select
Open Folder
and selectcs1302_24a
.
In the file explorer, you can navigate to a notebook to open it. However, to properly run the notebook, you would also need to start the Kernel by choosing an appropriate Python environment such as base
, which is the default (conda) environment for our JupyterLab setup. Unlike JupyterLab, you may install additional extensions yourself to enrich the interface.[4]
In learning a new programming language, the first program to write is often the “Hello, World!” program, which says Hello to the world. As your first lab exercise, you will write such a program in python.
The following code cell is a solution cell. Since you are not expected to know python yet, you can simply expand the hint above and copy the answer to the solution cell instead.
def say_hello():
# YOUR CODE HERE
raise NotImplementedError
say_hello()
It’s important to follow certain guidelines when writing your answers or code in the notebooks:
- Only provide your answers in the cells that are designated for this purpose, which are usually labeled with
YOUR CODE HERE
orYOUR ANSWER HERE
. - For coding exercises, be sure to remove the line
raise NotImplementedError()
from the cell before submitting your work. - Do not clone or duplicate the answer cells, as this can cause issues with version control and grading.
To test your program:
- Run your program by selecting the solution cell and press Shift + Enter.
- Then, run the following visible test to check whether your program prints the correct message.
# Run this test cell right after running your "Hello, World!" program.
import io
import sys
old_stdout, sys.stdout = sys.stdout, io.StringIO()
say_hello()
printed = sys.stdout.getvalue()
sys.stdout = old_stdout
assert printed == "Hello, World!\n"
The test returns an assertion error if your program does not print the correct message.
- You can repeatedly modify your solution and run the test cell until your solution passes the test. There is no mark penalty in failing the test before submission.
- You should try to understand the error messages from a failed test.
- To assess your solution thoroughly, we will run new tests hidden from you after you have submitted your notebook. Therefore, you should ensure your solution works in general rather than just the visible tests.
- If you open the same notebook multiple times in different browser windows, be careful in making changes in different windows as you may overwrite your own changes.
- If your notebook fails to run any code, the kernel might have died. You can restart the kernel with
Kernel
Restart
. If restarting fails, check your code cells to see if there is anything that breaks the kernel.
How to submit?¶
- Late submissions will not be accepted without valid justifications.
- You can submit your assignment repeatedly before the deadline without penalty, so it is recommended to submit your assignment in advance. Please note that you are responsible for any issues related to failed submissions due to network outages that occur too close to the deadline.
- It is also important to make a record or backup of your submission that includes the submission timestamp. Double check to ensure that you have submitted the correct lab assignment, since multiple lab assignments may be open for submission at the same time.
You normally have at least 5 days to work on the lab after your lab session.
- You can check the due dates of all the labs from the course homepage.
- You may seek help from us or your classmates. However, you must write your own solution and indicate who your collaborators are by including their fullnames or EIDs such asThe policy applies to LLM as well.
COLLABORATORS: xfwong2, mklee3, GPT-4o
- Lecture notebooks under the subfolders
Lecture*\
need NOT be submitted. You only need to submit the lab notebooks underLab*\
.
Before you submit, it is a good idea to make sure everything runs as expected:
- Git-pull the notebooks: Follow any one of the link on the course homepage to a notebook, which will git-pull any updates/corrections to (all) your notebooks.
- Save the notebook: Unsaved changes are not submitted, even though they are in the memory.
- Restart the kernel:
Kernel
Restart Kernel...
to have a clean state before running visible tests. - run all cells:
Run
Run All Cells
to double check the results of the visible tests are as expected.
Re-executing cells in order in a Jupyter Notebook ensures that all dependencies and state changes are correctly applied, preventing misleading results from out-of-order execution.
- By default, JupyterLab autosaves an opened notebook every 120 seconds. This configuration can be changed at
Settings
Settings Editor
Document Manager
Autosave Interval
. - An opened file with unsaved changes has a solid circle next to its tab label. You can manually save the file using the save button in the toolbar.
To submit your notebook:
- Select the menu item
Nbgrader
Assignment List
. - Expand the Lab folder and click the
validate
button next to the notebook(s) to check if all the visible tests pass. - Click
Submit
to submit your notebook.
What is Nbgrader?
Nbgrader is a package for grading notebook assignments. It allows students to submit their notebooks directly through the JupyterHub server. Submitted notebooks can be both auto-graded with pre-defined test cases and manually graded with custom feedback. After grading is complete, you can check your scores and access the feedback using the same interface.
Your submission may not be graded under the following circumstances:
- The notebook files have been renamed, for example,
Setup.ipynb
being changed or copied toSetup (Copy).ipynb
. - An HTML file exists with the same name as a notebook, for example,
Setup.html
. - The file size is too large, e.g., exceeds
100MB
. - The code takes too long to run or requires an excessive amount of memory.
It is essential to ensure that your submission meets these guidelines to avoid any issues with grading.
Troubleshooting
If you believe your notebooks are corrupted,
- download/backup your existing notebooks,
- remove them from the
Lab*/
folder, - click the git-pull links from the course homepage to re-pull the notebooks, and
- copy your solutions to the new notebooks.
You may also run the course notebooks outside the jupyterhub server and locally on your computer. For more details, see the course homepage.
References¶
Reading is important in learning a new language. This is especially so for learning a programming language, whose syntax has a very precise structure and interpretation. Each topic will have some required readings listed on the course homepage.
The textbook by Halterman in Table 2 teaches Python programming using Python version 3.4.[5] As a programming language can evolve quickly over times, especially for a popular language like Python, it is important to be aware of the version you are using, and supplement your readings with the documentations of the newer versions. In particular, check out the documentations for:
- Python 3.12, which is used for quiz and exam.
- Python 3.11, which is used for lab assignents.
Is it okay to learn and use different versions of Python?
The version such as 3.12
consists of the major version number 3
followed by the minor version number 12
.
New features introduced in later versions may not work in earlier versions, and old features in earlier versions may be removed in newer versions. As an analogy, the prior is like trying to play VCD in a CD drive, and the latter is like imposing region restriction on VCD like the way we do for DVD. Both fails due to compatibility issues.
Nevertheless, it is generally okay to learn and use different minor versions of Python under the same major version, such as Python 3.*
, where
3
is the major version number, and*
is a wilcard matching any number called the minor version number.
This is because Python’s design has made a conscious effort to maintain backwards compatibility for the minor versions, which mean that code written in an earlier minor version runs in a later minor version.
If you have more time, further supplement your learning with materials from similar introductory python programming courses at other universities:[1]
MIT Open Courseware
An introductory programming course using Python:
- Course homepage: 6.0001
Introduction To Computer Science And Programming In Python
Textbook: Guttag, John V. Introduction to computation and programming using Python: with application to computational modeling and understanding data. Mit Press, 2021.[6]
An introductory programming course using Scheme:
UC Berkeley Course
An introductory programming course using Python:
- Course homepage: CS 61A Structure And Interpretation Of Computer Programs
Textbook: John DeNero. Composing Programs.
As a student at CityU, you also have access to a wide range of library resources. A useful e-learning resource to help you dive deeper into the cutting-edge computing technologies is LinkedIn Learning:
- Open the LinkedIn Learning page.
- Click LinkedIn Learning Login to login with your CityU account.
After logging in, take a look at the following relevant online courses:
LinkedIn Learning
Some courses on introductory python programming:
A course on how to use LinkedIn Learning:
Importing a library in programming is like bringing a toolbox into your workshop, giving you access to all the tools you need to complete your tasks.
If you are interested in what the first line does, it sets the video quality to medium while disabling caching and progress bars, and setting the verbosity to reporting only ERROR but not other critical information.
The VSCode interface is actually code-server, so some VSCode extensions may not be listed under the extension panel. You may still try to install them using the command
install-vscode-extension
in a terminal. This is only for advanced users who know what they are doing, or the risk of breaking things can be rather high...See the list of python versions at https://
www .python .org /doc /versions/ Note that these assume students have no prior programming experience but they may different topics than our course does.
After clicking the link, CityU students can further link to the full text from the
View Online
section of the opened CityU library page.