A program becomes useful when it can listen. In this course you ask the user a question with input(), you learn why the answer is always text and how to turn it into a number, and you write small programs that ask, calculate and answer: a temperature converter, a tip calculator, a unit converter and a bill splitter. The practice checks your answers for you, and gives the program its answers, so you do not have to type them.
4 lessons, about 2 h 5 min4 simulations13 problems8 practice questionsPython in every lesson
The input() function shows a question, waits for the user to type an answer and press Enter, and gives back what was typed. The text in the brackets is the question. We keep the answer in a variable. On this site, the answers are typed in the Input box, one on each line, before you press Run, and each input() reads the next line. If the Input box has too few lines, the program stops with an EOFError.
input() always gives text, even when the user types digits, so adding two answers joins them: 3 and 4 give 34. To calculate, change the text into a number: int() for a whole number and float() for a number with a decimal point. str() changes a number into text so that it can be joined to other text. If the text cannot be a number, for example a word, or 3.5 for int(), Python stops with a ValueError.
A small program that asks has three parts: input, calculation and output. Plan them in words first. Ask with input() and change the answers to numbers, calculate with the formula, and show the answer in one clear line with print(). Use round() to keep the answer short. A good program tells the user what it asks for and what the answer means. Programs such as a temperature converter, a circle area and a tip calculator all follow the same plan.
In this project we write two programs that ask. A unit converter changes kilometres to miles and kilograms to pounds with fixed factors. A bill splitter divides a bill among friends with // and % to show what each pays and what is left over. We plan each program, write it in small steps, test it with numbers that we know the answers for, and then change it to make it our own.
Log in to join the discussion.
Loading…