Python - Basics

Hello World!

print("Hello World!")

Syntax and Comments

Multi-Line Statements

x = 2 + \
    3 + \
    4
print(x)

Multiple Statements on a Single Line

x = 4; y = 5; print(x + y)

Comments starts with a #

print("Hello World!") # This is a comment

Multiline comments starts with a triple-quoted string (''') or (""")

'''This is a multiline comment.
comment
comment
'''
print("Hello World!")

Variables

Variable names are case-sensitive and need to have a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_).

y = 5.4
z = 3e18
x = 'hey'
X = 34
x = 4
y = 2 + 3j  # complex number
print(x + y)  # (6+3j)

Data Type Casting

x = str(3)
y = int(3.56)
z = float(34)

for example:

Function Description Example
int(x [,base]) Converts x to an integer. x = int("20")

y = int('101',2)
float(x) Converts x to a floating-point number. x = float("43")
complex(real [,imag]) Converts x to a complex number. x = complex("43+5j")
str(x) Converts x to a string. x = str(1520)
tuple(x) Converts x to a tuple. x = tuple([1, 2, 3])
list(x) Converts x to a list. x = list((1, 2, 3))
set(x) Converts x to a set. x = set((1, 2, 3))
dict(x) Creates a dictionary. x must be a sequence of (key,value) tuples. x = dict([(4, 3)])

Assigning multiple values to multiple variables

x, y, z = 1, 2, 3
print(x)
print(y)
print(z)

Assigning One Value to Multiple Variables

x = y = z = 1
print(x)
print(y)
print(z)

Built-in Data Types

Category Types
Text str
Numeric int, float, complex
Sequence list, tuple, range
Mapping dict
Set set, frozenset
Boolean bool
Binary bytes, bytearray, memoryview

Getting Variables Types

x = "test"
print(type(x)) # <class 'str'>

Operators

Arithmetic Operators

Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y

Arithmetic Assignment Operators

Operator Example
= x = 2
+= x += 3
-= x -= 5
*= x *= 1
/= x /= 6
%= x %= 4
**= x **= 8
//= x //= 3

Bitwise Operators

Operator Name Example
& AND x & y
| OR x | y
^ XOR x ^ y
~ NOT ~ x
<< Left shift x << (Number)
>> Right shift x >> (Number)

Bitwise Assignment Operators

Operator Example
&= x &= 2
|= x |= 2
^= x ^= 7
>>= x >>= 8
<<= x <<= 1

Comparison Operators

Operator Example
== x == y
!= x != y
> x > y
< x < y
>= x >= y
<= x <= y

Logical Operators

Operator Example
and x == 1 and x > y
or x < 3 or x = 2
not not(x < 3 or x = 2)

Identity Operators

Use to check if variables are the same object

Operator Example
is x is y
is not x is not y

Membership Operators

Use to check if a sequence is presented in an object

Operator Example
in x in y
not in x not in y

Strings

Assign String to a Variable

x = "Text"

Assign a multiline string to a variable

a = """brohelp.me 
string string
string."""

Access characters in a string

Square brackets can be used to access elements of the string.

a = "str"
a[2] = 3
print(a[1:-1])

Looping Through a String

a = "str"
for x in a:
    print(x)

Unicode String

print(u'Hello, world!')
print(u'מה קורה')

String Length

a = "test"
print(len(a))

Check if phrase in string

txt = "test be brohelp"
if "be" in txt:
    print("yes")
elif "be" not in txt:
    print("no")

Convert a String to Uppercase

txt = "test"
print(txt.upper())

Convert a String to Lowercase

txt = "TEST"
print(txt.lower())

Remove white space from the beginning or end of a string

txt = " TEST "
print(txt.strip())

Removes all leading whitespace in string

txt = "  test "
print(txt.lstrip())

Removes all trailing whitespace of string

txt = "  test "
print(txt.rstrip())

Capitalizes first letter

txt = "test"
print(txt.capitalize())

Inverts case for all letters in string

txt = "tEsT"
print(txt.swapcase())

Splits string

str = "123 456"
print(str.split(" ",))

Replace substring

a = "Hello bro"
print(a.replace("llo", "haha "))

Concatenation of Two or More Strings

Use the + operator to join strings together

a = "Hello"
b = "bro"
print(a + " " + b)

String Format

y = 3
txt = "{} + {} = {}"
print(txt.format(x, y, x + y))

Escape Characters

Character Description
\n Newline
\t Tab
\' Single Quote
\\ Backslash

Example

print("Hey\nBye")

Substring first occurrence

The find() method returns -1 if the value is not found.

x = txt.find("l")
print(x)

Substring appears in the string

count (value, start, end) - returns the number of times a substring appears in the string.

string = "hahaha bye"
x = string.count("ha")
print(x)

Lists

List is an ordered sequence of items.

Declaring a Lists

x = [1,"ddd"]
print(x)
x = list((1,"ddd"))
print(x)
x = 40*[0]

Updating Lists

x = [1, "ddd", 2, 3, 4, 5, 6, 7, 8]
x[2] = 9
print(x)
x[3:5] = [1, 1]
print(x)

Negative indexing

The index of -1 refers to the last item and so on.

x = [1, "ddd", 2, 3, 4, 5, 6, 7, 8]
x[-2] = 9
print(x)

Slice List

you can access a range of items in a list by using the slicing operator :.

x = [1, "ddd", 2, 3, 4, 5, 6, 7, 8]
print(x[1:4])

Add Elements

append adds its argument as a single element to the end of a list. The length of the list itself will increase by one.

x = [1, "ddd", 2, 3, 4, 5, 6, 7, 8]
x.append(3)

extend iterates over its argument adding each element to the list. The length of the list will increase by The number of elements you add.

x = [1, "ddd", 2, 3, 4, 5, 6, 7, 8]
x.extend([1, 2, 3])

Inserts an item at the specified index.

x = [1, "ddd", 2, 3, 4, 5, 6, 7, 8]
x.insert(1,"r")

Remove Element

To remove a specified element.

x = ["1", "2", "3"]
x.remove("2")

To remove the specified index.

x = [1, "ddd", 2, 3, 4, 5, 6, 7, 8]
x.pop(2)

To removes and returns element by specified index.

x = [1, "ddd", 2, 3, 4, 5, 6, 7, 8]
y = x.pop(2)
x.pop()

removes and returns element by specified index. also can delete the list completely.

x = [1, "ddd", 2, 3, 4, 5, 6, 7, 8]
del x[1]
print(x)
del x

To empties the list. The list still remains, but it has no content.

x = [1, "ddd", 2, 3, 4, 5, 6, 7, 8]
x.clear()
print(x)

Check if Element Exists

x = ["1", "2", "3"]
if "1" in x:
  print("Yes")

List Length

x = ["1", "2", "3"]
print(len(x))

Get max value in a List

x = ["1", "2", "3"]
print(max(x))

Get min value in a List

x = ["1", "2", "3"]
print(min(x))

Loop Through a List

By Index

x = ["1", "2", "3"]
for i in range(len(x)):
    print(x[i])

By Iterable

x = ["1", "2", "3"]
for number in x:
    print(number)

Sort List Alphanumerically

Ascending

x = ["5", "3", "2", "6", "1"]
x.sort()
print(x)

Descending

x = ["5", "3", "2", "6", "1"]
x.sort(reverse=True)
print(x)

Customize Sort Function

x = [1, 2, 3, -6, 3, -8]
x.sort(key=lambda x: abs(x))
print(x)

Another example

def myfunc(x):
    return x.lower()

x = ["a", "d", "c", "B"]
x.sort(key=myfunc)
print(x)

Reverse list order

x = ["1", "2", "3"]
x.reverse()
print(x)

Copy a List

You cannot use list2 = list1, because: list2 will only be a reference to list1.

x = ["a", "b", "c"]
newlist1 = x.copy()
print(newlist1)
newlist2 = list(x)
print(newlist2)

Combine Lists

using the + operator.

x = ["1", "2", "3"]
y = ["4", "5", "6"]
z = x + y
print(z)

Count Element in List

count() method returns the number of elements with the specified value.

x = ["1", "2", "3", "1"]
print(x.count("1"))

Tuples

A tuple is a collection which is ordered and unchangeable.

Declaring a Tuple

x = ("a",) # To write a tuple containing a single value you have to include a comma,
y = (1, 2, 3, 4, 5, 6)
x = ("a", "b") * 40

Access Tuple Element

X = ("A", "B", "C")
print(X[1])
print(X[-1])
print(X[1:])
print(X[0:-1])

Check if Element Exists

x = ("1", "2", "3")
if "1" in x:
  print("Yes")

Tuple Length

x = ("1", "2", "3")
print(len(x))

Loop Through a Tuple

By Index

x = ("a", "b", "c")
for i in range(len(x)):
    print(x[i])

By Iterable

x = ("a", "b", "c")
for y in x:
    print(y)

Combine Tuples

using the + operator.

x = ("1", "2", "3")
y = ("4", "5", "6")
z = x + y
print(z)

Count Element in Tuple

count() method returns the number of elements with the specified value.

x = ("1", "2", "3", "1")
print(x.count("1"))

Find Element index in Tuple

x = ("1", "2", "3", "1")
print(x.index("3"))

Get max value in a Tuple

x = ("1", "2", "3")
print(max(x))

Get min value in a Tuple

x = ("1", "2", "3")
print(min(x))

Sets

Set is an unordered, unchangeable and unindexed.Also collection of unique elements.

Declaring a Set

x = {"1", "2", "3"}
y = {1, 2, 3}
print(x)

Set Length

x = {"1", "2", "3"}
print(len(x))

Loop Through a Set

x = {"a", "b", "c"}
for i in x:
    print(i)

Check if Element Exists in a Set

x = {"1", "2", "3"}
if "1" in x:
    print("Yes")

Add Elements to a Set

x = {"a", "b", "c"}
x.add("d")
x.add((1, 2, 3))
print(x)

Add Any Iterable

x = {"a", "b", "c"}
y = [1, 2, 3]
x.update(y)
print(x)

Remove Set Elements

remove() method - If the element to remove does not exist, remove() method will raise an error.

x = {"a", "b", "c"}
x.remove("b")
print(x)

discard() method - If the element to remove does not exist, discard() method will not raise an error.

x = {"a", "b", "c"}
x.discard("b")
print(x)

pop() method - will remove the last element in the set.

x = {"a", "b", "c"}
x.pop()
print(x)

clear() method - empties the set

x = {"a", "b", "c"}
x.clear()
print(x)

Join Sets methods

update() method - inserts all the elements from one set into another.

x = {"a", "b", "c"}
y = {"1", "3", "c"}
x.update(y)
print(x)

union() method - returns a new set with all elements from both sets.

x = {"a", "b", "c"}
y = {"1", "3", "c"}
z = x.union(y)
print(z)

intersection() method - Return a set that contains the elements that exist in both set.

x = {"a", "b", "c"}
y = {"1", "3", "c"}
z = x.intersection(y)
print(z)

intersection_update() method - Keep the elements that exist in both sets.

x = {"a", "b", "c"}
y = {"1", "3", "c"}
x.intersection_update(y)
print(x)

symmetric_difference() method - Return a set that contains all elements from both sets.

x = {"a", "b", "c"}
y = {"1", "3", "c"}
z = x.symmetric_difference(y)
print(z)

symmetric_difference_update() method - Keep the elements that are not present in both sets.

x = {"a", "b", "c"}
y = {"1", "3", "c"}
x.symmetric_difference_update(y)
print(x)

Compare Sets methods

isdisjoint() method - return true if no elements in set x is present in set y.

x = {"a", "b", "c"}
y = [1, 2, 3]
z = x.isdisjoint(y)
print(z)

issubset() method - Return true if all elements in set x are present in set y.

x = {"a", "b", "c"}
y = [1, 2, 3]
z = x.issubset(y)
print(z)

issuperset() method - Return true if all elements set y are present in set x.

x = {"a", "b", "c"}
y = [1, 2, 3]
z = x.issuperset(y)
print(z)

Dictionaries

Dictionary is an ordered collection of key-value pairs.

Declaring a Dictionary

x = {
    "a": "1",
    "b": (2,),
    "c": 3
}
print(x)

Access Dictionary Element

x = {
    "a": "1",
    "b": (2,),
    "c": 3
}
print(x["a"])

Dictionary Length

x = {
    "a": "1",
    "b": (2,),
    "c": 3
}
print(len(x))

Get all Keys in Dictionary

x = {
    "a": "1",
    "b": (2,),
    "c": 3
}
z = x.keys()
for i in z:
    print(i)

Get all Values in Dictionary

x = {
    "a": "1",
    "b": (2,),
    "c": 3
}
z = x.values()
for i in z:
    print(i)

Get all key:value pairs in Dictionary

x = {
    "a": "1",
    "b": (2,),
    "c": 3
}
z = x.items()
for i in z:
    print(i)

Check if Key Exists in Dictionary

x = {
    "a": "1",
    "b": (2,),
    "c": 3
}
if "a" in x:
    print(x["a"])

Change Values in Dictionary

x = {"a": "Yes", "b": (2,), "c": 3}
print(x)

Add new Element to Dictionary

x = {"a": "Yes", "b": (2,), "c": 3}
x["d"] = [1, 2, 3]
print(x)

Remove Dictionary Elements

pop() method - removes the elements with the specified key name.

x = {"a": "Yes", "b": (2,), "c": 3}
x.pop("b")
print(x)

popitem() method - removes the last inserted element.

x = {"a": "Yes", "b": (2,), "c": 3}
x.popitem()
print(x)

clear() method - empties the dictionary

x = {"a": "Yes", "b": (2,), "c": 3}
x.clear()
print(x)

Loop Through a Dictionary

x = {"a": "Yes", "b": (2,), "c": 3}
for i in x:
    print(str(i) + ":" + str(x[i]))

Copy a Dictionary

x = {"a": "Yes", "b": (2,), "c": 3}
y = x.copy()
print(y)
z = dict(x)
print(z)

Conditions

if...else statement use to make decision.

If Statement Syntax

if Condition 1:
    statement 1 #Condition 1 True
elif Condition 2:
   statement 2 #Condition 2 True
else:
	statement 3

Example

x = 4
if x == 2:
    print("2")
elif x == 4:
    print(4)
else:
    print("No")

Short If

print("4") if x == 4 else print("No")

Comparison Operators

Operator Example
== x == y
!= x != y
> x > y
< x < y
>= x >= y
<= x <= y

Example

x = 4
if x == 2:
    print("2")
elif x >= 4:
    print(4)
else:
    print("No")

Logical Operators

Operator Example
and x == 1 and x > y
or x < 3 or x = 2
not not(x < 3 or x = 2)

Example

x = 4
if x == 2 or x == 4:
    print("Yes")
else:
    print("No")

Pass Statement

x = 4
if 2 <= x <= 4:
    pass
else:
    print('Go')

Loops

loop are execute a set of statements as long as a condition is true.

While Loop

i = 65
while i < 91:
    print(chr(i))
    i += 1

For Loops

x = "BroHelp.me"
for c in x:
    print(c)

Continue Statement

Continue statement design to stop the current iteration of a loop, and continue with the next iteration.

i = 64
while i < 91:
    i += 1
    if i == 86:
        print("HaHa")
        continue
    else:
        print(chr(i))

Break Statement

Break statement design to stop the loop even if the while or for condition is true

i = 65
while i < 91:
    print(chr(i))
    i += 1
    if i == 86:
        break

Functions

Function

def bro_print():
    print("BRO!!!")


bro_print()
bro_print()
bro_print()

Function Arguments

def bro_print(name):
    print("BRO " + name + str(type[0][1]))


bro_print("bob", (1, 2, 3), (4, 5, 6))

Keyword Arguments

def bro_print(name, type):
    print("BRO " + name + type)


bro_print(type="1", name="bob")

Default Parameter Value

def bro_print(name, type="2"):
    print("BRO " + name + type)


bro_print("bob")

Function with Return Values

def bro_print(name, type="2"):
    x = ("BRO " + name + type)
    return x


y = bro_print("bob")
print(y)

Pass Statement

if you want to declare empty function use pass statement.

def bro_print(name, type="2"):
    pass

Recursion

Recursive function is a function that calls itself.

def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)


y = fibonacci(3)
print(y)

Lambda function

A lambda function is a small function.

x = lambda a, b: a ** b
print(x(2, 4))

Another example

x = {"a":35, "b": 23, "c": 85, "d": 2, "e":733}
y = sorted(x.items(), key=lambda x:x[1])
print(y)

Classes

Create a Class

class BroClass:
    y = "Hey"

    def printX(self):
        print(self.y)


x = BroClass()
x.printX()
print(x.y)

__init__() Function

class BroClass:
    def __init__(self, y):
        self.y = y

    def printX(self):
        print(self.y)


x = BroClass("hey")
x.printX()
print(x.y)

Pass Statement

class BroClass:
    pass

Inheritance

class BroClass:
    def __init__(self, text):
        self.y = text

    def print_y(self):
        print(self.y)


class BroChildClass(BroClass):
    def __init__(self, text):
        BroClass.__init__(self, text)


y = BroClass("Hey")
y.print_y()
z = BroChildClass("Bye")
z.print_y()