Python basics, part 1 of 6
Python First Steps
This page takes you from nothing to small working programs: running Python, printing, storing values in variables, working with numbers and making decisions with if. It is a Python 3 rewrite of the opening Pythofrank lessons from February 2017. The number and if-else examples are the original ones, updated from Python 2.7. The rest is written fresh.
Getting started
Group 1 of 4 · running Python and showing output
Before writing programs you need to know what Python is, how to start it and how to make it show something on the screen.
- What Python is: the language and where it is used
- Running Python: interactive mode and script files
- Showing output with print: values, separators and f-strings
- Comments: notes for the person reading the code
What Python is
Python is a general purpose programming language, first released by Guido van Rossum in 1991. Its code reads close to plain English, which makes it a common first language.
Python is interpreted: a program called the interpreter reads your code and runs it directly, so there is no separate compile step. It is also dynamically typed: you do not declare the type of a variable, Python works it out from the value.
| Where it is used | Examples |
|---|---|
| Web back ends | Django, Flask, FastAPI |
| Data analysis and machine learning | pandas, NumPy, scikit-learn, PyTorch |
| Automation and scripting | renaming files, calling APIs, scheduled jobs |
| Testing and tooling | pytest, command line tools |
| Teaching | schools, universities, coding interviews |
Version: this site uses Python 3. Python 2, which the 2017 lessons were written for, reached its end of life in 2020 and should not be used for new code.
Running Python
First check that Python is installed. Open a terminal and ask for the version. On macOS and Linux the command is usually python3. On Windows it is often python or py.
If the command is not found, install Python from python.org and try again.
Interactive mode
Type python3 on its own to start interactive mode. The >>> prompt waits for one statement, runs it and shows the result straight away. It is the quickest way to try an idea.
A script file
For anything you want to keep, save the code in a file ending in .py and pass the file name to Python. The file is run from the first line to the last.
Difference: interactive mode shows the value of any expression you type. A script shows nothing unless you call print().
Showing output with print
print() writes values to the screen. Give it several values separated by commas and it puts one space between them and a new line at the end.
Concept: a string with f before the opening quote is an f-string. Python replaces each {...} inside it with the value of the expression. :.2f means two digits after the decimal point.
Comments
A comment is a note for people. Python ignores everything from # to the end of the line. Use comments to say why the code does something, not to repeat what it plainly does.
Building blocks
Group 2 of 4 · the rules every Python file follows
These chapters cover how values are named, how they come in from the keyboard and how Python expects code to be laid out.
- Variables and names: giving a value a name
- Input and type conversion: reading text and turning it into numbers
- Indentation: spaces that are part of the syntax
- Quotation: single, double and triple quotes
- Statements and lines: long statements and short ones
Variables and names
A variable is a name that points to a value. It is created the moment you assign to it with =. There is nothing to declare first, and the same name can later point to a value of another type.
Naming rules
| Rule | Fine | Not allowed |
|---|---|---|
| Letters, digits and underscore only | account_no | account-no, account no |
| Cannot start with a digit | account2 | 2account |
| Cannot be a keyword | class_name | class, if, for, return |
| Upper and lower case differ | balance and Balance are two separate names | |
Convention: write variable names in lower case with underscores between words (opening_balance), and values that never change in capitals (MIN_BALANCE = 1000). Choose names that say what the value means.
Input and type conversion
input() shows a prompt, waits for the user to type a line and press Enter, and returns what was typed. This block waits for the keyboard, so it is not run by the site's checker.
input() always returns a string, which is Python's type for text. To do arithmetic you must convert it. int(), float() and str() make a new value of that type.
Remember: a conversion that cannot work raises a ValueError. The try and except used here to catch it are explained in Python Errors and Files.
Indentation
Many languages mark a block of code with braces. Python uses indentation, the spaces at the start of a line. A line ending in a colon opens a block, and every line indented under it belongs to that block.
Wrong indentation is not a style problem, it is an error. Python refuses to start this file, which is why the block is not run here.
Convention: use 4 spaces for each level and never mix tabs with spaces. Most editors insert 4 spaces when you press Tab in a .py file.
Quotation
Text goes between quotes. Single and double quotes mean exactly the same thing, so pick the one that does not appear in your text. Three quotes in a row start a string that may run over several lines.
Concept: a triple quoted string keeps its line breaks. The same form, placed as the first statement of a function or file, is used as its documentation.
Statements and lines
Normally one line holds one statement. A statement that is too long can continue on the next line in two ways: inside any open bracket, or after a backslash at the very end of the line.
The opposite is also possible. A semicolon separates several statements on one line.
Advice: prefer brackets to the backslash, because a single space after a backslash breaks it. Keep one statement per line in real code. The semicolon form is shown so you can read it, not so you write it.
Numbers
Group 3 of 4 · number types and arithmetic
These chapters follow the 2017 Numbers lesson. The same values are used, with the results Python 3 gives.
- Number types: int, float and complex
- Arithmetic: the operators, including
//,%and** - Floats and complex numbers: arithmetic that is not exact
- Converting numbers: from one number type to another
- The math module: square roots, rounding and constants
Number types
Python has three built-in number types. An int is a whole number. A float has a decimal point. A complex number has a real part and an imaginary part, written with j. type() tells you which one a value is.
Python 2: the old lesson also had a long type, written 256L. Python 3 has no long. Every whole number is an int of unlimited size, and 256L is a syntax error.
Arithmetic
The usual operators work as in school maths. Three need a closer look: // divides and rounds down to a whole number, % gives the remainder, and ** raises to a power.
Multiplication and division are done before addition and subtraction, and ** before all of them. Brackets change the order. An operator followed by = updates a variable in place.
Python 2: in the 2017 lesson 4 / 5 gave 0, because dividing two whole numbers threw the fraction away. In Python 3 / always gives a float. Use // when you want the whole number.
Floats and complex numbers
The same operators work on floats. A float is stored in binary with a fixed number of digits, so some decimal values cannot be held exactly and a tiny error can show up at the end.
Complex numbers support +, -, *, / and **.
Money: never compare floats with == after arithmetic, and do not keep money in a float. Store whole paise or cents in an int, or use Decimal from the decimal module. Python 2: the old lesson used % on complex numbers. Python 3 removed that and raises a TypeError.
Converting numbers
Calling a type like a function makes a new number of that type. int() cuts off the fraction. round() goes to the nearest value instead.
Surprise: round(4.5) is 4, not 5. Python rounds an exact half to the nearest even number, which keeps long sums from drifting upwards.
The math module
A module is a file of ready made code. import math loads the standard maths module, and its functions are then used as math.name. A few number functions are built in and need no import.
Decisions
Group 4 of 4 · running code only when a condition holds
A program becomes useful when it can choose what to do. These chapters follow the 2017 If else lesson and then add the pieces it left out.
- if and else: one of two paths
- elif: one of several paths
- Comparison and logical operators: building conditions
- Truthiness: values that count as true or false
- The conditional expression: a choice on one line
if and else
if checks a condition. When it is true the indented block under it runs. When it is false the block under else runs instead. The else part is optional.
Careful: = stores a value, == compares two values. Writing if a = 10: is a syntax error.
elif
elif is short for "else if". Python checks the conditions from the top and runs the block of the first one that is true. The rest are skipped, even if they are true as well.
An if can sit inside another if. Each level is indented by 4 more spaces.
Order matters: put the most specific condition first. If amount > balance came after a wider check that is also true, it would never be reached.
Comparison and logical operators
A comparison gives True or False, the two values of the bool type. Logical operators join comparisons into larger conditions.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | equal to | 5 == 5.0 | True |
!= | not equal to | 5 != 3 | True |
< > | less than, greater than | 3 > 10 | False |
<= >= | less or equal, greater or equal | 5 <= 5 | True |
and | true when both sides are true | 5 > 3 and 5 > 9 | False |
or | true when at least one side is true | 5 > 3 or 5 > 9 | True |
not | turns true into false and back | not 5 > 3 | False |
in | is inside a collection or string | "kesh" in "Rishikesh" | True |
and and or stop as soon as the answer is known. This is called short circuiting, and it lets the first check protect the second one.
Precedence: not is applied first, then and, then or. When a condition mixes them, add brackets so nobody has to remember that.
Truthiness
The condition after if does not have to be a comparison. Any value can be used, and Python treats it as true or false. Zero, empty collections, the empty string and None count as false. Everything else counts as true.
Concept: None is Python's value for "nothing here". Test for it with is None or is not None, not with ==.
The conditional expression
When an if and else only choose between two values, the choice fits on one line: value_if_true if condition else value_if_false.
Advice: use this form for a short choice between two values. If either side needs more than a simple expression, the normal if block is easier to read.
Quick reference
| You want to | Write |
|---|---|
| Check the version | python3 --version |
| Run a file | python3 hello.py |
| Show values | print("Balance:", balance) |
| Put values into text | f"{owner} has {balance:.2f}" |
| Write a comment | # why this line exists |
| Store a value | balance = 5000 |
| Read from the keyboard | amount = int(input("Amount: ")) |
| Convert a type | int("42"), float("9.5"), str(42) |
| Divide | 7 / 2 is 3.5, 7 // 2 is 3, 7 % 2 is 1 |
| Raise to a power | 2 ** 10 |
| Round | round(3.14159, 2), math.floor(x), math.ceil(x) |
| Choose one of several paths | if ...: elif ...: else: |
| Join conditions | and, or, not |
| Choose between two values | "low" if balance < 1000 else "ok" |
What changed since Python 2
| Python 2.7 (2017 lessons) | Python 3 (this page) |
|---|---|
print a, b | print(a, b) |
4 / 5 is 0 | 4 / 5 is 0.8, 4 // 5 is 0 |
256L is a long | only int, of any size |
raw_input() returns text | input() returns text |
<type 'int'> | <class 'int'> |
The 2017 originals are still online: Numbers and If else.
Next, learn how Python stores text and collections of values in Python Data Types.