Basics: literals, variables, strings
Comments, numbers, strings, variables and program structure.
All lessons · Python lessons: learn from scratch
Values and types
Every piece of data a program uses has a type. Whole numbers are int, decimals are float, text is str, and true/false is bool. The type() function reveals the type of a value.
print(type(15)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("Baku")) # <class 'str'>
print(type(10 > 3)) # <class 'bool'>A dot is the decimal separator: 2.5. To make large numbers readable you may add underscores: 1_000_000.
Variables and naming
A variable is a name given to a value. The = sign does not mean “equals”; it means “store the value on the right under the name on the left”. You can assign a different value to the same name later.
city = "Ganja" population = 335000 print(city, population) population = population + 5000 print(population) # 340000
- A name starts with a letter or _, never a digit.
- Case matters: Age is not age.
- Keywords (if, for, class…) cannot be used as names.
- Pick meaningful names: price, not pr.
Strings
Text is written in single, double or triple quotes. Triple quotes are for multi-line text. You can join strings with + and repeat them with *.
line = "-" * 12
print(line)
print("Nibras" + " " + "Code")
note = """First line
Second line"""
print(note)The easiest way to put variables inside text is an f-string: write f before the quote and put the variable in {}. A form like {x:.2f} shows a number with two decimals.
item = "tea"
price = 1.5
qty = 4
print(f"{qty} x {item} = {price * qty:.2f} AZN")Strings are immutable: you cannot change part of one in place, you create a new string. Useful tools: upper(), lower(), strip(), replace(), split(), len().
s = " Hello, World "
print(s.strip().lower()) # hello, world
print(s.replace("World", "Python"))
print("a,b,c".split(",")) # ['a', 'b', 'c']
print(len("salam")) # 5