Python Commands

Input and Output

input() Read a line
name = input()
print("Hi " + name)    # type Farhan → Hi Farhan
print() Show the result
print("Hello World")   # Hello World
print(5 + 3)           # 8

Converting Types

int() Text to whole number
age = int("12")
print(age + 1)         # 13
float() Text to decimal
price = float("2.5")
print(price * 2)       # 5.0

Maths

+ - * / Basic operators
print(7 + 3)           # 10
print(7 - 3)           # 4
print(7 * 3)           # 21
print(7 / 2)           # 3.5
// Whole-number division
print(7 // 2)          # 3
print(3 * 2 // 2)      # 3
+= *= /= Update a variable
score = 10
score += 5             # 15
score *= 2             # 30
score /= 3             # 10.0
print(score)

Comparisons and Logic

>= <= At least / at most
keys = 3
print(keys >= 2)       # True
print(keys <= 1)       # False
== Equal
print(5 == 5)          # True
print("AB" == "CD")    # False
and Both conditions true
start = 10
end = 11
print(start >= 9 and end <= 12)   # True
in Check if a character is in a string
print("+" in "+-*/")   # True
print("a" in "+-*/")   # False
True / False Booleans
is_open = True
print(is_open)         # True
print(not is_open)     # False

Strings

"#" + word Join strings
word = "coding"
print("#" + word)      # #coding
len() Count characters
print(len("hello"))    # 5
print(len("AB") == len("CD"))   # True
.title() Title case
print("hello world".title())   # Hello World
.split() Break a line into a list
loot = "Potion Gold Ruby".split()
print(loot)            # ['Potion', 'Gold', 'Ruby']

Lists

list[0] First item
loot = ["Potion", "Gold", "Ruby"]
print(loot[0])         # Potion
list[-1] Last item
loot = ["Potion", "Gold", "Ruby"]
print(loot[-1])        # Ruby
[] Empty list
bag = []
print(bag)             # []
.append() Add an item
bag = []
bag.append("Map")
bag.append("Sword")
print(bag)             # ['Map', 'Sword']
sum() Add up a list
numbers = [13, 2, -10]
print(sum(numbers))    # 5

Control Flow

if / elif / else Make decisions
keys = 1
if keys >= 2:
    print("Open")
elif keys == 1:
    print("Almost")    # Almost
else:
    print("Locked")
for ch in text Loop over characters
for ch in "abc":
    print(ch)          # a, b, c on separate lines

Optional

eval() Evaluate an expression string
print(eval("13+2-5*2"))   # 5