Python Fundamentals
Comments
# a valid single line commment
# for multi line commment use:
"""
Three quotes. This also acts like multi line string
"""
print("Hello world") #after a valid statement
Variables
- No datatype
x=5
y='hello'
- Casting
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3)
- For the type of datatype, use:
x=6
print(type(x))
#output: <class 'int'>
- Many Values to Multiple Variables
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
#output:
Orange
Banana
Cherry
- Unpack a Collection
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
#output:
apple
banana
cherry
Datatypes
| Type | Keyword |
|---|---|
| Text Type: | str |
| Numeric Types: | int, float, complex |
| Sequence Types: | list, tuple, range |
| Mapping Type: | dict |
Set Types:set, |
frozenset |
| Boolean Type: | bool |
| Binary Types: | bytes, bytearray, memoryview |
| None Type: | NoneType |
Type Conversion
#convert from int to float:
x = float(1)
print(x)
print(type(x))
#output:
1.0
<class 'float'>
Random Number
Python does not have a random() function to make a random number, but Python has a built-in module called random that can be used to make random numbers:
import random
print(random.randrange(1, 10))
Strings are Arrays
a = "Hello, World!"
print(a[1])
#output: e
Looping Through a String
for x in "banana":
print(x)
#output:
b
a
n
a
n
a