Input and Output


Python.

This module will teach you about input, output, and variables in Python.

All challenges will require you to make your own python file with the .py extension. You can name these files whatever you want. In challenges when you see yourFile.py, replace that with the file you made! To run a python file: python yourFile.py.


Challenges

The first thing to learn when programming is how to print information to the screen, as a program is only useful if you can see its results. In Python to print to the screen, we will use the print() function (we will cover functions in more detail later).

Print Syntax:

Text that you want to print, must be in quotes. Later, we will show you how to print other things too!

print("STRING MESSAGE TO PRINT")

For example:

print("My Output!!")

When run this will display the following:

My Output!!

In addition to printing things to the screen, you sometimes need to add messages inside your code. This is called a comment. Comments can be useful to help explain Python code and make it more readable or to stop certain lines from executing.

Comment Syntax:

# This is a comment

Comments start with a #, this is vital because it tells Python to ignore what follows. Comments can be placed on their own line, or at the end of an existing lines.

For example:

# This is a greeting print statement
print("GREETINGS USER!") # Another Comment, do you think this is a good greeting?

Challenge:

Use python to print the text 'Hello World!' to the screen.

  1. Create a new file with the file extension .py
  2. Write the python code to print the text Hello World!
  3. Test your code with python yourFile.py
  4. Verify your solution with verify yourFile.py

Programming is so much more than printing things to the screen. We also need to learn how to store information and use it throughout the program: this can be accomplished with variables.

Variables allow us to store data in our programs, and use it to compute results! You can imagine a variable as a box that can hold a single value at a time. All variables need a name, this is how we can access them to store/process data.

Python makes using variables super simple, as it doesn't care about defining the type of the variable. That is to say, you give python what you want to store and it just handles it, whereas some languages require you to explicitly declare what type it is beforehand.

For the sake of this lesson we only care about Integers (whole numbers), Floats (decimal point numbers), and Strings (words/sentences). Here is how we declare each:

counter = 1000          # creates an integer numeric variable
total = 1024.67		    # creates a float numeric variable
name = "The Rizzler" 	# creates a string variable

Later we will learn how to use these variables throughout the program, but for now we are only concerned about declaring them correctly. The easiest way to verify that you created your variables correctly is to print them to the screen. Again, Python makes this super easy. We will use the same method (print()) we used in the Printing Text challenge, but pass the variables into it instead of hardcoding a string. This allows us to display the contents of our variables to the user.

Variable Syntax:

[VARIABLE_NAME] = [DATA_TO_STORE]

print([VARIABLE_NAME])

To print the variables declared above:

# Print each variable to the screen
print(counter)
print(total)
print(name)

Try printing out your variables, and verify that they are exactly the same as what you assigned them to in your program.

Challenge:

Use python to create 3 variables. They can have any name, and any data stored in them. Maybe try saving your name, age, and GPA! After creating and storing data in them, print them all out!

  1. Create a new file with the file extension .py
  2. Write python to create 3 variables and print them to the screen
  3. Test your solution with python yourFile.py
  4. Verify your solution with verify yourFile.py

Sometimes when we print, we want to include some more information instead of just the value stored in a variable. This can be accomplished in a couple different ways. The first way is simply adding multiple strings and variables together. A string of words needs to be wrapped in quotation marks "like this." Variables can be printed by just including the variable name. We need to use commas to separate each thing we want to print.

Using the name variable we defined in the previous challenge, we could print a message before we print the value of name by doing something like this:

print("Name is defined as", name)

When run, the program will output the following:

Name is defined as The Rizzler

This is rather straightforward, but can become messy quickly if printing multiple variables and messages. The other way we could accomplish this is by using a format string. This requires some different pieces: the variable placeholders {}, the .format() function call, and the variables to be printed. Each placeholder {} is where a value will be printed. The order of your variables matters here - the first variable will print where the first placeholder is in your string.

If we put it all together, we can create some interactive prints. Using variables we defined previously, let's build out a format string:

print("Hello {}, Your Total is: {}".format(name, total))

When running this code, we will get the following output:

Hello The Rizzler, Your Total is: 1024.67

Challenge:

