Up to now our programs have been rather "one-sided". We created variables, wrote instructions such as print, and let the computer carry these out from start to finish. Våra sköldpaddor har gått precis som vi sagt åt dem.

But usually programs do different things depending on what we tell them to do. We will talk more about that now.


Our programs can ask questions to the user by using a function called input.

The answer that the user enters can be stored in a variable to be used later the program. As always, give the variable a name that reflects the expected answer. Here is an example:

Note the small space after the question mark - that's just to give a bit of air between the question and what the user then enters.

Remember the datatypes!

It's not always easy to remember what year you were born. We can write a program to help us out with that::

age = input("How old are you? ")
current_year = 2022
birthyear = current_year - age
print(f"you were born in {birthyear}")

Wait a minute, we can't do this.

Python doesn't initially know what the user enters. It thinks every input is some kind of text, in other words a string. That means line 3 actually crashes when we try to compute a mix of different datatypes.

Since we know that the age is a number, an int, we can ask Python to convert the input to an input. The easiest way is to change the first line as follow.

age = int(input("How old are you? "))

Or, we can do the conversion on a different line

age = input("How old are you? ")
age = int(age)

If we forget to convert to an int we get an error message. In the next section we will get better at understanding them.

Variables may vary

We just saw this line of code: 

age = int(age)

The variable "age" had value type (a string) but is now replaced by a new value type (an int). A variable can change value, and even change what type of data it contains.  

Here is another example: 

a_number = 1
a_number = a_number + 1

The first print instruction will print "1". Afterwards, the variable a_number changes to a_number+1, which then is 1+1, or 2. The second print instruction will therefore print "2".

Read page in other languages

In this video, we use the input function and see how it can replace previously predetermined ("hardcoded") variables.

  • Interactive: A program that changes and adapts to what the user has entered or what buttons have been pushed.
  • I/O: I/O: Short for input/output. In Python we use the functions input and print.
  • Data type: What kind of data a variable contains. This can be, for example, an integer (5), a floating point number (2.3), a string (“Marcus”) or something else.
Difficulty level