MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Jupyter notebook – Lab Session – 10 – Introduction of Data Types, Variables & checkpoint

This lab is a Jupyter notebook that introduces Python's basic data types (str, int, float, bool), variables and naming rules, arithmetic, comparison and string operators, and the list, tuple and dict collections. The guide below explains what each group of cells shows, why some cells deliberately fail, what the word "checkpoint" in the file name means, and fills in topics the notebook skips, such as type conversion, floor division and safe dictionary lookups.


What the notebook covers

The notebook embedded above is a run-through of Python fundamentals inside Jupyter. Each cell is short and shows one idea with its output. This table maps the cells to the concept each one demonstrates, so you can find a topic quickly.

CellsConceptKey takeaway
a = "hacktiv8", a = 8, a = "8"Dynamic typingA variable has no fixed type. type() reports the type of the value it currently holds, so 8 and "8" are different types.
Quote examplesString literalsUse the other quote style, or escape with \' / \", to put a quote inside a string.
123123123123123123123 + 1IntegersPython integers have arbitrary precision and do not overflow.
4., .4e7, 4.2e-4FloatsScientific notation always produces a float.
a = b = c = 300, var = 24.5 then a stringAssignmentChained assignment, and a variable can be rebound to a value of another type.
age, Age, AGE, _ageIdentifiersNames are case-sensitive and cannot start with a digit.
+ - * / % **, == != <= >=Operators/ always returns a float. Comparisons return bool.
s + t, s * 4, in, .upper()String operationsConcatenation, repetition, substring test and case methods.
List cellsListsOrdered and mutable, with indexing, negative indexing, slicing, del and slice assignment.
Tuple cellsTuplesOrdered and immutable. Supports unpacking into several variables.
MLB_team, personDictionariesKey/value pairs that can be added, updated, deleted and nested.
someone_is_of_working_ageLine continuationWrap a long expression in parentheses to split it over several lines.

