Python is a general-purpose, high-level programming language.It is used for a wide variety of applications, including web development, data science and machine learning.Here is Python cheatsheet for beginners.
full_name = "John Doe"
age = 25
married = False
age and Age are two different variables.snake_case format, so each word is separated by an underscore.str |
Text |
int, float, complex |
Numeric |
list, tuple, range |
Sequence |
dict |
Mapping |
set, frozenset |
Set |
bool |
Boolean |
bytes, bytearray, memoryview |
Binary |
None |
NoneType |
#single line comment.
""" Multiline comment
"""
''' Multiline comment 2
'''
Comments should be written in plain English (or the language of the code's audience) and follow standard conventions for spelling, grammar, and punctuation.
Code should be organized into logical blocks with descriptive names and headers. Comments can be used to introduce and summarize these blocks.
Comments can also be used to temporarily disable lines of code during testing or debugging. However, this should be used sparingly and documented clearly.
print("Hello, World!")
Hello, World!
print("Hello", "World!")
Hello World!
print(x, y) # you can use one or more variables
print("Hello", "World!", sep=", ")
Hello, World!
You can prevent the print() function from adding a newline character at the end using the end keyword argument.
print("Hello, World!", end=" ")
print("Hello, World!")
Hello, World! Hello, World!
You can format the output using string formatting techniques, such as f-strings, format strings, or the % operator.
name = "John"
age = 25
print(f"{name} is {age} years old.")
John is 25 years old.
You can redirect the output of the print() function to a file using the file keyword argument.
with open("output.txt", "w") as f:
print("Hello, World!", file=f)
string_1 = "string with double quotes"
string_2 = 'string with single quotes'
multi_string_1 = """Multiline Strings
can be written like this by
wrapping inside three double quotes"""
multi_string_2 = '''Multiline Strings
can be written like this by
wrapping inside three single quotes'''
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # John Doe
print("Hello " * 5) # Hello Hello Hello Hello Hello
name = "john Doe"
print(name.upper()) # JOHN DOE
print(name.lower()) # john doe
print(name.title()) # John Doe # Make the first letter in each word upper case:
print(name.strip()) # John Doe # remove leading and trailing whitespaces
print(name.replace("Doe", "Smith")) # John Smith
print(name.split(" ")) # ["John", "Doe"]
name = "John Doe"
print(name[0]) # J
print(name[1]) # o
print(name[-1]) # e
print(name[-2]) # o
name = "John Doe"
print(name[1:4]) # ohn
print(name[:4]) # John
print(name[5:]) # Doe
print(name[1:7:2]) # oh o
print(name[::-1]) # eoD nhoJ
name = "John"
age = 25
print(f"{name} is {age} years old.") # John is 25 years old.
print("{} is {} years old.".format(name, age)) # John is 25 years old.
print("%s is %d years old." % (name, age)) # John is 25 years old.
print("Hello\nWorld!") # Hello
# World!
print("Hello\tWorld!") # Hello World!
print("\"Hello World!\"") # "Hello World!"
print("Hello\\World!") # Hello\World!
name = "John"
print(name.encode("ascii")) # b'John'
print(name.encode("utf-8")) # b'John'
print(name.encode("utf-16")) # b'\xff\xfeJ\x00o\x00h\x00n\x00'
age = 25 # int
radius = 8.3 # float
rec = 8j # complex
age = 25
print(float(age)) # 25.0
print(complex(age)) # (25+0j)
x = 5
y = 3
print(x + y) # 8
x = 5
y = 3
print(x - y) # 2
x = 5
y = 3
print(x * y) # 15
x = 5
y = 3
print(x / y) # 1.6666666666666667
x = 5
y = 3
print(x % y) # 2
x = 5
y = 3
print(x ** y) # 125
x = 5
y = 3
print(x // y) # 1
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(25)) # 5.0
print(math.pow(2, 3)) # 8.0
print(math.floor(2.9)) # 2
print(math.ceil(2.1)) # 3
import random
print(random.randrange(1, 10)) # 7
print(random.random()) # 0.4283688941880216
print(random.choice([1, 2, 3, 4])) # 3
print(round(2.1)) # 2
print(round(2.9)) # 3
print(abs(-2.9)) # 2.9
print(complex(2, 3)) # (2+3j)
print(max([1, 2, 3, 4])) # 4
print(min([1, 2, 3, 4])) # 1
print(sum([1, 2, 3, 4])) # 10
x = True
y = False
x = ["apple", "banana", "cherry"]
y = ["apple", "banana", "cherry"]
z = x
print(x is z) # True
print(x is y) # False
print(x == y) # True
print(not True) # False
print(not False) # True
print(True and True) # True
print(True and False) # False
print(False and True) # False
print(False and False) # False
print(True or True) # True
print(True or False) # True
print(False or True) # True
print(False or False) # False
print(bool("Hello")) # True
print(bool(15)) # True
print(bool(["apple", "banana", "cherry"])) # True
print(bool(False)) # False
print(bool(None)) # False
print(bool(0)) # False 0 is always false
print(bool("")) # False empty string is always false
print(bool(())) # False empty tuple is always false
print(bool([])) # False empty list is always false
print(bool({})) # False empty dictionary is always false
fruits = ["apple", "banana", "cherry"]
fruits = list(("apple", "banana", "cherry"))
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[2]) # cherry
fruits = ["apple", "banana", "cherry"]
print(fruits[-1]) # cherry
print(fruits[-2]) # banana
print(fruits[-3]) # apple
fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(fruits[2:5]) # ['cherry', 'orange', 'kiwi']
print(fruits[:4]) # ['apple', 'banana', 'cherry', 'orange']
print(fruits[2:]) # ['cherry', 'orange', 'kiwi', 'melon', 'mango']
print(fruits[-4:-1]) # ['orange', 'kiwi', 'melon']
fruits = ["apple", "banana", "cherry"]
fruits[0] = "kiwi"
print(fruits) # ['kiwi', 'banana', 'cherry']
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
fruits = ["apple", "banana", "cherry"]
if "apple" in fruits:
print("Yes, 'apple' is in the fruits list")
fruits = ["apple", "banana", "cherry"]
print(len(fruits)) # 3
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits) # ['apple', 'banana', 'cherry', 'orange']
fruits = ["apple", "banana", "cherry"]
fruits.insert(1, "orange")
print(fruits) # ['apple', 'orange', 'banana', 'cherry']
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits) # ['apple', 'cherry']
fruits = ["apple", "banana", "cherry"]
del fruits[0]
print(fruits) # ['banana', 'cherry']
fruits = ["apple", "banana", "cherry"]
seperated_fruit = fruits.pop(1)
print(fruits) # ['apple', 'cherry']
print(seperated_fruit) # banana
fruits = ["apple", "banana", "cherry"]
del fruits
print(fruits) # NameError: name 'fruits' is not defined
fruits = ["apple", "banana", "cherry"]
fruits.clear()
print(fruits) # []
fruits = ["apple", "banana", "cherry"]
x = fruits.copy()
print(x) # ['apple', 'banana', 'cherry']
fruits = ["apple", "banana", "cherry"]
cars = ["Ford", "BMW", "Volvo"]
x = fruits + cars
print(x) # ['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']
fruits = ["apple", "banana", "cherry"]
cars = ["Ford", "BMW", "Volvo"]
fruits.extend(cars)
print(fruits) # ['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']
fruits = ["apple", "banana", "cherry", "mango", "cherry"]
x = fruits.count("cherry")
print(x) # 2
fruits = ["apple", "banana", "cherry", "mango", "cherry"]
x = fruits.index("cherry")
print(x) # 2
newlist = [expression for item in iterable if condition == True]
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist) # ['apple', 'banana', 'mango']
fruits = ["apple", "banana", "cherry"]
fruits.reverse()
print(fruits) # ['cherry', 'banana', 'apple']
fruits = ["apple", "banana", "cherry"]
fruits.sort()
print(fruits) # ['apple', 'banana', 'cherry']
fruits = ["apple", "banana", "cherry"]
fruits.sort(reverse = True)
print(fruits) # ['cherry', 'banana', 'apple']
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(key=myFunc)
print(cars) # ['VW', 'BMW', 'Ford', 'Mitsubishi']
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
print(cars) # ['BMW', 'Ford', 'Volvo']
A tuple is a collection which is ordered and unchangeable.
In Python tuples are written with round brackets.
Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created.
Tuples are used to store multiple items in a single variable. `
fruits = ("apple", "banana", "cherry")
print(fruits) # ('apple', 'banana', 'cherry')
fruits = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(fruits) # ('apple', 'banana', 'cherry')
fruits = ("apple", "banana", "cherry")
print(fruits[1]) # banana
fruits = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(fruits[2:5]) # ('cherry', 'orange', 'kiwi')
fruits = ("apple", "banana", "cherry")
print(fruits[-1]) # cherry
fruits = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(fruits[-4:-1]) # ('orange', 'kiwi', 'melon')
fruits = ("apple", "banana", "cherry")
print(len(fruits)) # 3
fruits = ("apple", "banana", "cherry")
if "apple" in fruits:
print("Yes, 'apple' is in the fruits tuple") # Yes, 'apple' is in the fruits tuple
fruits = ("apple", "banana", "cherry")
fruits[3] = "orange" # TypeError: 'tuple' object does not support item assignment
fruits = ("apple", "banana", "cherry","mango")
vegetables = ("carrots","tomato","potato")
mytuple = fruits + vegetables
print(mytuple) # ('apple', 'banana', 'cherry', 'mango', 'carrots', 'tomato', 'potato')
Sets cannot have two items with the same value.
A set is a collection which is unordered and unindexed.
In Python sets are written with curly brackets.
Sets are unordered, so you cannot be sure in which order the items will appear.
Sets are unchangeable, meaning that we cannot change the items after the set has been created.
Set items can be of any data type.
sets are mutable
fruits = {"apple", "banana", "cherry", "apple", "banana"}
print(fruits) # {'cherry', 'apple', 'banana'}
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
print(fruits) # {'cherry', 'apple', 'banana', 'orange'}
fruits = {"apple", "banana", "cherry"}
fruits.clear()
print(fruits) # set()
fruits = {"apple", "banana", "cherry"}
more_fruits = ["orange", "mango", "grapes"]
fruits.update(more_fruits)
print(fruits) # {'cherry', 'apple', 'banana', 'orange', 'mango', 'grapes'}
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits) # {'cherry', 'apple'}
fruits = {"apple", "banana", "cherry"}
del fruits
print(fruits) # NameError: name 'fruits' is not defined
fruits = {"apple", "banana", "cherry"}
fruits.pop()
print(fruits) # {'apple', 'banana'}
A dictionary is a collection of key-value pairs, where each key is unique and associated with a value.
Dictionaries are written with curly brackets, and have keys and values.
Dictionaries are unordered, so you cannot be sure in which order the items will appear.
Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.
Dictionaries cannot have two items with the same key.
Dictionaries can be of any data type (int, float, string, boolean, list, tuple, None, etc.).
Dictionaries are mutable
empty_dict = {}
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
book_ino = {"name": "limitless", "price": 1.54, "ISBN": "16161IJ"}
school_marks = dict(name="John", age=18, marks=90)
print(school_marks) # {'name': 'John', 'age': 18, 'marks': 90}
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
print(school_marks["maths"]) # 72
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
print(school_marks.get("maths")) # 72
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
school_marks["maths"] = 90
print(school_marks) # {'maths': 90, 'chemistry': 65, 'physics': 68}
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
for key, value in school_marks.items():
print(key) # maths chemistry physics
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
if "maths" in school_marks:
print("yes") # yes
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
print(len(school_marks)) # 3
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
school_marks["english"] = 70
print(school_marks) # {'maths': 72, 'chemistry': 65, 'physics': 68, 'english': 70}
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
maths = school_marks.pop("maths")
print(school_marks) # {'chemistry': 65, 'physics': 68}
print(maths) # 72
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
school_marks.popitem()
print(school_marks) # {'maths': 72, 'chemistry': 65}
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
del school_marks["maths"]
print(school_marks) # {'chemistry': 65, 'physics': 68}
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
del school_marks
print(school_marks) # NameError: name 'school_marks' is not defined
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
school_marks.clear()
print(school_marks) # {}
school_marks = {"maths": 72, "chemistry": 65, "physics": 68}
school_marks_copy = school_marks.copy()
print(school_marks_copy) # {'maths': 72, 'chemistry': 65, 'physics': 68}
school_marks = {
"student1": {
"name": "John",
"age": 18,
"marks": 90
},
"student2": {
"name": "Jane",
"age": 17,
"marks": 80
}
}
print(school_marks) # {'student1': {'name': 'John', 'age': 18, 'marks': 90}, 'student2': {'name': 'Jane', 'age': 17, 'marks': 80}}
x = 5
x += 3 # x = x + 3
x -= 3 # x = x - 3
x *= 3 # x = x * 3
x /= 3 # x = x / 3
x %= 3 # x = x % 3
x //= 3 # x = x // 3
x **= 3 # x = x ** 3
x = 5
y = 3
print(x == y) # False
print(x != y) # True
print(x > y) # True
print(x < y) # False
print(x >= y) # True
print(x <= y) # False
x = 5
print(x > 3 and x < 10) # True
print(x > 3 or x < 4) # True
print(not(x > 3 and x < 10)) # False
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
print(x is z) # True
print(x is y) # False
print(x == y) # True
print(x is not z) # False
print(x is not y) # True
x = ["apple", "banana"]
print("banana" in x) # True
print("pineapple" not in x) # True
x = 5
y = 3
print(x & y) # 1
print(x | y) # 7
print(x ^ y) # 6
print(x >> 2) # 1
print(x << 2) # 20
if condition:
# do something
else:
# do something else
if condition:
# do something
elif condition:
# do something else
else:
# do something else
if_true if condition else if_false
print("cheap") if price <50 else print("expensive")
if condition1:
if condition2:
# Code to execute if both condition1 and condition2 are True
else:
# Code to execute if condition1 is True and condition2 is False
else:
# Code to execute if condition1 is False
if_true if condition else if_false
print("cheap") if price <50 else print("expensive")
if condition1 and condition2 and condition3:
# do something
if condition1 or condition2 or condition3:
# do something
if condition1 and condition2 or condition3:
# do something
for i in range(10):
print(i)
i = 0
while i < 10:
print(i)
i += 1
for i in range(10):
for j in range(10):
print(i, j)
for i in range(10):
if i == 5:
break
print(i)
for i in range(10):
if i == 5:
continue
print(i)
for i in range(10):
print(i)
else:
print("Done")
for i in range(10):
if i == 5:
pass
print(i)
def my_function():
print("Hello from a function")
def my_function():
print("Hello from a function")
my_function()
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
x = lambda a : a + 10
print(x(5))
def my_function(x):
return 5 * x
print(my_function(3))
f = open("demofile.txt", "r")
print(f.read(5))
f = open("demofile.txt", "r")
print(f.readline())
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
f = open("demofile.txt", "r")
for x in f:
print(x)
f = open("demofile.txt", "r")
print(f.readline())
f.close()
f = open("demofile.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("demofile.txt", "r")
print(f.read())
f = open("myfile.txt", "x")
import os
os.remove("demofile.txt")
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
import os
os.rmdir("myfolder")
with open('workfile') as f:
read_data = f.read()
When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
There are several types of exceptions in Python. Common ones are:
full exception list (docs.python.org)
try:
print(x)
except:
print("An exception occurred")
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
with open("myfile.txt", "r", encoding='utf8') as file:
for line in file:
print(line)