The ability to get input from the user allows us to make our programs interactive i.e. they can respond to what the user enters. When we get input from the user we must store it somewhere. This means whenever we request input we must provide a variable which will be assigned the value input. The basic input command can be seen below.
name = input("Enter your name: ")
In the above line of code, name is the variable that will be assigned the input and "Enter your name: " is the prompt that will appear to the user so they know what to enter.
The syntax rules for the basic input statement are:
By default all input is of string data type. to store something as an integer or real/float we must cast it. This can be done over two lines or in one line as seen below. When we use 1 line we are in escence passing the entire input statement as the parameter to our int or float command.
num = input("Enter a whole number") num = int(num) OR num = int(input("Enter a whole number: ")) |
num = input("Enter a decimal number") num = float(num) OR num = float(input("Enter a whole number: ")) |
You can convert a string to UPPERCASE, lowercase or Sentence Case using the methods below.
Case to convert to | Description | Method |
lowercase | Converts all text to lowercase | .lower() |
uppercase | Converts all text to uppercase | .upper() |
title case | First letter of each word capitalised, the rest lowercase | .title() |
By converting on input, you can save yourself the problem of having to check for different cases the user might have entered e.g.
guess = input(“What is the capital of England? ”).lower()
Regardless of how the user typed their response it will be stored as lowercase, meaning we only have to check for 1 possibly correct response. Otherwise they may have entered - London, LONDON or london. We will be looking at how to check answers soon when we cover selection.
Copy the lines below into a Python editor of your choice. Each line has a one or more syntax errors. Fix them one by one so they get the desired input and store it in the named variable.
name = input("Enter your name: ") #input is assigned to a variable |
age = int(input("Enter your age in years: ")) #print now in lowercase |
colour = input("What is your favourite colour? ") #suitable variable named - you don't store stuff in input |
height = float(input("Enter your height in meters: ")) #final missing bracket added |
score = int(input("Input your score: ")) #it is int-input not input-int |
surname = input("Enter your surname: ").upper() #added the .upper command to convert to upper case |
film = input("What is your favourite film? ").title() #added the .title command to convert to title case |
© All materials created by and copyright S.Goff