Run the lab yourself

  1. Create an isolated environment and install JupyterLab with the commands below.
  2. Download the notebook from the gist embedded above (via the gist's Download ZIP button, or with git clone), then give it a clean name.
  3. Start JupyterLab and open the notebook.
  4. Use Kernel > Restart Kernel and Run All Cells. The cells were originally run out of order (the execution counts jump from 2 to 4, 9 to 11, and so on), and a clean top-to-bottom run shows the real outputs.
  5. Two cells stop with SyntaxError. This is deliberate. Read the error and move on to the next cell.
python3 -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install jupyterlab

git clone https://gist.github.com/082ee2640365eda326b5eb61aa1aef32.git lab10
cd lab10
mv Jupyter-notebook-DataTypes-Variables-checkpoint.ipynb datatypes-variables.ipynb

jupyter labCode language: PHP (php)

To run the whole notebook without the browser, for example in CI, use nbconvert. Without --allow-errors, execution stops at the first intentional SyntaxError.

jupyter nbconvert --to notebook --execute --allow-errors \
  datatypes-variables.ipynb --output executed.ipynbCode language: CSS (css)

Note: The notebook metadata shows a Python 3.8 kernel. Python 3.8 is end-of-life, so use a supported Python 3 release. All the cells behave the same on current versions, though some error messages are worded differently.

Why two cells fail on purpose

Unescaped quote. In print('This string contains a single quote (') character.'), the second ' closes the string early. Python then reads character. as code and finds a new string that never closes. Older Python versions report invalid syntax. Recent versions say unterminated string literal. There are three fixes:

print("This string contains a single quote (') character.")   # switch outer quotes
print('This string contains a single quote (\') character.')   # escape the quote
print("""Quotes ' and " both work inside triple quotes.""")    # triple quotesCode language: PHP (php)

Invalid identifier. 9_kepala_naga = True fails because a variable name cannot start with a digit. Python reads 9_ as the start of a number (underscores are allowed in numeric literals, as in 1_000_000), so it reports invalid decimal literal. Rename it to kepala_naga_9 or nine_headed_dragon. Names can contain letters, digits and underscores, cannot be a keyword such as class or for, and by convention use snake_case.

Why a cell shows only one value

Jupyter automatically displays only the value of the last expression in a cell. A bare expression earlier in the cell is evaluated, and its result is thrown away. This explains several outputs in the notebook:

  • a = 30, a, b = 20, b shows only 20. The a on line 2 is never displayed.
  • In the name = "ANI" cell, name and 'ANI' show nothing. Only the print(name) output appears.
  • In the person = {} cell, type(person) shows nothing because more statements follow it.

To show several values from one cell, use print(), or display(), which is available in IPython kernels and keeps rich formatting:

a = 30
b = 20
print(a, b)        # 30 20
display(a)         # 30
display(b)         # 20

# Or tell IPython to echo every bare expression in later cells
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"Code language: PHP (php)

Type conversion and operators the lab skips

The notebook shows that 8 and "8" have different types but never converts between them. Data you read from files, forms or input() usually arrives as strings, so conversion comes up constantly. Run this cell after the lab. The expected output is in the comments.

a = "8"
b = int(a)
print(b + 2, type(b))            # 10 <class 'int'>
print(float("4.2") * 2)          # 8.4
print(str(8) + "8")              # 88
# "8" + 2  -> TypeError: can only concatenate str (not "int") to str

print(7 // 2, -7 // 2)           # 3 -4   (floor division rounds down)
print(7 % 2, divmod(7, 2))       # 1 (3, 1)
print(10 < 20, 10 > 20)          # True False
print(18 <= 42 <= 65)            # True  (chained comparison)

print(0.1 + 0.2)                 # 0.30000000000000004
print(round(0.1 + 0.2, 2))       # 0.3

print(bool(0), bool(""), bool("False"))   # False False True
print(type(None))                # <class 'NoneType'>
print(isinstance(True, int))     # True  (bool is a subclass of int)Code language: PHP (php)

Chained comparisons also make the line continuation example shorter and easier to read: (18 <= person1_age <= 65) or (18 <= person2_age <= 65) or (18 <= person3_age <= 65).

Lists, tuples and dictionaries: behaviour to know

In the slice assignment cell, a[1:4] = [1.1, 2.2, 3.3, 4.4, 5.5] replaces three items with five, so the list grows from 6 to 8 elements. A slice on the left side of = does not need to match the length of the new values. The cell below covers the edge cases beginners hit most often:

# Tuples are immutable
t = ('foo', 'bar')
# t[0] = 'x'  -> TypeError: 'tuple' object does not support item assignment
print(type(('foo')), type(('foo',)))   # <class 'str'> <class 'tuple'>  (the comma makes the tuple)

# min()/max() on strings compare by Unicode code point, not pure alphabet order
print(min(['foo', 'Bar', 'apple']))                  # Bar  (uppercase sorts first)
print(min(['foo', 'Bar', 'apple'], key=str.lower))   # apple

# Missing dictionary keys
d = {'a': 10}
# d['z']  -> KeyError: 'z'
print(d.get('z'), d.get('z', 0))       # None 0
print('a' in d)                        # True (checks keys, not values)

# Chained assignment with mutable objects shares ONE object
x = y = []
x.append(1)
print(y)                               # [1]
x, y = [], []                          # two independent listsCode language: PHP (php)

Note: a = b = c = 300 is safe because integers are immutable. With lists or dicts, all three names point to the same object, so a change through one name shows up through the others.

What checkpoint means in this lab

The -checkpoint suffix in the file name is not a Python concept. It comes from Jupyter's checkpoint feature. When you save a notebook explicitly (Ctrl+S, or Save and Checkpoint in the classic interface), Jupyter writes a snapshot to a hidden .ipynb_checkpoints/ folder next to the notebook, named <notebook>-checkpoint.ipynb. Autosave updates the notebook file itself but leaves the checkpoint alone. If you break a notebook, File > Revert Notebook to Checkpoint restores the last explicit save.

  • Jupyter keeps one checkpoint per notebook by default. It is a quick undo, not version history. Use Git for history.
  • Add .ipynb_checkpoints/ to .gitignore so snapshot copies are never committed or shared by mistake, which is how this lab's file name ended up with the suffix.
  • Clear outputs before committing to keep diffs small: jupyter nbconvert --clear-output --inplace datatypes-variables.ipynb.

Corrections to the original notebook

OriginalCorrectedWhy
print("Hackiv8 " + "PTP")print("Hacktiv8 " + "PTP")Typo. Every other cell spells it Hacktiv8.
#len(), min(), max() berdasarkan dari urutan abjad# len(), min(), max(): min/max compare strings by Unicode code pointThe comment is in Indonesian ("based on alphabetical order"), and the order is not purely alphabetical because uppercase letters sort before lowercase.
#in Opeators# in operatorTypo in the comment.
"Now I'am a String""Now I'm a String"Grammar in the string literal.
a = 30 / a / b = 20 / bprint(a) and print(b)Only the last expression in a cell is displayed, so a never appears.
File saved as ...-checkpoint.ipynbSave as a plain name such as datatypes-variables.ipynbThe file is a Jupyter checkpoint snapshot, not the working notebook.

Frequently asked questions

Why does type("8") return str while type(8) returns int?

Quotes make a value a string literal, whatever characters it contains. Use int("8") or float("8") to convert it before doing arithmetic.

Why does 10/5 give 2.0 instead of 2 in Python?

In Python 3 the / operator always performs true division and returns a float. Use // for floor division, which returns an int when both operands are ints.

What is the .ipynb_checkpoints folder in Jupyter?

Jupyter creates it to hold a snapshot of each notebook from its last explicit save, which you can restore with Revert Notebook to Checkpoint. It is safe to delete, and you should add it to .gitignore.

Why does my Jupyter cell show only the last value?

Jupyter displays only the result of the final expression in a cell. Use print() or display() for any other values you want to see.

What is the difference between a list and a tuple in Python?

Both are ordered sequences that support indexing and slicing. You can change a list in place, but a tuple is immutable, which makes it suitable for fixed records and usable as a dictionary key.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services — all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Jupyter notebook – Lab Session – 8 – Calculating Descriptive Statistics with math, statistics, numpy, pandas

This lab calculates descriptive statistics in a Jupyter notebook with Python's built-in math and statistics modules, NumPy, SciPy and pandas. It covers central tendency (mean, weighted, harmonic…

Read More

Jupyter notebook – Lab Session – 5 – Exploring Datasets with Pandas and Matplotlib

This lab loads the UN Canada immigration dataset (Canada.xlsx) into a pandas DataFrame, cleans it, and draws a waffle chart with Matplotlib comparing total immigration from Denmark,…

Read More

Jupyter notebook – Lab Session – 6 – Conditions, Control Flow & Looping

This lab works through Python decision-making and looping in a Jupyter notebook: if, elif and else, one-line conditionals, the conditional (ternary) expression, pass, while and for loops,…

Read More

Jupyter notebook – Lab Session – 4 – Exploring Datasets with Pandas

This lab loads the Canada immigration dataset (1980 to 2013) from an Excel file into a pandas DataFrame. It then inspects the data with head(), tail(), info(),…

Read More

Jupyter notebook – Lab Session – 2 – Analyzing Data with Pandas, NumPy & Visualizing Data with matplotlib

This lab loads a historical earthquake dataset into a Jupyter notebook with pandas, joins the separate Date and Time columns into one datetime column, and makes it…

Read More

Why Your Jupyter Notebook Forgets Everything Between Sessions

A notebook you closed on Friday rarely opens the same way on Monday. The file is exactly as you left it — every cell, every output, every…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x