Lecture 3 Core Python Language¶
Mostly copied from the official python tutorial
- Total: 100
- Complete All Example Code: 20
- Exercise: 30
- Assignment: 40
- AI usage description: 10
Using AI in this assignment¶
For this assignment, do not use AI to write Python for you.
Right now you are learning basic syntax and how to take a problem apart. Those skills are built by getting stuck on a small error and working out why — that is not wasted time, that is the lesson. An assistant that hands you working code removes exactly the practice you need, and the gap shows up later, when the problems are hard enough that you cannot check an answer you do not understand. Later in the semester, once the syntax is automatic, we will use AI deliberately, and some assignments will require it.
What you may use AI for on this assignment:
- Interpreting an error message you do not understand — "what does
IndexError: list index out of rangemean?" - Suggesting a debugging strategy — "how can I find out which line in my loop is producing this error?"
What you may not use AI for on this assignment:
- Writing, completing, or fixing any code you submit — lecture code, exercises, or the assignment
- Answering the exercise or assignment questions for you
Anything beyond interpreting an error and suggesting how to hunt it down is outside the policy for this assignment.
You must describe your AI usage. It is worth 10 points (see Section 10). For every time you used AI, record which question you were working on, the exact prompt you typed, and what you did with the answer.
If you did not use AI at all, say so in Section 10 — that earns full marks. The points are for an honest, complete account, not for using AI.
1. Invoking Python¶
There are three main ways to use python.
- By running a python file, e.g.
python myscript.py - Through an interactive console (python interpreter or ipython shell)
- In an interactive iPython notebook
We will be using the iPython notebook.
2. Basic Variables: Numbers and String¶
# comments are anything that comes after the "#" symbol
a = 1 # assign 1 to variable a
b = "hello" # assign "hello" to variable b
HintsThe following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here:
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
Additionally, the following a built in functions which are always available in your namespace once you open a python interpreter
abs() dict() help() min() setattr() all() dir() hex() next() slice() any()
divmod() id() object() sorted() ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str() bool() exec() isinstance() ord() sum() bytearray()
filter() issubclass() pow() super() bytes() float() iter() print() tuple()
callable() format() len() property() type() chr() frozenset() list() range()
vars() classmethod() getattr() locals() repr() zip() compile() globals() map()
reversed() __import__() complex() hasattr() max() round() delattr() hash()
memoryview() set()
# how to we see our variables?
print(a)
print(b)
print(a,b)
1 hello 1 hello
All variables are objects. Every object has a type (class). To find out what type your variables are
# as a shortcut, jupyter notebooks will automatically print whatever is on the last line
type(a)
type(b)
str
type(a) is int
True
Hints Different objects attributes and methods, which can be accessed via the syntax variable.method
IPython will autocomplete if you press <tab> to show you the methods available.
# this returns the method itself
b.capitalize
<function str.capitalize()>
# this calls the method
b.capitalize()
# there are lots of other methods
'Hello'
# binary operations act differently on different types of objects
c = 'World'
print(b + c)
print(a + 2)
print(a + b)
helloWorld 3
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[9], line 5 3 print(b + c) 4 print(a + 2) ----> 5 print(a + b) TypeError: unsupported operand type(s) for +: 'int' and 'str'
Exercise 1 (4 points):¶
Define a float variable d = 8. Print the type of the variable.
3. Math¶
Basic arithmetic and boolean logic is part of the core python library.
# addition / subtraction
1+1-5
-3
# multiplication
5 * 10
50
# division
1/2
0.5
# that was automatically converted to a float
type(1/2)
float
# exponentiation
2**4
16
# rounding
round(9/10)
1
# built in complex number support
(1+2j) / (3-4j)
(-0.2+0.4j)
Exercise 2 (6 points):¶
Let a = 2, b = 3.3, c = 2, calculate the following equation.
$y = 6a^3 - \frac{8b^2}{4c} + 11$
4. Logic:¶
and: Returns True if both statements are true
or: Returns True if one of the statements is true
not: Reverse the result, returns False if the result is true
True and True
True
True and False
False
# logic
(not True) or (not False)
True
True or True
True
x = 4
x < 5 and x < 10
True
x = 4
x < 5 or x < 4
True
x = 4
x < 5 and x < 4
False
not(x < 5 and x < 10)
False
Exercise 3 (6 points):¶
For each of the following expressions, guess whether they evaluate to True or False. Then type them to check your answers.
- 1<=1
- 1!=1
- 123 == '123'
- 1!=1 and 1<=1
- 1!=1 or 1<=1
- 'good' != 'bad'
5. Conditionals¶
Conditional statements are an essential part of programming in Python. They allow you to make decisions based on the values of variables or the result of comparisons.
Hint: In Python, indentation is MANDATORY. Blocks are closed by indentation level.
x = 100
if x > 0:
print('Positive Number')
elif x < 0:
print('Negative Number')
else:
print ('Zero!')
Positive Number
# Blocks are closed by indentation level
if x > 0:
print('Positive Number')
if x >= 100:
print('Huge number!')
Positive Number Huge number!
Exercise 4 (4 points):¶
Given a number x, print if it is an odd or even number.
6. Loop¶
A loop is an instruction that repeats multiple times as long as some condition is met.
while loop¶
# make a loop
count = 0
while count < 10:
# bad way
# count = count + 1
# better way
count += 1
print(count)
10
Hint: Be careful with the conditions. Avoid defining an infinite loop.
for loop¶
# use range
for i in range(5):
print(i)
0 1 2 3 4
# Reverse the order
for i in range(5,0,-1):
print(i)
5 4 3 2 1
Important point: in python, we always count from 0!
# what is range?
type(range)
type
range?
Init signature: range(self, /, *args, **kwargs) Docstring: range(stop) -> range object range(start, stop[, step]) -> range object Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When step is given, it specifies the increment (or decrement). Type: type Subclasses:
# iterate over a list we make up
for pet in ['dog', 'cat', 'fish']:
print(pet, len(pet))
dog 3 cat 3 fish 4
What is the thing in brackets? A list! Lists are one of the core python data structures.
Exercise 5 (5 points):¶
Create a loop from 100 to 1, if ood number, print 'odd' and the number, or print 'even' and the number.
7. Lists¶
l = ['dog', 'cat', 'fish']
type(l)
list
# list have lots of methods
l.sort()
l
['cat', 'dog', 'fish']
# we can convert a range to a list
r = list(range(5))
r
[0, 1, 2, 3, 4]
while r:
p = r.pop()
print('p:', p)
print('r:', r)
p: 4 r: [0, 1, 2, 3] p: 3 r: [0, 1, 2] p: 2 r: [0, 1] p: 1 r: [0] p: 0 r: []
There are many different ways to interact with lists. Exploring them is part of the fun of python.
list.append(x) Add an item to the end of the list. Equivalent to a[len(a):] = [x].
list.extend(L) Extend the list by appending all the items in the given list. Equivalent to a[len(a):] = L.
list.insert(i, x) Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
list.remove(x) Remove the first item from the list whose value is x. It is an error if there is no such item.
list.pop([i]) Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
list.clear() Remove all items from the list. Equivalent to del a[:].
list.index(x) Return the index in the list of the first item whose value is x. It is an error if there is no such item.
list.count(x) Return the number of times x appears in the list.
list.sort() Sort the items of the list in place.
list.reverse() Reverse the elements of the list in place.
list.copy() Return a shallow copy of the list. Equivalent to a[:].
Don't assume you know how list operations work!
# "add" two lists
x = list(range(5))
y = list(range(10,15))
z = x + y
z
[0, 1, 2, 3, 4, 10, 11, 12, 13, 14]
# access items from a list
print('first', z[0])
print('last', z[-1])
print('first 3', z[:3])
print('last 3', z[-3:])
print('middle, skipping every other item', z[5:10:2])
first 0 last 14 first 3 [0, 1, 2] last 3 [12, 13, 14] middle, skipping every other item [10, 12, 14]
MEMORIZE THIS SYNTAX! It is central to so much of python and often proves confusing for users coming from other languages.
In terms of set notation, python indexing is left inclusive, right exclusive. If you remember this, you will never go wrong.
# that means we get an error from the following
N = len(z)
z[N]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[39], line 3 1 # that means we get an error from the following 2 N = len(z) ----> 3 z[N] IndexError: list index out of range
# this index notation also applies to strings
name = 'Xiaomeng Jin'
print(name[:4])
Xiao
print(name[:-4])
Xiaomeng
print(name[-3:])
Jin
# you can also test for the presence of items in a list
5 in z
False
Lists are not meant for math! They don't have a datatype.
z[4] = 'fish'
z
[0, 1, 2, 3, 'fish', 10, 11, 12, 13, 14]
Python is full of tricks for iterating and working with lists
# a cool python trick: list comprehension
squares = [n**2 for n in range(5)]
squares
[0, 1, 4, 9, 16]
# iterate over two lists together uzing zip
for item1, item2 in zip(x,y):
print('first:', item1, 'second:', item2)
first: 0 second: 10 first: 1 second: 11 first: 2 second: 12 first: 3 second: 13 first: 4 second: 14
Exercise 6 (5 points):¶
Define a list from a range of values, check if an element exists in the list.
8. Assignment: Python Lists and Loops¶
In this problem, we will explore the basic data structures and flow controls of python by manually parsing a CSV file.
Note that this is a futile exercise. In the "real world" you should never manually parse a CSV file. There are utilities out there that will do it for you much more quickly and efficiently. However, it is a useful exercise for learning python.
Before starting the python part, use the JupyterLab file browser to browse to esa_roster_fall_2026.csv. Click to open it. What do you see?
Now we will begin the process of reading the file with python
8.1 Open the file using the open function (1 point)¶
Specifically, run the command
file = open('esa_roster_fall_2026.csv')
8.2 Use the help function to get the documentation for your new variable file (2 points)¶
This will produce a long list of methods you can use with file.
8.3 Read the lines of the file into a variable called lines (5 points)¶
It should be a familiar type we learned about in class.
8.4 Display lines at the end of a cell in order to see its contents (3 points)¶
8.5 Display the number of students in class (5 points)¶
8.6 Use slicing to display the first three items of the list (3 points). And the last 3 (3points)¶
8.7 Now iterate through lines and print the item if it contains your NetID. (iteration: 3 points; print: 3 points)¶
8.8 Split the file into two lists, and find the longest last name (6 points)¶
Build two lists, names and netids, so that names[k] and netids[k] belong to the same
student. Then use zip to print each NetID next to its name.
Now work out which student has the longest last name. The roster is written last name first, so take the first word of each name. Print the last name and how many characters it has.
Hints
- Every line still ends with a newline character. Before you write the loop, take a single line
and look at what
.strip()and.split(',')each do to it. - Do not use
max()orsorted(). Walk the list with a loop and keep track of the best one you have seen so far. - Before you accept your answer: are you certain there is only one?
8.9 Do the NetIDs follow the rule? (6 points)¶
A Rutgers NetID usually begins with the first letter of the student's first name. Write code that checks this for every student and prints the ones where it fails.
10. AI Usage Description (10 points)¶
Describe every use you made of an AI assistant while working on this notebook. Remember the policy at the top: error messages and debugging strategy only.
For each use, give three things:
| Where | The exact prompt you typed | What you did with the answer |
|---|---|---|
| Exercise 4 | "what does TypeError: not all arguments converted during string formatting mean?" |
It said I was mixing % on a string. I saw I had written x%2 where x was a string, and used int(x) instead. |
Fill in the cell below with your own table. Two rules:
- Quote the prompt exactly. Paraphrasing it defeats the purpose.
- If you did not use AI at all, write "I did not use AI on this assignment." That is worth full marks. These points are for an honest and complete account, not for using AI.