Console
In Python 3 we use input and output methods. With print()
, which requires method syntax, we generate output. This is a simple, easy-to-maintain approach.
We can pass arguments to print()
to specify what values to print, and how to print them. With no argument, we print an empty line.
This program uses 3 calls to print()
. It uses one and then 2 arguments. When 2 arguments are used to print, a space is rendered in between the strings.
string
variable, but other values (like integers) and even objects can be printed.# Print a string literal. print("Hello") # Print two arguments. print("Hello", "there") # Print the value of a string variable. a = "Python" print(a)Hello Hello there Python
Here we read characters and strings (lines) from the console. When this program executes, it will pause and wait for a line input.
input()
method immediately returns this value.# Get input from console. s = input() print("You typed", s) # Use if-statement on input. if s == "a": print("Letter a detected") else: print("Not letter a")a You typed a Letter a detected
A console program can continually prompt the user until a quit command is received. This allows the same program to run many commands without restarting.
while-true
loop and break
if the user types a lowercase "q." The loop continues infinitely until a "q" is received.# Continue while true. while True: # Get input. value = input() # Break if user types q. if value == "q": break # Display value. print("You typed: ", value) # Exit message. print("You quit.")1 You typed: 1 2 You typed: 2 3 You typed: 3 q You quit.
The result of the input method is a string
. It can be converted to any other type. Here I convert the result to an integer with the int()
built-in operator.
print("Enter number:") # Get input and convert it to an integer. value = input() number1 = int(value) print("Again:") value = input() number2 = int(value) print("Product:") # Multiply the two numbers. print(number1 * number2)Enter number: 10 Again: 2 Product: 20
User input is often imperfect. It has errors. We can use the try and except statements to validate this input. The int()
method raises an error if the input is invalid.
string
argument to the input method).string
received into an integer. If the value is not numeric, int()
will raise an error. The loop will continue.while True: try: # Get input with prompt. code = input("Code: ") # Attempt to parse input. value = int(code) break; except: print("Invalid code") print("Value:", value)Code: g Invalid code Code: 89 Value: 89
We can use Python in interactive mode. This helps us learn about Python constructs. In interactive mode, we can call the "help" built-in with an argument.
dict
" which constructs a dictionary.>>>> help(dict) Help on class dict in module builtins: class dict(object) | dict() -> new empty dictionary. | dict(mapping) -> new dictionary initialized from a mapping object's | (key, value) pairs.
By default, print()
writes to the console. But we can change it to write to a file on the disk. We use the optional file argument.
open()
method.# Open this file for writing. f = open("C:\\profiles\\perls.txt", "w") # Print lines to the file. print("Some text", file=f) print("Some more text", file=f)Some text Some more text
Print has an optional "end" argument. This is set to a newline sequence by default, but you can override
it. We often set end as a named argument.
string
literal. So print renders no end.string
, we can use print multiple times on a single line.print()
with multiple arguments.# Change end argument to avoid newline. print("Hi, ", end="") print("how are you?")Hi, how are you?
The print method can be used with no arguments. In this case, it will simply output the "end" value. By default, the end is a newline.
print(100) # Use an empty print statement. print() print(200)100 200
All expressions are evaluated before being passed to the print()
method. Here, 1 + 2 is transformed to 3 before being passed to print.
override
this behavior, we need to construct a string
out of our numbers before passing anything to print.# This prints 3. print(1 + 2) # This prints the expression. print("1 + 2")3 1 + 2
Print does not support format strings. Instead we must pass the result of the str.format
method to the print method. This syntax is not short
, but it does make sense.
# Print formatted string. value = 10 print(str.format("There are {} apples", value))There are 10 apples
The __repr__ method on a class
determines how it is printed. On your custom objects, you can provide an implementation for repr. Formatting can be done in one location only.
With print()
and input()
, we can write data to the console, and accept input from the user's keyboard. Many simple programs are best implemented with text interfaces.