A5 - Input and Variables
In your u1 folder, create a Python file called a5.py.
Paste in the following code, and try it out:
first_name = input("What is your first name? ")
last_name = input("What is your last name? ")
print("Hello there", first_name, last_name, "- have a great day!")
This short program contains two variables: first_name and last_name.
A variable is a symbol that represents a stored value in the computer.
There are two rules to follow when choosing names for variables:
- Only letters, numbers, and the
_(underscore) character are allowed - The variable name is not allowed to start with a number
There are also some variable naming conventions in Python that you should follow, even though your program will still work if you ignore them:
- Choose variable names that are descriptive of the data you are representing
- Avoid capital letters, as they traditionally denote special meaning that we will see later
- Since spaces are not permitted, use underscores to separate multiple words such as
first_name
The above program also introduces the input function, which collects information from the user. For example,
Finally, we see a slightly new usage of the print function. For example,
If you provide the print function with multiple arguments, it will print all of them in a single line, each separated by a space.
Notice that we quote strings that we want to print verbatim, and leave variable names unquoted when we want to print the values they're storing.
Creating a Madlib
In the next task, you will create a Madlib in Python. If you don't know a Madlib is, have a look at this website Here is a sample for you to try.:
name = input("Enter a name: ")
animal = input("Enter an animal: ")
colour = input("Enter a colour: ")
noun = input("Enter a noun: ")
print(name, "had a little", animal)
print("whose fleece was", colour, "as", noun+ ".") # (1)!
- Notice after
nounI used a+rather than a comma. This is one way to avoid having Python insert a space between the noun and the period following it.