DEV Community

Cover image for Python Basics
Erickson mugendi
Erickson mugendi

Posted on

Python Basics

Started Learning Python?

Variables: names for values

A variable is a name that points at a value. You create one with =, and Python reads the line from right to left: it works out the right side first, then attaches the name on the left.

If you have used a spreadsheet, you may expect a name to behave like a formula cell. It does not. Watch what happens to total:

quantity = 3
total = quantity * 55
quantity = 10
print(total)
Enter fullscreen mode Exit fullscreen mode
165
Enter fullscreen mode Exit fullscreen mode

Python worked out 3 * 55 when it reached that line and stored 165. Changing quantity afterwards does not reach back and redo the sum. To get 550 you run the total line again, after the change.

This is also why takings = takings + 660 makes sense. The right side runs first, using the old value, and the result takes the name.

takings = 0
takings = takings + 660
takings = takings + 600
print(takings)
takings += 100
print(takings)
Enter fullscreen mode Exit fullscreen mode
1260
1360
Enter fullscreen mode Exit fullscreen mode

The last two lines show +=, a shorthand for the same pattern.

Choosing names

A name can hold letters, digits and underscores. It cannot start with a digit or contain a space. Capitals count, so Bread and bread are two different names. The usual style is lowercase words joined by underscores, as in bread_sold.

Name a value for what it means, not for what type it is. bread_sold tells the next reader something. my_int tells them nothing. You read code far more often than you write it, so spend the extra few seconds.

Two ways a name goes wrong

The first is a typo:

bread_sold = 12
print(bread_sld)
Enter fullscreen mode Exit fullscreen mode

Traceback (most recent call last):
  File "shop.py", line 2, in <module>
    print(bread_sld)
          ^^^^^^^^^
NameError: name 'bread_sld' is not defined. Did you mean: 'bread_sold'?
Enter fullscreen mode Exit fullscreen mode

Read an error from the bottom. The last line says what went wrong, and the lines above say where.

The second is a name that starts with a digit:

1st_item = "bread"
Enter fullscreen mode Exit fullscreen mode

  File "shop.py", line 1
    1st_item = "bread"
    ^
SyntaxError: invalid decimal literal
Enter fullscreen mode Exit fullscreen mode

Python rejects this before the program runs at all, because the line is not valid Python.

Data types: what kind of value is it?

Every value has a data type, and the type decides what you can do with it. Four cover most of a beginner's needs, and the shop uses all of them:

loaves = 12
sugar_kg = 0.75
item = "bread"
in_stock = True
print(type(loaves), type(sugar_kg), type(item), type(in_stock))
Enter fullscreen mode Exit fullscreen mode
<class 'int'> <class 'float'> <class 'str'> <class 'bool'>
Enter fullscreen mode Exit fullscreen mode

An int is a whole number (loaves), a float has a decimal point (kilograms of sugar), a str is text (the item name) and a bool is True or False (is it in stock). The type() function tells you what Python thinks a value is.

Numbers

+, - and * do what you expect. / always gives a decimal, // divides and drops the remainder, % gives only the remainder, and ** raises to a power. Two conversions are worth seeing next to them:

