This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International LicenseIntro | Statements | Values | Expressions | Variables | Conditionals | Comments | Iteration | Functions | Input | Lists | Summary
Computation is the process of computing new values from old ones. That’s it. The values may be numbers or text or many other things, and a computer is given some values and asked to compute new ones. For example, it could be given your grades in your courses and asked to compute your GPA (grade point average). Or it could be given the prices of the items in your shopping cart and asked to compute the total including tax. Or it could be given the positions of pieces on a chess board and asked to compute the best move for one of the players.
You probably knew that. But did you know that until quite recently, a computer was someone that computes. That’s right. Computers were people who worked with (mostly) numerical values: counting votes, managing financial ledgers, solving scientific equations, etc. They often had mechanical devices such as old-fashioned adding machines or slide rules to help them, but the people were the ones who knew how to compute whatever it was they were computing.
Now, if you want to tell a human how to do something, first you need to know how to do it yourself. And then you need to be able to describe it to them in a language that they understand, using steps that they know how to do. If I want you to prepare a meal of spaghetti, first I need to know how to make spaghetti myself, and then I also need to be able to explain it to you in way that you understand and can follow. If I want you to compute a student’s GPA given their grades, first I need to know how to do it and then I need to tell you how to do it in a way that you understand and can do for yourself.
Of course, we’re not really interested in telling humans how to compute things. Since the mid-twentieth century, we have been able to build computing devices, which are what we will mean from now on when we talk about “computers.” But whether it’s a human computer or a computing device, before you can tell the computer how to do something, you need to know how to do it yourself. And then you need tell the computer what to do using a language that it understands, using steps that it knows how to do.
A program is a set of instructions for telling a computer (computing device) how to compute something. Programming is the act of creating a program. That is, it’s the process of creating a set of instructions that tell a computer how to compute something. Programs are written using a programming language that the computer understands.
Unfortunately, the programming languages that computers understand are not much like human languages. And the steps that computers know how to do by themselves are amazingly basic. Human toddlers can do more by themselves than the most powerful computer. But it’s what we have to work with.
There are many different programming languages, and programmers can be passionate about which is best. Leaving that question aside, we will be using the Python programming language for this tutorial.
This short tutorial is intended to teach you the basics of programming so that you can start to communicate with a computer and get it to do things for you. Think of it like learning how to say “please” and “thank you,” “how much does that cost?”, and “where is the bathroom?” in a different human language. It’s not much, but it’s a start, and it’s not that hard. We’ll look at getting the computer to do some very simple things. As you begin to understand what computers can do, you’ll be able to teach yourself how to get them to do it.
Programming is not Computer Science.
We just said that there are two aspects involved in getting a computer to do something. First you need to understand what the computer needs to do. Then you need to tell the computer what to do in a language that it understands. Programming is the second part. Computer Science is the science behind the first part.
Computer Science is the science of computing. Just like Physics is the science of how the physical world works, and Biology is the science of how the living world works, Computer Science is the science of how the computing world works.
When you study Physics, you learn the principles of the physical world. When you study Biology, you learn the principles of the living world. When you study Computer Science, you learn the principles of the computing world: how computers (computing devices) work, how different aspects of computers are related, how to compute things, how to compare different ways of computing things, and much more. You learn the principles of computing—the fundamental concepts and rules that govern computing. And you learn how to apply those principles to problems to create applications of the principles to specific problems (a.k.a. apps).
Programming is the way that you communicate your understanding of how to solve a problem to the computer so that it can (try to) do it for you. Computer Science provides the framework for understanding computational problems and their solutions. Although most topics in Computer Science involve programming, the programming is not really the point. Programming is how a Computer Scientist puts their ideas and principles into practice.
This short tutorial is about programming. We’ll work on simple problems where you should be able to figure out what the computer needs to do fairly easily. The challenge for now is learning how to “speak” using a programming language. If you go on to study Computer Science, you’ll learn the principles of computing and how to apply them to harder problems.
So let’s get started.
Like a human essay, speech, or conversation, a program is a sequence of statements. Each statement tells the listener something. In the case of a program, the programmer is telling the computer something.
The simplest statements are commands: “do something.”
What do you think the following statement will do? print(123)
Try it.
What are you telling Python to do? Print. What do you want it to print? 123. So this is a print statement.
You can also tell Python to print several things: print(1, 2, 3, 123)
You can give the print
command more than one thing to print, separated by commas, and it will print them all, separated by spaces, on the same line. Python then starts a new line for the next print statement.
That’s all we need to know about printing for now.
What do computers compute? They compute values.
Numbers are values and 123 is the written decimal representation of a number. So you can tell Python to print the number (the value) 123 like we just did.
You can also have numbers with fractional parts. Try these:
print(3.14159) print(0.001)The whole numbers are called integers and the numbers that can have fractional parts are called floats. Python keeps integers and floats separate, but you don’t usually have to worry too much about the differences between them.
Numbers aren’t everything. You can also have values that are text.
print("Hello world!")In programming, a sequence of characters is also called a string, as in a string of beads, a string of pearls, a string of horses, a string of hit songs, or a string of Christmas lights. So text values in programs are also called strings.
The doublequotes (") tell Python that you want to print literally the characters capital-h, e, l, l, o, space, w, o, r, l, d, exclamation point. So a sequence of characters in quotes is also called a string literal. It’s how you write a string value in your program, just like writing the digits 1 2 3 is how you write a numeric literal value. (In Python, you can also use single quotes to write string literals.)
Computers can compute new values from old ones. That’s what computing is all about.
For example, try this: print(1+2)
Instead of a numeric literal (a number) or a string, here we’re asking Python to print the value of an expression. Python computes the value of the expression, in this case the sum of 1 and 2, and gives that value to the print
statement to print.
Python understands lots of basic math: +
and -
, *
for multiplication, /
for division, parentheses for grouping, and more. For example:
print(1+2*3)
print((1+2)*3)
You can see that Python understands the standard order of operations (multiplication before addition) and has parentheses for when you want to specify some other order.
One cool thing is that +
also works with string values. What do you think this will print?
print("abc" + "def")
Try it.
You can use an expression whenever you have a formula for computing something, and then your program can compute the value for you.
Suppose that you want to know the area of two American football fields. Or two circles of radius 10. Using the answers to the previous exercises, you might write: print(100 * 50 + 100 * 50) print(3.14159 * 10 * 10 + 3.14159 * 10 * 10) Seems awkward. Easy to make a mistake cutting and pasting. Hard to read this program and understand what the expression is computing.
Wouldn’t it better to compute the area once, and then use it twice? Something like this: area = 100 * 50 print(area+area) area = 3.14159 * 10 * 10 print(2*area)
This is our second kind of statement: an assignment statement.
The name on the left of the equals sign is a name with which we want to associate with a value. This is called a variable because the associated value can vary (change).
The assignment statement tells Python to associate the value of the expression on the right with the variable on the left. In other words, make the value associated with the name be the value of the expression. This is called assigning a value to a variable.
Once you’ve done this, you can use the name of the variable in an
expression, and Python will substitute its current value, like in our print
statements.
Note that if you try to use the value of a variable before assigning it a value, you will get an error from Python: print(volume) ... NameError: name 'volume' is not defined So don’t do that.
You use variables to make your code clearer, not just to avoid cut and paste. The name of a variable tells a human reader the meaning of its value. It takes a bit of practice, but using variables and expressions is an important part of making your programs readable by humans (including yourself!).
One more thing about variables: In math, you usually have to “solve for” the values of variables. For example, you’re given one or more equations involving one or more variables, and the goal is to find the values of the variables that make the equation(s) true.
In programming, variables are just names for values. You can change the value associated with a name at any time using an assignment statement.
You can change the value assigned to a variable. For example: height = 3 print(height) height = 21 print(height)
You can also use the current value of the variable in the expression when you assign it a new value. For example: x = 1 print(x) x = x + 1 print(x)
In math, “x = x + 1
” does not make sense. In programming, it means use the current value of x
in the expression x+1
and assign the value of the expression back to x
. The value of x
after the first assignment statement is 1, so x+1
is 1+1 or 2. So the new value assigned to variable x
is 2, and that’s what gets printed.
You can do quite a lot of useful computing using only assignment and print statements with variables and expressions. But a program like that will always do the same thing. Sometimes you want your programs to do different things in different circumstances.
A conditional statement lets you tell the computer to test a condition in order to decide whether or not to do something. For example, here’s an if
statement:
The keyword if
is followed by an expression that must evaluate to either true or false. Python evaluates the expression and if the result is true, then it executes the indented statements following the colon (only one in this example). These are called the “then” clause of the statement, because if the condition is true, then the statements are executed.
If the condition is false, Python skips the indented statements and continues executing the program at the next non-indented line.
Or you can tell Python what to do if the condition is false:
if x > 0:
print(x, "is positive")
else:
print(x, "is negative or 0")
This is called an “else” clause for obvious reasons, and it is part of the if
statement.
Note the colons and the indentation. Very important in Python. Other programming languages do it differently, but they all have conditional statements of one kind or another.
You can give additional conditions to test using elif
:
if x > 0:
print(x, "is positive")
elif x < 0:
print(x, "is negative")
else:
print(x, "is 0")
You can have as many elif
clauses as you want. Whichever condition evaluates to true first, the indented statements following it are executed and the rest are skipped. If no condition evaluates to true, then the else
clause is executed (if there is one, otherwise nothing is executed).
You can also nest conditional statements. That is, the statements in the clauses of one conditional statement may themsleves be conditional statements. For example:
if x > 0:
if x > 100:
print(x, "is positive and large")
else:
print(x, "is positive and small")
else:
print(x, "is not positive")
Of course, you could have a nested conditional in the else
clause, and you could have elif
clauses for the inner conditional, and you could nest conditional statements as deeply as you want (although it gets quite hard to follow after a while).
There are many ways to specify a condition in Python. Here are a few of the most common:
==
y : True if value x is equal to value y. (Note: not single equals sign!)
!=
y : True if value x is not equal to value y.
<
y : True if value x is strictly less than value y.
<=
y : True if value x is less than or equal to value y.
>
y: True if value x is strictly greater than value y.
>=
y : True if value x is greater than or equal to value y.
These comparisons work for both numeric and string values, which is cool.
Conditions can also be combined to make more complicated conditions:
and
: The condition
“c1 and
c2” is true if both
c1 and c2 are true
or
: The condition
“c1 or
c2” is true if either
c1 is true or c2 is true (or both)
not
: The condition
“not
c” is true if
c is false, and is false if c is true
With conditional statements, your programs can do more than just compute new values from old values. Now they can make decisions.
n
whose value is the number of dogs at an animal rescue shelter. Use a conditional statement to print its value as either “n dog” (singular) or “n dogs” (plural), where n is the value of the variable. Test your code by assigning different values to the variable and running the program.
n
has value 0, the correct phrase is plural: “0 dogs.”
temp
whose value is the temperature of water measured during an experiment, in degrees Fahrenheit. Use a conditional statement to print whether or not the water is solid (ice), liquid, or gas. Test your code by assigning different values to temp
and running the program.
temp
is in degrees Celsius.
tempC
and tempF
, rather than having one variable whose value is sometimes degrees C and sometimes degrees F. But the question said not to change the conditional statement, and it uses temp
, so...
else
to handle any other values of size
, even if all you do is print an error message or “I don’t know.”
As your programs get bigger, it becomes harder to figure out what they’re doing. After all, they’re written in a strange language that is not any human’s native language. It is therefore helpful to include some comments, written in English (or any human language), to help future readers of the code.
In Python, comments are indicated by the hash symbol #
(also called a number sign or pound sign):
# This is a comment
A comment may be an entire line, like the one above, or added at the end of a line:
y = 1 + x + x * x # First three terms of Taylor series for 1/(1-x)
Python ignores any characters after a hash symbol until the end of the line. That’s right. Comments are ignored by Python. Python doesn’t understand English (or any human language) anyway.
But if you’re working as part of a team of programmers, comments allow you to explain your intent, what you’re trying to do, to other members of the team. Maybe your code is perfect, but it still might be hard for them to understand it. Or maybe it’s not working, and it would be good for them to know what you were trying to do with it so that they can work on fixing it.
And in fact, the future readers of your comments may well include you yourself! After a hard night of programming, when you return to work the next day, you may well not remember what it was you were trying to do. Or why you thought that a certain piece of code did the job. Comments in your code will give you the context that you need to understand it.
Comments are not a replacement for using meaningful variable names and breaking your programs into understandable chunks. But in combination with writing clear code, comments make programs self-documenting.
Challenge #1: Suppose I ask you print five asterisks, each on a line by themselves. What would you do? Try it yourself, then check my answer.
Not too hard. But what if I’d said one hundred asterisks? Or one thousand? Painful. You’ll probably do cut-and-paste and try to count in your head. What’s the chance of your getting it right and knowing that you got it right? Probably pretty low.
Challenge #2: Suppose I ask you to print the numbers from 1 to 5, each on a line by themselves. What would you do?
Also not too hard. But what if I’d said 1 to 100? Or 1000? Even more painful than before, right? Not only do you have to cut-and-paste many times, you also have to edit each line to print the appropriate value. You’re unlikely to get it right, and also it’s a lot of programming work for a really simple program.
One more challenge: Print the numbers from 1 to some other number that you don’t know until the program runs (that is, it’s stored in a variable). Don’t try too hard on this one before you check my answer.
We want to do the same thing, or almost the same thing, some number of times or until some condition is met. And in fact, doing something some number of times is equivalent to doing it until you have done it the required number of times.
This is called iteration, from the Latin iterum meaning “again.” There are several types of iteration statements. For example, here’s a while
statement:
row = 1
while row <= 5:
print("*")
row = row + 1
Try it (it solves challenge #1).
There’s the keyword while
, then a condition that can be either true or false, and then a sequence of one or more statements indented after the colon. These are called the body of the statement. A while
statement executes its body “while” the condition is true.
When Python executes a while
statement, it first tests the condition. If the condition is false, the body is skipped and execution continues with the next statement in the program. This is just like when an if
statement skips any clauses whose conditions are false.
But if the condition is true, the while
statement executes the statements in its body and then comes back to the start and tests the condition again. If the condition is true, the body is executed again, and so on, until the condition is false when it is tested.
Because the program may “loop back” and execute its body more than once, iteration statements are also called loops and a while
statement is also called a while
loop.
What about challenge #2: printing the numbers from 1 to 5? Instead of printing an asterisk, we’re supposed to print the number itself. Try it yourself using a while
loop, then check my answer.
It’s the same program, but now we’re printing the value of the variable row
each time around the loop.
The value of variable row
is 1 when Python first tests the condition. Yes, that’s less than or equal to 5, so Python executes the body of the statement. Those two statements tell Python to print the value 1, and then increment row
(to 2). Python loops back to the start and tests the condition again. Yes, the value of row
, now 2, is less than or equal to 5, so execute the body again. This time the print
statement prints 2, since that’s the value of row
, increments row
, and repeat for 3, 4, and 5.
The loop stops when row
gets incremented to 6, because then the condition row <= 5
is false. Python skips the loop body and continues at the next statement in the program. You can check the value of row
after the loop by printing it. Try it.
For challenge #3, let’s suppose that the limit for our printing is in some other variable, such as: limit = 5 Perhaps you computed it somewhere else, read it from a file, or got it from the user (we’ll see how to do that shortly).
How can you use a while
statement to print the numbers from 1 to that limit? Try it yourself, then look at my answer.
limit
being used in the loop condition rather than the numeric literal 5. So the loop limit is variable—it depends on the value of the variable limit
at the time the condition is tested.
Remember: conditions are just expressions whose value is either true or false.
Iteration statements can be nested just like conditional statements. And in fact, you can use a conditional statement in the body of an interation statement and vice-versa.
A while
loop, and iteration statements in general, allow you to perform repetition with variation. There are other forms of iteration statements in Python, but this is enough for for us for now.
The following exercises involve printing different patterns. For these, you may sometimes want to use multiple print
statements to build up a single line of output.
In Python, you can tell the print
command not to print a newline at the end by adding end=""
as the last thing to print. That is, tell print
to end the line with... nothing (an empty string containing no characters):
print(1, 2, 3, end="")
To end a line by printing only a newline, use a print
statement with no arguments, just empty parentheses:
print()
Now on to the exercises.
while
loop, write a program that prints 5 stars (asterisks) on a single line with no spaces between them, followed by a newline.
while
loops, one nested within the body of the other.
You could do this by copying and pasting your code for printing a row a stars five times and adjusting the limits of the loops. Don’t do that. Use only two nested while
loops.
while
loops.
size
would be a good name for it). Go ahead and do it.
while
loop that sums (adds up) the numbers from 1 to a given number. Test your program for several different limits.
total
, to keep a running total within the loop over the numbers from 1 to the limit.
# Add numbers from 1 to limit
limit = 5
total = 0
num = 1
while num <= limit:
total = total + num
num = num + 1
print("sum of numbers from 1 to", limit, "=", total)
This is a very common idiom (way of speaking/writing) in programs.
Suppose that we want to compute the sum of the numbers from 1 to 5, from 1 to 10, and from 1 to 100. We could copy the program from the previous section’s exercises three times and edit them each a tiny bit, but that’s going to be ugly and likely to result in errors. So we won’t do that.
Instead, let’s tell Python how to do the summing in such a way that we can easily get it to compute any such sum. def sum(limit): "Return the sum of the numbers from 1 to the given limit." num = 1 total = 0 while num <= limit: total = total + i num = num + 1 return total
The keyword def
tells Python that we are defining a new function. You probably know that in math, a function maps “input” input elements from its domain to “output” elements from its range. In programming, a function tells the computer how to compute the output values from the input values.
The name of the function follows def
, in this case we are defining a function named sum
. You should always use a name that clearly identifies what the function does. In this case, it computes a sum. Nice.
The inputs to the function are then listed in parentheses. In this example, we need to be given one value, the “limit” up to which we need to compute the sum. In the definition of a function, the inputs are called parameters (“a numerical or other measurable factor forming one of a set that defines a system or sets the conditions of its operation,” New Oxford American Dictionary). And then, in Python, a colon and the body of the function, its code, indented following the colon.
In this example, the string at the start of the body is called a doc string, short for documentation string. It is optional, but I strongly recommend that you always include one in any function that you write. Although Python will just skip over it, it explains your function to someone reading your code. And there are tools that can automatically generate documentation from docstrings, which is why they are better than comments for documenting functions.
Following the docstring is the main body of the function. And check it out: it’s the code from the last exercise of the previous section that computes the sum of the numbers from 1 to a given limit. In other words, we’re telling Python that that’s what to do if someone asks it to compute a sum.
The last statement tells Python to return
the value of the given expression, in this example the value of the variable total
, as the value of the function. A return
statement is often the last statement in a function, but it doesn’t have to be. But whenever it is executed (for example, in a conditional statement), the execution of the function terminates and the value of the given expression is returned as the value of the function.
Now, to use our new function, we call it. That is, we ask it to do its thing and give it whatever inputs it requires. For example: s = sum(5) print(s)
We use the name of the function and provide values, called arguments, one for each of the function’s parameters. In this example, the sum
function has one parameter, limit
, so we provide one value, 5. You can use any expression to provide the argument value(s). Python will evaluate the expressions to determine their values and then pass those values to the function.
Each time your program calls a function, Python treats each parameter like a variable, and sets its value to the corresponding argument. So in our example, the only parameter of the sum
function is limit
, so Python assigns the value of our only argument, 5, to the variable limit
.
Python then executes the body of the function until a return statement is executed (or the end of the body is reached). In our example, it will sum the numbers from 1 to the value of limit
(which is 5 in this example) using the variable total
and then return the value of that variable. In this example, the total is 15.
Try it. You can print the value of total
inside the loop in the body of the function if you want to watch what happens. Try that also.
After the function call returns, Python continues executing where it left off, and substitutes the return value of the function for the function call. In our example, it was computing the value of an expression in order to assign it to the variable s
. So it will assign 15 to s
, and then go on to print that.
A couple of quick things about functions:
print
function. There are many more builtin functions and functions in the Python standard library.
print
function, for example. A call to the print
function causes output to appear in the console, but it doesn’t actually return anything meaningful.
Here’s another example of a function that doesn’t return a value:
def printStars(n):
"Print the given number of stars (asterisks) on the same line."
i = 1
while i <= n:
print("*", end="")
i = i + 1
This function does what its docstring says. But, like print, it doesn’t return anything. BTW: You can read all the gory details of the print
function in its documentation.
In some programming languages, this would be called a procedure. In Python there are only functions, and in fact they always return something. But you would probably never use the value returned by a call to print
or printStars
in an expression.
limit
within the body of the function and it will print whatever was passed as the argument to sum
.
But try printing the value of limit
outside the body of the function, for example together with s
after the call to sum
. You will get an undefined name error.
In summary, functions are a very powerful way to structure your code. They allow code to be reused: used multiple times in different places in a program without cut-and-paste. More interestingly, you can think of functions as extending the Python language with new capabilities that you designed. Very cool.
What do you think the following program will do? x = input() if x == "xyzzy": print("you typed the magic word!") else: print("you typed", x, "; boring")
Perhaps you guessed this, but I should tell you that input()
is a call to the Python builtin function input
. It takes no arguments and it returns the next string that the user types, up to when they type Return. (That’s good enough for now.)
Try the program if you haven’t already.
Now you know how to get a string from the user. Your programs can now be interactive!
Let’s try input
with our conditional statement that tests for positive, negative, or zero:
x = input()
if x > 0:
print(x, "is positive")
elif x < 0:
print(x, "is negative")
else:
print(x, "is 0")
Oops. input
always gives you what the user typed as a string, but you need a number in order to compare it to the numeric value 0. (The first program worked because you were comparing two strings.)
Use float
instead of int
if you want a number with a fractional part (if any):
f = float(input())
And just for completeness, if you have a number (numeric value) and you want a string, Python provides the builtin function str
:
n = 1.5
s = "The value of n is " + str(n)
print(s)
input
so that the user knows that you’re waiting for them (and what they’re supposed to enter).
int
for yourself (give yours a different name).
s
is a variable whose value is a string, and expr
is an expression whose value is some number i, then len(s)
is the number of characters in the string, and s[expr]
is the i’th character in the string, starting with i=0.
Suppose that you are developing a program to analyze student grades. This requires, first, that you be able to store the grades in your program. And then second, that you know how to access them in order to analyze them. Python makes this quite easy.
If you know the grades at the time you’re writing the program, you can tell Python to create a list containing them and assign that to a variable: grades = [ 95, 72, 88, 75, 72, 80 ]
The square brackets, “[ ]
”, indicate a list. Python reads the comma-separated expressions between the brackets and creates a list containing their values.
In this example, the expressions are just numbers, but you can have lists of anything, and Python even allows you to have different types of things in one list. For example: things = [ 42, "Hello", -123.456 ]
You can also create an empty list: prices = [ ] And you can add items to the end of a list: prices.append(10.99) prices.append(7.50) print(prices) # Prints [10.99, 7.50]
The addition operator “+
” works with lists by combining them. It creates a new list containing the elements of the first list followed by the elements of the second list. For example:
evens = [ 0, 2, 4 ]
odds = [1, 3, 5 ]
print(evens + odds) # Prints [0, 2, 4, 1, 3, 5]
The Python builtin function len
gives you the length of the list (how many elements are in it):
print(len(grades))
Each element in a list has an index—its position in the list, starting at index 0. To access an element of a list, use its index as follows: print(grades[0]) # Prints 92 print(grades[3]) # Prints 75 Don’t get these square brackets confused with the square brackets used when you create a list (a list literal). They’re both about lists, but in this case we’re indexing into the list to get one of its elements.
You can use indexing to iterate over all the elements of a list (that is, to use an interation statement to access one element of the list after the other on each iteration):
i = 0
while i < len(grades):
g = grades[i]
print(g)
i = i + 1
Note that the loop condition uses “strictly less than” (<
) since the indexes start at 0, not 1, so the index of the last element in the list is one less than the length of the list.
It is so common to iterate through the elements of a list that Python provides a different kind of iteration statement for it, a for
statement:
for g in grades:
print(g)
This is easier to use, but only if you don’t need to know the index of the elements as you’re iterating over them.
The Python builtin function sorted
takes a list as argument and returns a new list with the same elements but sorted into their “natural” order:
print(sorted(grades)) # Prints [72, 72, 75, 80, 88, 95]
This leaves the original list unchanged. You may use the following to sort a list “in place”:
grades.sort()
They look quite similar, but print the list before and after the two different calls. You’ll see the difference.
This is enough to get you started with lists. The official Python Tutorial has An Introduction to Lists and More on Lists.
FYI: “The median of a set of numbers is the ‘middle’ number, when the numbers are listed in sorted order. If there is an even number of numbers, then there is no single middle value; the median is then usually defined to be the mean of the two middle values.” (Wikipedia)
int(n/2)*2 == n
. You can also use the “modulus” or “remainder” operator: n % 2
is the remainder when n is divided by 2 using integer division. And BTW: 0 is even.
list
is a list and i
and j
are indexes of elements in the list, then after calling
swap(list, i, j)
,
the element of the list previously at index i
will now be at index j
and vice-versa.
swap
function to sort a list “in place,” like the builtin function sort
? Think about it, then check out the hint.
sorted
(that is, a function that takes a list as argument and returns a new list with the same elements but in sorted order, say smallest to largest)? Think about it, then check out the hint.
FYI: You can insert an element into a list before a given index using
list.insert(index, element)
If the index is 0, the element is inserted at the start of the list. If the index is equal to len(list)
, the element is inserted at the end of the list (since len(list)
is one more than the index of the last item in the original list).
We have covered all the basics of programming. We have used the Python programming language, but all programming languages have similar elements. The details are different, but the concepts are the same.
print
to produce output
if
-elif
-else
while
and for
def
), parameters, calling, arguments, return
; builtin and library functions
input
Some of the many things that we didn’t cover:
But remember: it’s not easy to learn a new language.
The only way to learn a language is to immerse yourself in it. For learning French, that means going to Paris and hanging out and talking with people at cafes and art galleries. For learning programming, that means writing lots of programs, trying different versions of programs, and getting feedback on your programs from other more fluent programmers. And by the way, since most programming languages are quite similar, you’ll be able to learn other programming languages fairly easily.
But of course you still need to know what to say. You need to know how to solve your problem and then you need to break your solution down into steps that the computer knows how to perform. This tutorial has given you some idea of what those steps need to be and how to use them to solve simple problems. It will take some practice before you’re an expert problem solver and programmer, but you’re on your way.
Good luck!