Python Syntax
print("Hello World")
#This is a comment
Python Variables
Carname = "Volvo"
x = 50
x = 5
y = 10
print(x + y)
z = x + y
print(z)
Python Strings
x = "Hello World"
print(len(x))
txt = "Hello World"
txt[0]
txt = "Hello World"
txt[2:5]
txt = "Hello World"
x = txt.strip()
txt = "Hello World"
txt = txt.upper()
txt = "Hello World"
txt = txt.lower()
txt = "Hello World
txt = txt.replace("H", "J")
Python Operators
print(10 * 5)
print(10 / 2)
fruits = ["apple", "banana"]
if "apple" in fruits:
print("apple is in the fruits")
if 5 != 10:
print("5 is not equal to 10")
if 5 == 10 or 4 ==4:
print("At leat one of two statements is True")
Python Lists
fruits = ["apple", "banana", "cherry"]
print(fruits[1])
fruits = ["apple", "banana", "cherry"]
fruits[0] = "kiwi"
*append is to join or add on to the end of something
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
fruits = ["apple", "banana", "cherry"]
fruits.insert(1, "lemon")
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
Python Tuples
fruits = ("apple", "banana", "cherry")
print(fruits[0])
fruits = ("apple", "banana", "cherry")
print(len(fruits))
Python Sets
fruits = {"apple", "banana", "cherry"}
if ("apple" in fruits):
print("Apple is in the fruits set")
fruits = {"apple", "banana", "cherry"}
fruit.add("orange")
fruits = {"apple", "banana", "cherry"}
more_fruits = ["orange", "mango", "grapes"]
fruits.update(more_fruits)
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
fruits = {"apple", "banana", "cherry"}
fruits.discard("banana")
Python Dictionaries
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(car.get("model"))
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car["year"] = 2018
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car["color"] = "red"
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.pop("model")
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.clear()
Python If / Else
a = 50
b = 10
if a > b:
print("Hello World")
a = 50
b = 10
if a != b:
print("Hello World")
a = 50
b = 10
if a == b:
print("Yes")
else:
print("No")
a = 50
b = 10
if a == b:
print("1")
elif a>b:
print("2")
else:
print("3")
if a == b and c == d:
print("Hello")
if a == b or c == d:
print("Hello")
Python Loops
i = 6
while i < 6:
print (i)
i += 1
i = 1
while i < 6:
if i == 3:
break
i += 1
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
for x in range(6):
print(x)
Python Functions
def my_function():
print("Hello, this is a function")
def my_function():
print("Hello from a function")
my_function()
def my_function(fname, lname):
print(fname)
def my_function(x):
return x + 5
x = lambda a:a