Three built-in functions carry most of your first programs: print() to show output, input() to read what the user types, and the assignment operator that creates a variable. Each one behaves in a way that trips up beginners in the same predictable way. Get these three right and the rest of Python's syntax starts to look like what you already expected it to be.
The previous lesson in this module covered "Running Your First Python Program End to End", and the next lesson in this module is about "The Python REPL: A Practical Daily Workflow".
What does print() really do?
print() takes any number of objects, turns each one into text, joins them together with a separator, and writes the result to the standard output with a newline at the end. The default separator is a single space, and both the separator and the newline can be changed.
print('alpha', 'beta', 'gamma') # space separated, newline at the end
print('alpha', 'beta', 'gamma', sep=' | ') # custom separator
print('waiting...', end='') # no newline yet
print('done') # continues the same line
print() # just a newline
print('None prints as:', None)
print('print itself returns:', print('this inner call runs first'))
Two details in that output are worth pausing on. The last line shows you that print() returns None, so you cannot write message = print('hi') and expect to get text back. What you get instead is the absence of a value. And print happily prints None, which is how you notice that a function forgot to return anything at all.
Two keyword arguments earn their keep here. end lets you build output one piece at a time without a newline after each piece, and that is how progress messages are written. flush sends the text out immediately instead of leaving it in a buffer, which matters when the output is a log file or a live dashboard and somebody is waiting to see it.
Why does input() always hand you a string?
Because a keyboard gives you characters and not numbers. input() reads one line from the user, removes the trailing newline, and returns that line as a str. It does not guess whether you meant the text '30' or the number 30.
age = input('Age: ')
print('the value you typed is:', age)
print('its type is:', type(age).__name__)
try:
print(age + 1)
except TypeError as error:
print('adding 1 failed with:', error)
print('after conversion:', int(age) + 1)
That TypeError is the most common error in a beginner's first interactive program, and Python's message about it is unusually helpful. It tells you that you cannot add a str to an int. The fix is to write int(age). The bigger lesson underneath it is that converting the value is your job, because Python will not guess what a person meant.
One small but useful detail is that input() keeps the spaces at the start and the end of the line, so input().strip() is the normal first move when a value might have extra spaces in it. Later in the course you will meet a safer pattern that converts the value and checks it at the same time, so that a stray letter gives a friendly message instead of a traceback.
There is a second subtlety worth knowing about. input() reads a whole line, so if the user types 42 and presses Enter, you get the string '42'. If the user types nothing at all and presses Enter, you get the empty string, which is falsy. That is why if not value: is the usual way to catch an empty answer before you try to convert it.
What is a variable, really?
A Python variable is not a box with a fixed shape. It is a name bound to an object. The object holds the data, and the name is simply a label that you can move to a different object at any time. That one idea explains most of Python's surprising behaviour.
first = [1, 2, 3]
second = first
print('same object?', first is second)
second.append(4)
print('first ->', first)
print('second ->', second)
third = first.copy()
third.append(5)
print('after copying, first ->', first)
print('after copying, third ->', third)
Two names pointing at the same list means that the list has two references, so adding an item through either name changes what both names see. The copy() call breaks that link. And the last four lines show the other half of the story. Giving first a new value did not empty the old list. It simply attached the name to a different object, and the two lists are now genuinely separate.
Two results follow from all of this. Passing a list to a function and changing it inside that function also changes the list in the caller, because you passed a reference. And giving a list a second name does not copy it, so second = first and second = first.copy() are very different lines of code. If you are not sure, ask yourself whether you want the same object or a separate one.
How should you name things so other people can read them?
Names are the cheapest documentation in any language, and Python's conventions make them easy to get right.
- Use snake_case for variables and functions, such as
total_priceandread_file. This is the official style guide, and it matters because other Python developers read your code. - Use UPPER_SNAKE_CASE for constants that should not change, such as
MAX_RETRIES = 3. The convention only works if you respect it. - Never shadow a built-in. The line
list = [1, 2]breakslist()for the rest of the module, and the bug shows up far away from its cause. - A single leading underscore marks something that is internal, such as
_helper. Two leading underscores trigger name mangling inside classes. - Names are case-sensitive, so
totalandTotalare two different variables. That is a bug waiting to happen.
Python also lets you attach a type hint to a name or to a parameter. Hints are optional, and Python never checks them while the program runs, but they let editors and type checkers catch mistakes before you run anything.
MAX_RETRIES = 3
def greet(name: str, excited: bool = False) -> str:
suffix = '!' if excited else '.'
return 'Hello, ' + name + suffix
print(greet('Ada'))
print(greet('Ada', excited=True))
Python 3.8 and later also have the walrus operator :=, which assigns a value in the middle of an expression. It is handy once you are comfortable with normal assignment, but you do not need it yet.
Your turn: build a tip calculator
- Create a file called
tips.py. It asks for a bill amount and a tip percentage withinput(), converts both withfloat(), and prints the total with the tip included. - Run it and type a bill of
42.50and a tip of12. Your total should be 47.60. If it says "unsupported operand", then you forgot to convert one of the two inputs. - Add a line that prints the type of each converted value with
type(value).__name__. Also print the type of the raw input, so that you can see the change happen. - Now make it safe. Put the conversion inside a
tryblock, catchValueError, and print "Please type a number" instead of crashing when somebody types letters. - Finally, rename your variables to
bill_amountandtip_percent, and add atip_totalname for the tip itself. Read the file from the top to the bottom and ask whether a stranger could guess what each variable holds from its name alone.
Recap
print()joins its arguments with a space and ends with a newline. Usesepandendto change both.print()returnsNone, so never keep its result expecting text.input()always returns a string, and converting it is your responsibility.- A variable is a name bound to an object. Rebinding moves the name, and changing the object is visible through every name that points at it.
- Use snake_case, use UPPER_SNAKE_CASE for constants, and never shadow a built-in.