Use python to create and print a variable with .format

  1. Create a new file with the file extension .py
  2. Create a python variable that contains a name
  3. Write the python code to print the text Hello, <name> where <name> is the name stored in a variable
# Example program output
Hello, Rizzler
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

Now that you understand variables, it is important to learn how to change them on the fly. This allows your program to be interactive, and can be accomplished by using user input.

Starting with what you already know, you should be able to understand what the following does:

name = "The Rizzler"
location = "Ohio"

print("Hello, my name is", name)
print("I am from", location)

If you run this program repeatedly, the same output would be displayed. But what happens if you want to use a different name? Or different location? You have to open the code, change the values for each variable, save and run. This doesn't sound too bad right now, but imagine the code base was thousands of lines of python - this would not be ideal.

Because of this, you need a way to assign different values from the user in runtime - while the program is running. This can be accomplished with the input() function. We've used the print() function before to display output to the user, this time input() will "read in" input from the user.

When the program encounters the input() function, it will wait for the user to enter data until the Enter key is pressed. The sequence of characters that the user typed then get stored in a string variable for further use. The program then proceeds to run any following lines of code.

name = input()
location = input()

print("Hello, my name is", name)
print("I am from", location)

Now the variables are not assigned a specific value until runtime. Every time this program is run different values can be inputed. So the program has become truly interactive.

You can copy the code above and see for yourself what the input() prompt looks like! You may notice that the program doesn't seem to be doing much of anything - until you type a word and hit Enter. This brings up a couple of questions...

How does the user know the program is waiting for input? The user will have no idea that the program is waiting for input. If they know what the program is supposed to be doing, it will probably be fine. But if they don't, it might appear as though the program is hanging or not responding. You can give the user some instructions by providing a text prompt. This could be as simple as a print statement before the input line or by passing a prompt string to the input function.

Both methods will effectively accomplish the same thing, but with one small difference. If the prompt is a separate print line before the input call, the program will display these on two separate lines. If you pass the prompt to the input function, the program will both display the prompt and get user input on the same line.

# separate lines
print("Enter your name:")
name = input()
  
# the same line
name = input("Enter your name: ")

Challenge:

Use python to read a user's name and tell them Hello

  1. Create a new file with the file extension .py
  2. Write python to accept a name from the user - make sure to give them a prompt!
  3. Print Hello, <name> where <name> is the value of your name variable
# Example Running of the program
python yourScript.py
What is your name: Greg
Hello, Greg
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py

Input is only stored in strings, but how do we do math on strings? For example, how would we add 7 to the user's age? With the knowledge we've gained so far, we may try something like this:

age = input("Enter your age: ")
future_age = age + 7
print("Age in the future", future_age)

Unfortunately, if you were to run the code above you would likely encouter a TypeError. This is because Python does not have the ability to do math on strings. So if you're expecting the user to input a numeric value, it will have to be converted from a group of characters into a number, which can then be used throughout the rest of the program. Thankfully, Python allows "type casting" and makes this process very easy. In the example above, we can most likely assume that age is an integer (a whole number) and the input we get from the user will need to be an integer. To convert age from the input string to an integer/numberical value, you can simply "cast" it to an integer using the int() function. The int() function takes a string variable, and gives you the integer value stored in that string.

age = input("Enter your age: ") # read in as a string
age = int(age) # type cast to an int
future age = age + 7 # do some math
print("Age in the future", future_age) # print updated value

A shorter way to type the same thing:

# read in as a string, then immediately cast to an int
age = int(input("Enter your age: ")) 
future_age = age + 7
print("Age in the future", future_age)

Python will let you type cast to other data types as well. The ones you should be concerned about are int(), float(), and str().

Challenge:

Use python to calculate a users age + 7

  1. Create a new file with the file extension .py
  2. Write python to accept an integer from user input that represents their age
  3. Write the python code to calculate their age in 7 years and prints the resulting number
# Example Running of the program
python yourScript.py
What is your age: 15
22
  1. Test your code with python yourFile.py
  2. Verify your solution with verify yourFile.py


30-Day Scoreboard:

This scoreboard reflects solves for challenges in this module after the module launched in this dojo.

Rank Hacker Badges Score
Loading.