print(int(9.99))
print(round(9.99))
print(7 / 2, 7 // 2, 7 % 2, 7 ** 2)
Enter fullscreen mode Exit fullscreen mode
9
10
3.5 3 1 49
Enter fullscreen mode Exit fullscreen mode

int(9.99) gives 9, because int() cuts off the decimal part and does not round. Use round() when you want 10.

Decimals have a catch of their own:

price = 1.1
print(price * 3)
print(round(price * 3, 2))
Enter fullscreen mode Exit fullscreen mode
3.3000000000000003
3.3
Enter fullscreen mode Exit fullscreen mode

Computers store decimals in binary, and some decimal fractions have no exact binary form, just as one third has no exact decimal form. The tiny error shows up when you print. Round for display. For real money, keep whole units (cents, not dollars) or use Python's decimal module.

Text

Text goes inside quotes, single or double. Pick one style and stay with it.

item = "  bread "
print(len(item))
print(item.strip().title())
print("-" * 20)
print("Sunrise" + " " + "Corner Shop")
Enter fullscreen mode Exit fullscreen mode
8
Bread
--------------------
Sunrise Corner Shop
Enter fullscreen mode Exit fullscreen mode

len() counts characters, including the spaces at both ends. strip() removes those spaces and title() capitalises each word, which matters in a moment, because people type items with stray spaces. Multiplying text repeats it, so "-" * 20 draws a line on a receipt. A + between two strings joins them.

Mixing types

Python will not add text to a number:

loaves = "5"
print(loaves + 5)
Enter fullscreen mode Exit fullscreen mode

Traceback (most recent call last):
  File "shop.py", line 2, in <module>
    print(loaves + 5)
          ~~~~~~~^~~
TypeError: can only concatenate str (not "int") to str
Enter fullscreen mode Exit fullscreen mode

The refusal has a reason. A + between text means "join", and a + between numbers means "add". With one of each, Python cannot tell which you want, so it stops. You choose by converting one side:

loaves = "5"
print(int(loaves) + 5)
print(loaves + str(5))
Enter fullscreen mode Exit fullscreen mode
10
55
Enter fullscreen mode Exit fullscreen mode

int("5") + 5 adds and gives 10. "5" + str(5) joins and gives the text 55. The converters are int(), float() and str().

True and False

A comparison produces a boolean. Combine booleans with and (both true), or (at least one true) and not (flip it):

loaves = 4
is_weekend = True
low_stock = loaves < 5
print(low_stock and is_weekend)
print(low_stock or is_weekend)
print(not low_stock)
Enter fullscreen mode Exit fullscreen mode
True
True
False
Enter fullscreen mode Exit fullscreen mode

Other types turn into booleans too, and one result surprises people:

print(bool("False"), bool(""), bool(0), bool(12))
Enter fullscreen mode Exit fullscreen mode
True False False True
Enter fullscreen mode Exit fullscreen mode

Any text with something in it counts as true, even the text "False". Empty text and zero count as false.

Input and output: talking to the program

print() accepts any number of values and puts a space between them. The sep option changes that separator. An f-string, a string that starts with f, lets you put values inside {}. A format after a colon controls how the value looks: <10 pads to ten characters, left-aligned, and >8.2f right-aligns in eight characters with two decimals.

item = "bread"
price = 55.0
print("Item:", item, "Price:", price)
print("Item:", item, "Price:", price, sep=" | ")
print(f"{item:<10}{price:>8.2f}")
print(f"{item:<10}{price * 3:>8.2f}")
Enter fullscreen mode Exit fullscreen mode
Item: bread Price: 55.0
Item: | bread | Price: | 55.0
bread        55.00
bread       165.00
Enter fullscreen mode Exit fullscreen mode

The last two lines show how receipt columns line up.

input() shows a prompt, waits, and returns what the person typed. It always returns text, even when they typed a number:

quantity = input("How many loaves? ")
print(type(quantity))
print(quantity * 2)
Enter fullscreen mode Exit fullscreen mode

How many loaves? 3
<class 'str'>
33
Enter fullscreen mode Exit fullscreen mode

Nothing crashed, and the answer is wrong. "3" * 2 repeats the text, so the result is 33, not 6. A program that fails loudly is easier to fix than one that quietly gives a wrong answer. Convert as soon as the value arrives: quantity = int(input("How many loaves? ")).

Basic syntax: the rules that hold it together

Python has few syntax rules and enforces them strictly. Four come up in nearly every program.

Blocks and indentation

Python marks a block of code by indenting it, usually four spaces. A line that ends in a colon (if, elif, else) opens a block, and the indented lines under it belong to that block.

takings = 1260
target = 1500
if takings >= target:
    print("Target reached")
elif takings >= 0.8 * target:
    print("Close to target")
else:
    print("Below target")
Enter fullscreen mode Exit fullscreen mode
Close to target
Enter fullscreen mode Exit fullscreen mode

Python checks the conditions from the top. 1260 >= 1500 is false. 1260 >= 0.8 * 1500 is 1260 >= 1200, which is true, so it prints "Close to target" and skips the else. Only the first matching branch runs.

Forget the indentation and Python stops:

bread_sold = 12
if bread_sold > 10:
print("busy day")
Enter fullscreen mode Exit fullscreen mode

  File "shop.py", line 3
    print("busy day")
    ^
IndentationError: expected an indented block after 'if' statement on line 2
Enter fullscreen mode Exit fullscreen mode

One equals sign or two

= stores a value. == compares two values. Mixing them up in a condition is a common slip:

total = 120
if total = 100:
    print("hit")
Enter fullscreen mode Exit fullscreen mode
 File "shop.py", line 2
    if total = 100:
       ^^^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
Enter fullscreen mode Exit fullscreen mode

Capitals count

Every built-in function is lowercase, and Python treats Print as a different name from print:

Print("hello")
Enter fullscreen mode Exit fullscreen mode
Traceback (most recent call last):
  File "shop.py", line 1, in <module>
    Print("hello")
    ^^^^^
NameError: name 'Print' is not defined. Did you mean: 'print'?
Enter fullscreen mode Exit fullscreen mode

Comments

A # makes Python ignore the rest of the line. Use comments to say why the code does something.

Top comments (0)