Python 101Free
FOUNDATIONS

Input and Output

Talking to the user with print and input, and how a script actually runs.

SECTION 01

print and input basics

print writes its arguments to standard output, separated by spaces, ending with a newline. The sep argument changes the separator and end changes the trailing character. Pass several arguments and Python handles spacing between them automatically.

input is the reverse. It blocks until the user types something and presses enter, then returns whatever they typed as a string. The optional argument is a prompt that gets printed first.

The most common surprise is that input always returns a string, even when the user types digits. If you want a number, you have to convert it: int(input("age? ")). Forgetting this conversion is a classic source of TypeError later in the code.

python
print("hi", "there", sep="-", end="!\n")
# hi-there!

age = int(input("age? "))   # cast right away; input is always str
SECTION 02

REPL and script execution

Python ships with two ways to run code. The REPL (read, eval, print, loop) is an interactive prompt that runs each line as you type it and shows the result. It is the fastest way to try things out, inspect a value, or remember how a method behaves.

A script is a .py file. Python runs it top to bottom, executing each statement once. There is no main function in the C sense, the file itself is the entry point.

The if __name__ == "__main__": guard at the bottom of a script is convention. It marks code that should run when the file is invoked directly, but not when the file is imported as a module from somewhere else. Most beginners do not need this until they start splitting code across multiple files.

python
def main():
    print("running as a script")

if __name__ == "__main__":
    main()
← PREVIOUS
Strings