>>> print("Hello, World!")
Hello, World!
The famous "Hello World" program in Python.
age = 18 # age is of type int
name = "John" # name is now of type str
print(name)
Python can't declare a variable without assignment.
| Type | Description |
|---|---|
| str | Text |
| int, float, complex | Numeric |
| list, tuple, range | Sequence |
| dict | Mapping |
| set, frozenset | Set |
| bool | Boolean |
| bytes, bytearray, memoryview | Binary |
>>> msg = "Hello, World!"
>>> print(msg[7:9])
llo
mylist = []
mylist.append(1)
mylist.append(2)
for item in mylist:
print(item) # prints out 1,2
num = 200
if num > 0:
print("num is greater than 0")
else:
print("num is not greater than 0")
for item in range(5):
if item == 3: break
print(item)
else:
print("Finally finished!")
s = "Hello"
print(s.upper()) # 'HELLO'
print(s.lower()) # 'hello'
print(s.replace("l", "x")) # 'Hexxo'
print(s[1:4]) # 'ell'
a = 5
b = 2.5
print(a + b) # 7.5
print(a // 2) # 2 (floor division)
print(a ** 3) # 125 (power)
t = (1, 2, 3)
print(t[1]) # 2
print(t.count(2)) # 1
s = {1, 2, 3}
s.add(4)
print(s) # {1, 2, 3, 4}
d = {"a": 1, "b": 2}
print(d["a"]) # 1
d["c"] = 3
lst = [0, 1, 2, 3, 4]
print(lst[1:4]) # [1, 2, 3]
print(lst[-2:]) # [3, 4]
print(lst[::-1]) # [4, 3, 2, 1, 0]
squares = [x*x for x in range(5)] # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0]
x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
for i in range(3):
print(i)
for idx, val in enumerate(['a', 'b']):
print(idx, val)
while x > 0:
x -= 1