DMarlon Studio

Lesson 5 · 5 of 20

Reading from the keyboard · Python

Ask the user for data with input() in Python and convert it into numbers with int() and float() so you can do maths with it.

Python · Reading from the keyboard in DMarlon Studio: the example's code and its output in the terminal

input() prints the message you give it and waits for the user to type a line and press Enter. What they type is the result: name = input("What is your name? ") stores it in name.

In this example the answers come from the input.txt file (as if someone were typing them), so they do not appear in the output: you only see each question followed by the program's reply. In the DMarlon Studio console you can type them yourself.

input() always returns text, even if you type 29. To do maths you have to convert it: int() turns it into a whole number and float() into a number with decimals. int(input(...)) does both in one line: it reads and converts.

Once converted, the numbers work as usual: your age in 10 years, your height in centimetres ({height * 100:.0f}, no decimals) and the price of three cinema tickets with two decimals.

Code · main.py

# input() shows a message and waits for a line from the keyboard.name = input("What is your name? ")print(f"Nice to meet you, {name}!")# input() always returns text: convert it to do maths.age = int(input("How old are you? "))print(f"In 10 years you will be {age + 10}.")# float() converts text with a decimal point.height = float(input("How tall are you, in metres? "))print(f"That is {height * 100:.0f} centimetres.")# Two numbers for a quick bill.price = float(input("Price of a cinema ticket? "))tickets = int(input("How many tickets? "))print(f"{tickets} tickets cost {price * tickets:.2f} euros.")

Input (what gets typed) · input.txt

Lucia
29
1.68
8.50
3

Output · python3 main.py

What is your name? Nice to meet you, Lucia!
How old are you? In 10 years you will be 39.
How tall are you, in metres? That is 168 centimetres.
Price of a cinema ticket? How many tickets? 3 tickets cost 25.50 euros.

Key points

  • input("message") reads a line from the keyboard.
  • input() always returns a string.
  • int() and float() turn text into numbers.
  • If the text is not a number, the conversion fails (you will handle that later with try).

Exercise

Also ask for the film's name and end with a sentence such as «3 tickets for Dune cost 25.50 euros.». Add the answer to input.txt.