Script, Input & Output
Until now, weβve been interacting directly in Pythonβs interpreter. We can keep using it from time to time to test some specific code but as of now, we will program in the text editor and only then execute it in the interpreter.
Script
We are going to create a script that calculates the perimeter and the area of a rectangle based on its length and width.
- Open Thonny.
- Write the below code in the script window (above the interpreter).
- Save your file and name it
rectangle.py
. -
Go to the tab
Run
and click onRun current script
The below result should appear in the interpreter:
It does not show an error, everything worked well.
Question
Why do we not see any result? Should we not see the value of the perimeter and the area of the rectangle?
Answer
As of the moment we use scripts, if we want to communicate with the user and show results on the screen, we need to use an output function: print()
.
Output
The print()
function prints whatever is written between the parenthesis to the screen. Let's improve our previous script so we can show to the user the results of our calculations.
-
Update your code:
π Python Scriptlength = 5 width = 3 perimeter = 2 * width + 2 * length area = width * length print(area, perimeter)
Info
No need to rewrite everything, just add
print
at the beginning of row 5. -
Go to the tab
Run
and click onRun current script
.The below result should appear in the interpreter:
-
Let's add some text in our
print
so the message is clearer.
length = 5
width = 3
perimeter = 2 * width + 2 * length
area = width * length
print("Area:", area, "Perimeter:", perimeter)
Very nice, you can now easily share information with the user.
Question
What if we want the user to choose the length and width of the rectangle?
Answer
If we want the user to communicate with the computer and give some information, we need to use an input function: input()
Input
The function input()
will allow our script to ask a question to the user. It will interrupt the execution of the program and wait for the input from the user. Then you can save the given answer in a variable and reuse it later on.
input()
accepts one optional parameter: the message that will be shown to the user.
The type of data returned by this function will always be a string. If you want to receive a float or an integer from the user, you have to specify it.
Example
Let's improve our previous script by asking the width and length to the user.
-
Update your code:
π Python Scriptlength = float(input("Give me a length: ")) width = float(input("Give me a width: ")) perimeter = 2 * width + 2 * length area = width * length print("Area:", area, "Perimeter:", perimeter)
Info
No need to rewrite everything, just add the input on the right side of the assignation
=
for length and width. -
Go to the tab
Run
and click onRun current script
.The below result should appear in the interpreter: