Module 1 · Getting Started · Lesson 2 of 40

Your Python toolkit

The few Python tools this course uses: variables, lists, loops, if, and functions.

In this lesson · about 20 minutes

  • Make variables and lists, and read items by index
  • Repeat work with for and while loops
  • Write a small function that returns an answer

You only need a small part of Python for this course. If you have never coded before, take this lesson slowly and run every example. If you know Python already, use it as a quick refresher.

Variables

A variable is a name for a value. age = 12 stores the number 12 under the name age.

Lists

A list holds many values in order: nums = [4, 8, 15]. Each item has a position number called an index. Python starts counting at 0, so nums[0] is 4 and nums[2] is 15. len(nums) tells you how many items there are.

Loops

A for loop repeats work for each item: for n in nums:. A while loop repeats while something is true: while count < 10:. The lines that repeat are indented (pushed right by 4 spaces).

Decisions

if, elif and else choose what to do: if n > 10: runs the indented lines only when n is bigger than 10.

Functions

A function is a named recipe you can reuse. You give it inputs and it returns an answer:

def double(x):
    return x * 2

double(5)   # gives 10

Try it: lists and loops

Run it. Then change the numbers in the list and run it again.

Exercise

Add up a list

Finish the function total(nums) so it returns the sum of all the numbers in the list. Use a loop (do not use the built-in sum).

Exercise

Find the biggest number

Write biggest(nums) that returns the largest number in a list that is not empty. Start by guessing the first item is the biggest, then check the rest.

Check your understanding0 of 4 correct

Question 1

1.nums = [7, 3, 9]. What is nums[1]?

Question 2

2.What does len([7, 3, 9]) give?

Question 3

3.What does a function's return line do?

Question 4

4.Which values does range(4) give?

Quiz score: 0 of 4

Exercises solved: 0 of 2

Tip: answer every quiz question correctly first.

Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.