![](logo.png)
Learn
Python
Python Syntax¶
print("Hello World")
# This is a comment.
Hello World
Python Variables¶
- A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
- Rules for Python variables:
- A variable name must start with a letter or the underscore character
- A variable name cannot start with a number
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Variable names are case-sensitive (age, Age and AGE are three different variables)
Create a variable
x = 5
y = "Hello, World!"
z = 'Hello, World!'
print(x)
print(y)
print(z)
5 Hello, World! Hello, World!
Assign Value to Multiple Variables
x, y, z = 5, "Hello, World!", 'Hello, World!'
print(x)
print(y)
print(z)
x = y = z = "Hello"
print(x)
print(y)
print(z)
5 Hello, World! Hello, World! Hello Hello Hello
Output both text and variable
x = "awesome"
print("Python is " + x)
Python is awesome
Add a variable to another variable
x = "Python is "
y = "awesome"
z = x + y
print(z)
Python is awesome
The global Keyword
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Python is fantastic
Python Data Types¶
- 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
- You can get the data type of any object by using the type() function
- You can set specific datatype by x = datatypename(value)
Getting the Data Type
x1 = "Hello World"
x2 = 5
x3 = 20.5
x4 = 3+1j
x5 = ["apple", "banana", "cherry"]
x6 = ("apple", "banana", "cherry")
x7 = range(6)
x8 = {"name" : "John", "age" : 36}
x9 = {"apple", "banana", "cherry"}
x10 = frozenset({"apple", "banana", "cherry"})
x11 = True
x12 = b"Hello"
x13 = bytearray(5)
x14 = memoryview(bytes(5))
print("type(x1): ",type(x1))
print("type(x2): ",type(x2))
print("type(x3): ",type(x3))
print("type(x4): ",type(x4))
print("type(x5): ",type(x5))
print("type(x6): ",type(x6))
print("type(x7): ",type(x7))
print("type(x8): ",type(x8))
print("type(x9): ",type(x9))
print("type(x10): ",type(x10))
print("type(x11): ",type(x11))
print("type(x12): ",type(x12))
print("type(x13): ",type(x13))
print("type(x14): ",type(x14))
type(x1): <class 'str'> type(x2): <class 'int'> type(x3): <class 'float'> type(x4): <class 'complex'> type(x5): <class 'list'> type(x6): <class 'tuple'> type(x7): <class 'range'> type(x8): <class 'dict'> type(x9): <class 'set'> type(x10): <class 'frozenset'> type(x11): <class 'bool'> type(x12): <class 'bytes'> type(x13): <class 'bytearray'> type(x14): <class 'memoryview'>
Int¶
- Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(x)
print(type(y))
print(y)
print(type(z))
print(z)
<class 'int'> 1 <class 'int'> 35656222554887711 <class 'int'> -3255522
Float¶
- Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(x)
print(type(y))
print(y)
print(type(z))
print(z)
<class 'float'> 1.1 <class 'float'> 1.0 <class 'float'> -35.59
- Float can also be scientific numbers with an "e" to indicate the power of 10.
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(x)
print(type(y))
print(y)
print(type(z))
print(z)
<class 'float'> 35000.0 <class 'float'> 120000.0 <class 'float'> -8.77e+101
Complex¶
- Complex numbers are written with a "j" as the imaginary part.
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
<class 'complex'> <class 'complex'> <class 'complex'>
Type Conversion¶
x = 1 # int
y = 2.8 # float
z = 1j # complex
# convert from int to float:
a = float(x)
# convert from float to int:
b = int(y)
# convert from int to complex:
c = complex(x)
# Note: You cannot convert complex numbers into another number type.
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
1.0 2 (1+0j) <class 'float'> <class 'int'> <class 'complex'>
Random Number¶
- Python does not have a random() function to make a random number.
- Python has a built-in module called random that can be used to make random numbers.
import random
#print a random number:
print(random.random())
0.2150000573140095
Python Random Module¶
- The seed() method is used to initialize the random number generator.
- The random number generator needs a number to start with (a seed value), to be able to generate a random number.
- By default the random number generator uses the current system time.
- Use the seed() method to customize the start number of the random number generator.
import random
random.seed(10)
print(random.random())
print(random.random())
random.seed(10)
print(random.random())
0.5714025946899135 0.4288890546751146 0.5714025946899135
- The getstate() method returns an object with the current state of the random number generator.
- Use this method to capture the state, and use the setstate() method, with the captured state, to restore the state
import random
#print a random number:
print(random.random())
#capture the state:
state = random.getstate()
#print another random number:
print(random.random())
#restore the state:
random.setstate(state)
#and the next random number should be the same as when you captured the state:
print(random.random())
#print a random number:
print(random.random())
0.4288890546751146 0.5780913011344704 0.5780913011344704 0.20609823213950174
- The getrandbits() method returns an integer in the specified size (in bits).
import random
print(random.getrandbits(4))
print(random.getrandbits(8))
13 125
- The randrange() method returns a randomly selected element from the specified range.
import random
print(random.randrange(3, 9)) #345678
print(random.randrange(3, 9, 2)) #357
5 7
import random
print(random.randint(3, 9))
9
- The choice() method returns a randomly selected element from the specified sequence.
- The sequence can be a string, a range, a list, a tuple or any other kind of sequence.
import random
mylist = ["apple", "banana", "cherry"]
print(random.choice(mylist))
apple
- The choices() method returns a list with the randomly selected element from the specified sequence.
- You can weigh the possibility of each result with the weights parameter or the cum_weights parameter.
- The sequence can be a string, a range, a list, a tuple or any other kind of sequence.
import random
mylist = ["apple", "banana", "cherry"]
print(random.choices(mylist, weights = [10, 1, 1], k = 6))
print(random.choices(mylist, weights = [10, 1, 1]))
['apple', 'apple', 'apple', 'cherry', 'apple', 'apple'] ['apple']
- The shuffle() method takes a sequence (list, string, or tuple) and reorganize the order of the items.
import random
mylist = ["apple", "banana", "cherry"]
random.shuffle(mylist)
print(mylist)
['cherry', 'banana', 'apple']
- The sample() method returns a list with a randomly selection of a specified number of items from a sequnce.
import random
mylist = ["apple", "banana", "cherry"]
print(random.sample(mylist, k=2))
['banana', 'cherry']
- The random() method returns a random floating number between 0 and 1.
import random
print(random.random())
0.28361821790671515
- The uniform() method returns a random floating number between the two specified numbers (both included).
import random
print(random.uniform(20, 30))
26.74964847134956
- The triangular() method returns a random floating number between the two specified numbers (both included), but you can also specify a third parameter, the mode parameter.
- The mode parameter gives you the opportunity to weigh the possible outcome closer to one of the other two parameter values.
- The mode parameter defaults to the midpoint between the two other parameter values, which will not weigh the possible outcome in any direction.
import random
print(random.triangular(20, 40, 37))
print(random.triangular(20, 40))
32.462848444871014 32.073607194626234
Python Casting¶
- int() - constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number), or a string literal (providing the string represents a whole number)
- float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)
- str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals
i1 = int(1) # x will be 1
i2 = int(2.8) # y will be 2
i3 = int("3") # z will be 3
print(i1)
print(i2)
print(i3)
1 2 3
f1 = float(1) # x will be 1.0
f2 = float(2.8) # y will be 2.8
f3 = float("3") # z will be 3.0
f4 = float("4.2") # w will be 4.2
print(f1)
print(f2)
print(f3)
print(f4)
1.0 2.8 3.0 4.2
s1 = str("s1") # x will be 's1'
s2 = str(2) # y will be '2'
s3 = str(3.0) # z will be '3.0'
print(s1)
print(s2)
print(s3)
s1 2 3.0
Python Strings¶
- String literals in python are surrounded by either single quotation marks, or double quotation marks.
- 'hello' is the same as "hello".
a = "Hello"
print(a)
Hello
Multiline Strings
a = """line1,
line2,
line3
line4."""
print(a)
a = '''line1,
line2,
line3
line4.'''
print(a)
line1, line2, line3 line4. line1, line2, line3 line4.
String Length
- To get the length of a string, use the len() function.
a = "Hello, World!"
print(len(a))
13
Strings are Arrays
a = "Hello, World!"
print(a[1])
print(a[2:5])
print(a[2:])
print(a[:4])
print(a[-5:-2])
print(a[-3:])
e llo llo, World! Hell orl ld!
Check String
- To check if a certain phrase or character is present in a string, we can use the keywords in or not in.
txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x)
x = "ain" not in txt
print(x)
True False
String Concatenation
- To concatenate, or combine, two strings you can use the + operator.
a = "Hello"
b = "World"
c = a + b
print(c)
print(a + " " + b)
HelloWorld Hello World
String Format
- we can combine strings and numbers by using the format() method!
- The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are:
age = 36
txt = "My name is John, and I am {}"
print(txt)
print(txt.format(age))
txt = "My name is John, and I am {}".format(age)
print(txt)
My name is John, and I am {} My name is John, and I am 36 My name is John, and I am 36
- The format() method takes unlimited number of arguments, and are placed into the respective placeholders:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
I want 3 pieces of item 567 for 49.95 dollars.
- You can use index numbers {0} to be sure the arguments are placed in the correct placeholders:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
I want to pay 49.95 dollars for 3 pieces of item 567.
String Methods
- All string methods returns new values. They do not change the original string.str.method(txt,args) , txt.method(args)
- The strip() method removes any whitespace from the beginning or the end:
print(str.strip(" Hello, World! ")) # returns "Hello, World!"
Hello, World!
- The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower()) # returns " hello, world! "
hello, world!
- The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper()) # returns " HELLO, WORLD! "
HELLO, WORLD!
- The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J")) # returns " Jello, World! "
Jello, World!
- The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
['Hello', ' World!']
- The capitalize() method returns a string where the first character is upper case.
print(str.capitalize("hello, and welcome to my world."))
Hello, and welcome to my world.
- The casefold() method returns a string where all the characters are lower case.
print(str.casefold("Hello, And Welcome To My World."))
hello, and welcome to my world.
- The center() method will center align the string, using a specified character (space is default) as the fill character.
a = "Hello, World!"
print(a.center(20))
Hello, World!
- The count() method returns the number of times a specified value appears in the string.string.count(value, start, end)
txt = "I love apples, apple are my favorite fruit"
print(txt.count("apple", 10 , 24))
1
- The encode() method encodes the string, using the specified encoding. If no encoding is specified, UTF-8 will be used.
string.encode(encoding=encoding, errors=errors)
encoding : Optional. A String specifying the encoding to use. Default is UTF-8
errors : Optional. A String specifying the error method. Legal values are:
'backslashreplace' :- uses a backslash instead of the character that could not be encoded
'ignore' :- ignores the characters that cannot be encoded
'namereplace' :- replaces the character with a text explaining the character
'strict' :- Default, raises an error on failure
'replace' :- replaces the character with a questionmark
'xmlcharrefreplace' :- replaces the character with an xml character
txt = "My name is Ståle"
print(txt.encode())
print(txt.encode(encoding="ascii",errors="backslashreplace"))
print(txt.encode(encoding="ascii",errors="ignore"))
print(txt.encode(encoding="ascii",errors="namereplace"))
print(txt.encode(encoding="ascii",errors="replace"))
print(txt.encode(encoding="ascii",errors="xmlcharrefreplace"))
b'My name is St\xc3\xa5le' b'My name is St\\xe5le' b'My name is Stle' b'My name is St\\N{LATIN SMALL LETTER A WITH RING ABOVE}le' b'My name is St?le' b'My name is Ståle'
- The endswith() method returns True if the string ends with the specified value, otherwise False. string.endswith(value, start, end)
txt = "Hello, welcome to my world."
print(txt.endswith("."))
True
- The expandtabs() method sets the tab size to the specified number of whitespaces.
txt = "H\te\tl\tl\to"
print(txt.expandtabs(6))
H e l l o
- The find() method finds the first occurrence of the specified value.
- The find() method returns -1 if the value is not found.
- The find() method is almost the same as the index() method, the only difference is that the index() method raises an exception if the value is not found. (See example below)
txt = "Hello, welcome to my world."
print(txt.find("welcome"))
7
- The format() method formats the specified value(s) and insert them inside the string's placeholder.
- The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below.
- The format() method returns the formatted string.
txt1 = "My name is {fname}, I'am {age}".format(fname = "John", age = 36)
txt2 = "My name is {0}, I'am {1}".format("John",36)
txt3 = "My name is {}, I'am {}".format("John",36)
print(txt1)
print(txt2)
print(txt3)
My name is John, I'am 36 My name is John, I'am 36 My name is John, I'am 36
- The index() method finds the first occurrence of the specified value.
- The index() method raises an exception if the value is not found.
txt = "Hello, welcome to my world."
x = txt.index("welcome")
print(x)
7
- The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).
- Example of characters that are not alphanumeric: (space)!#%&? etc.
txt = "Company12"
x = txt.isalnum()
print(x)
True
- The isalpha() method returns True if all the characters are alphabet letters (a-z).
txt = "CompanyX"
x = txt.isalpha()
print(x)
True
- The isdecimal() method returns True if all the characters are decimals (0-9).
- This method is used on unicode objects.
a = "\u0030" #unicode for 0
b = "\u0047" #unicode for G
print(a.isdecimal())
print(b.isdecimal())
True False
- The isdigit() method returns True if all the characters are digits, otherwise False.
- Exponents, like ², are also considered to be a digit.
txt = "50800"
x = txt.isdigit()
print(x)
True
- The isidentifier() method returns True if the string is a valid identifier, otherwise False.
- A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-9), or underscores (_). A valid identifier cannot start with a number, or contain any spaces.
a = "MyFolder"
b = "Demo002"
c = "2bring"
d = "my demo"
print(a.isidentifier())
print(b.isidentifier())
print(c.isidentifier())
print(d.isidentifier())
True True False False
- The islower() method returns True if all the characters are in lower case, otherwise False.
- Numbers, symbols and spaces are not checked, only alphabet characters.
b = "hello 123"
c = "mynameisPeter"
print(b.islower())
print(c.islower())
True False
- The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False.
- Exponents, like ² and ¾ are also considered to be numeric values.
a = "\u0030" #unicode for 0
b = "\u00B2" #unicode for ²
c = "10km2"
print(a.isnumeric())
print(b.isnumeric())
print(c.isnumeric())
True True False
- The isprintable() method returns True if all the characters are printable, otherwise False.
- Example of none printable character can be carriage return and line feed.
txt = "Hello!\nAre you #1?"
x = txt.isprintable()
print(x)
txt = "Hello! Are you #1?"
x = txt.isprintable()
print(x)
False True
- The isspace() method returns True if all the characters in a string are whitespaces, otherwise False.
txt = " "
x = txt.isspace()
print(x)
True
- The istitle() method returns True if all words in a text start with a upper case letter, AND the rest of the word are lower case letters, otherwise False.
- Symbols and numbers are ignored.
a = "HELLO, AND WELCOME TO MY WORLD"
b = "Hello"
c = "22 Names"
d = "This Is %'!?"
print(a.istitle())
print(b.istitle())
print(c.istitle())
print(d.istitle())
False True True True
- The isupper() method returns True if all the characters are in upper case, otherwise False.
- Numbers, symbols and spaces are not checked, only alphabet characters.
a = "Hello World!"
b = "hello 123"
c = "MY NAME IS PETER"
print(a.isupper())
print(b.isupper())
print(c.isupper())
False False True
- The join() method takes all items in an iterable and joins them into one string.
- A string must be specified as the separator.
myTuple = ("John", "Peter", "Vicky")
x = "#".join(myTuple)
print(x)
myDict = {"name": "John", "country": "Norway"}
mySeparator = "TEST"
x = mySeparator.join(myDict)
print(x)
John#Peter#Vicky nameTESTcountry
- The ljust() method will left align the string, using a specified character (space is default) as the fill character.
txt = "banana"
x = txt.ljust(20)
print(x, "is my favorite fruit.")
txt = "banana"
x = txt.ljust(20, "O")
print(x)
banana is my favorite fruit. bananaOOOOOOOOOOOOOO
- The lower() method returns a string where all characters are lower case.
- Symbols and Numbers are ignored.
txt = "Hello my FRIENDS"
x = txt.lower()
print(x)
hello my friends
- The lstrip() method removes any leading characters (space is the default leading character to remove)
txt = " banana "
x = txt.lstrip()
print("of all fruits", x, "is my favorite")
txt = ",,,,,ssaaww.....banana"
x = txt.lstrip(",.asw")
print(x)
of all fruits banana is my favorite banana
- The maketrans() method returns a mapping table that can be used with the translate() method to replace specified characters.
txt = "Hello Sam!";
mytable = txt.maketrans("S", "P");
print(txt.translate(mytable));
Hello Pam!
# Use a mapping table to replace many characters:
txt = "Hi Sam!";
x = "mSa";
y = "eJo";
mytable = txt.maketrans(x, y);
print(txt.translate(mytable));
Hi Joe!
# The third parameter in the mapping table describes characters that you want to remove from the string:
txt = "Good night Sam!";
x = "mSa";
y = "eJo";
z = "odnght";
mytable = txt.maketrans(x, y, z);
print(txt.translate(mytable));
G i Joe!
# The maketrans() method itself returns a dictionary describing each replacement, in unicode:
txt = "Good night Sam!";
x = "mSa";
y = "eJo";
z = "odnght";
print(txt.maketrans(x, y, z));
{109: 101, 83: 74, 97: 111, 111: None, 100: None, 110: None, 103: None, 104: None, 116: None}
- The partition() method searches for a specified string, and splits the string into a tuple containing three elements.
- The first element contains the part before the specified string.
- The second element contains the specified string.
- The third element contains the part after the string.
txt = "I could eat bananas all day"
x = txt.partition("bananas")
print(x)
('I could eat ', 'bananas', ' all day')
txt = "I could eat bananas all day"
x = txt.partition("apples")
print(x)
('I could eat bananas all day', '', '')
- The replace() method replaces a specified phrase with another specified phrase.
txt = "I like bananas"
x = txt.replace("bananas", "apples")
print(x)
I like apples
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three", 2)
print(x)
three three was a race horse, two two was one too.
- The rfind() method finds the last occurrence of the specified value.
- The rfind() method returns -1 if the value is not found.
- The rfind() method is almost the same as the rindex() method. See example below.
txt = "Mi casa, su casa."
x = txt.rfind("casa")
print(x)
12
txt = "Hello, welcome to my world."
x = txt.rfind("e", 5, 10)
print(x)
8
- The rindex() method finds the last occurrence of the specified value.
- The rindex() method raises an exception if the value is not found.
- The rindex() method is almost the same as the rfind() method. See example below.
txt = "Mi casa, su casa."
x = txt.rindex("casa")
print(x)
12
txt = "Hello, welcome to my world."
x = txt.rindex("e")
print(x)
13
- The rjust() method will right align the string, using a specified character (space is default) as the fill character.
txt = "banana"
x = txt.rjust(20)
print(x, "is my favorite fruit.")
banana is my favorite fruit.
- The rpartition() method searches for the last occurrence of a specified string, and splits the string into a tuple containing three elements.
- The first element contains the part before the specified string.
- The second element contains the specified string.
- The third element contains the part after the string.
txt = "I could eat bananas all day, bananas are my favorite fruit"
x = txt.rpartition("bananas")
print(x)
('I could eat bananas all day, ', 'bananas', ' are my favorite fruit')
- The rsplit() method splits a string into a list, starting from the right.
- If no "max" is specified, this method will return the same as the split() method.
txt = "apple, banana, cherry"
x = txt.rsplit(", ")
print(x)
['apple', 'banana', 'cherry']
txt = "apple, banana, cherry"
# setting the maxsplit parameter to 1, will return a list with 2 elements!
x = txt.rsplit(", ", 1)
print(x)
['apple, banana', 'cherry']
- The rstrip() method removes any trailing characters (characters at the end a string), space is the default trailing character to remove.
txt = " banana "
x = txt.rstrip()
print("of all fruits", x, "is my favorite")
of all fruits banana is my favorite
txt = "banana,,,,,ssqqqww....."
x = txt.rstrip(",.qsw")
print(x)
banana
- The swapcase() method returns a string where all the upper case letters are lower case and vice versa.
txt = "Hello My Name Is PETER"
x = txt.swapcase()
print(x)
hELLO mY nAME iS peter
- The title() method returns a string where the first character in every word is upper case. Like a header, or a title.
- If the word contains a number or a symbol, the first letter after that will be converted to upper case.
txt = "Welcome to my 2nd world"
x = txt.title()
print(x)
Welcome To My 2Nd World
- The translate() method returns a string where some specified characters are replaced with the character described in a dictionary, or in a mapping table.
- Use the maketrans() method to create a mapping table.
- If a character is not specified in the dictionary/table, the character will not be replaced.
- If you use a dictionary, you must use ascii codes instead of characters.
#use a dictionary with ascii codes to replace 83 (S) with 80 (P):
mydict = {83: 80};
txt = "Hello Sam!";
print(txt.translate(mydict));
Hello Pam!
txt = "Good night Sam!";
mydict = {109: 101, 83: 74, 97: 111, 111: None, 100: None, 110: None, 103: None, 104: None, 116: None};
print(txt.translate(mydict));
G i Joe!
txt = "Good night Sam!";
x = "mSa";
y = "eJo";
z = "odnght";
mytable = txt.maketrans(x, y, z);
print(txt.translate(mytable));
G i Joe!
- The upper() method returns a string where all characters are in upper case.
- Symbols and Numbers are ignored.
txt = "Hello my friends"
x = txt.upper()
print(x)
HELLO MY FRIENDS
- The zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length.
- If the value of the len parameter is less than the length of the string, no filling is done.
txt = "50"
x = txt.zfill(10)
print(x)
0000000050
Escape Character
- To insert characters that are illegal in a string, use an escape character.
- An escape character is a backslash \ followed by the character you want to insert.
# Double Quotes
txt = "We are the so-called \"Vikings\" from the north."
print(txt)
We are the so-called "Vikings" from the north.
# Single Quote
txt = 'It\'s alright.'
print(txt)
It's alright.
# Backslash
txt = "This will insert one \\ (backslash)."
print(txt)
This will insert one \ (backslash).
# New Line
txt = "Hello\nWorld!"
print(txt)
Hello World!
# Carriage Return
txt = "Hello\rWorld!"
print(txt)
World!
# Tab
txt = "Hello\tWorld!"
print(txt)
Hello World!
# This example erases one character (backspace):
txt = "Hello \bWorld!"
print(txt)
HelloWorld!
# A backslash followed by three integers will result in a octal value:
txt = "\110\145\154\154\157"
print(txt)
Hello
# A backslash followed by an 'x' and a hex number represents a hex value:
txt = "\x48\x65\x6c\x6c\x6f"
print(txt)
Hello
Python Booleans¶
- You can evaluate any expression in Python, and get one of two answers, True or False.
- Almost any value is evaluated to True if it has some sort of content.
- Any string is True, except empty strings.
- Any number is True, except 0.
- Any list, tuple, set, and dictionary are True, except empty ones.
print(10 > 9) #True
print(10 == 9) #False
if 10 > 9:
print("b is greater than a")
print(bool("Hello")) #True
print(bool(15)) #True
print(bool(0)) #False
print(bool("")) #False
True False b is greater than a True True False False
Python 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 |
Assignment Operators
Operator | Example | Same As |
---|---|---|
= | x = 5 | 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 &= 3 | x = x & 3 |
|= | x |= 3 | x = x | 3 |
^= | x ^= 3 | x = x ^ 3 |
>>= | x >>= 3 | x = x >> 3 |
<<= | x <<= 3 | x = x << 3 |
Comparison Operators
Operator | Name | Example |
---|---|---|
== | Equal | x == y |
!= | Not equal | x != y |
> | Greater than | x > y |
< | Less than | x < y |
>= | Greater than or equal to | x >= y |
<= | Less than or equal to | x <= y |
Logical Operators
Operator | Description | Example |
---|---|---|
and | Returns True if both statements are true | x < 5 and x < 10 |
or | Returns True if one of the statements is true | x < 5 or x < 4 |
not | Reverse the result, returns False if the result is true | not(x < 5 and x < 10) |
Identity Operators
Operator | Description | Example |
---|---|---|
is | Returns True if both variables are the same object | x is y |
is not | Returns True if both variables are not the same object | x is not y |
Membership Operators
Operator | Description | Example |
---|---|---|
in | Returns True if a sequence with the specified value is present in the object | x in y |
not in | Returns True if a sequence with the specified value is not present in the object | x not in y |
Bitwise Operators
Operator | Name | Description |
---|---|---|
& | AND | Sets each bit to 1 if both bits are 1 |
| | OR | Sets each bit to 1 if one of two bits is 1 |
^ | XOR | Sets each bit to 1 if only one of two bits is 1 |
~ | NOT | Inverts all the bits |
<< | Zero fill left shift | Shift left by pushing zeros in from the right and let the leftmost bits fall off |
>> | Signed right shift | Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off |
Python Lists¶
- List is a collection which is ordered and changeable. Allows duplicate members.
thislist = ["apple", "banana", "cherry"]
print(thislist)
['apple', 'banana', 'cherry']
Access Items
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[1])
print(thislist[-1])
print(thislist[2:5])
print(thislist[:4])
print(thislist[4:])
print(thislist[-4:-1])
banana mango ['cherry', 'orange', 'kiwi'] ['apple', 'banana', 'cherry', 'orange'] ['kiwi', 'melon', 'mango'] ['orange', 'kiwi', 'melon']
Change Item Value
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
['apple', 'blackcurrant', 'cherry']
Loop Through a List
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
apple banana cherry
Check if Item Exists
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Yes, 'apple' is in the fruits list
List Length
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
3
Add Items / Remove Item
# Add Items
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
['apple', 'banana', 'cherry', 'orange'] ['apple', 'orange', 'banana', 'cherry']
# Remove Item
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
thislist = ["apple", "banana", "cherry"]
thislist.pop(0)
print(thislist)
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
['apple', 'cherry'] ['apple', 'banana'] ['banana', 'cherry'] ['banana', 'cherry'] []
Copy a List
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
['apple', 'banana', 'cherry'] ['apple', 'banana', 'cherry']
Join Two Lists
# Method 1
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
#Method 2
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
#Method 3
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
['a', 'b', 'c', 1, 2, 3] ['a', 'b', 'c', 1, 2, 3] ['a', 'b', 'c', 1, 2, 3]
The list() Constructor
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)
['apple', 'banana', 'cherry']
List Methods
- The append() method appends an element to the end of the list.
fruits = ['apple', 'banana', 'cherry']
fruits.append("orange")
print(fruits)
a = ["apple", "banana", "cherry"]
b = ["Ford", "BMW", "Volvo"]
a.append(b)
print(a)
['apple', 'banana', 'cherry', 'orange'] ['apple', 'banana', 'cherry', ['Ford', 'BMW', 'Volvo']]
- The clear() method removes all the elements from a list.
fruits = ['apple', 'banana', 'cherry', 'orange']
fruits.clear()
print(fruits)
[]
- The copy() method returns a copy of the specified list.
fruits = ['apple', 'banana', 'cherry', 'orange']
x = fruits.copy()
print(x)
['apple', 'banana', 'cherry', 'orange']
- The count() method returns the number of elements with the specified value.
fruits = ['apple', 'banana', 'cherry']
print(fruits.count("cherry"))
points = [1, 4, 2, 9, 7, 8, 9, 3, 1]
print(points.count(9))
1 2
- The extend() method adds the specified list elements (or any iterable) to the end of the current list.
fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
print(fruits)
fruits = ['apple', 'banana', 'cherry']
points = (1, 4, 5, 9)
fruits.extend(points)
print(fruits)
['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo'] ['apple', 'banana', 'cherry', 1, 4, 5, 9]
- The index() method returns the position at the first occurrence of the specified value.
fruits = ['apple', 'banana', 'cherry']
print(fruits.index("cherry"))
fruits = [4, 55, 64, 32, 16, 32]
print(fruits.index(32))
2 3
- The insert() method inserts the specified value at the specified position.
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
print(fruits)
['apple', 'orange', 'banana', 'cherry']
- The pop() method removes the element at the specified position.
fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
print(fruits)
fruits = ['apple', 'banana', 'cherry']
x = fruits.pop(1)
print(x)
['apple', 'cherry'] banana
- The remove() method removes the first occurrence of the element with the specified value.
fruits = ['apple', 'banana', 'cherry']
fruits.remove("banana")
print(fruits)
['apple', 'cherry']
- The reverse() method reverses the sorting order of the elements.
fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits)
['cherry', 'banana', 'apple']
- The sort() method sorts the list ascending by default.
- You can also make a function to decide the sorting criteria(s).
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
print(cars)
['BMW', 'Ford', 'Volvo']
cars = ['Ford', 'BMW', 'Volvo']
cars.sort(reverse=True)
print(cars)
['Volvo', 'Ford', 'BMW']
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(key=myFunc)
print(cars)
['VW', 'BMW', 'Ford', 'Mitsubishi']
# A function that returns the 'year' value:
def myFunc(e):
return e['year']
cars = [
{'car': 'Ford', 'year': 2005},
{'car': 'Mitsubishi', 'year': 2000},
{'car': 'BMW', 'year': 2019},
{'car': 'VW', 'year': 2011}
]
cars.sort(key=myFunc)
print(cars)
[{'car': 'Mitsubishi', 'year': 2000}, {'car': 'Ford', 'year': 2005}, {'car': 'VW', 'year': 2011}, {'car': 'BMW', 'year': 2019}]
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(reverse=True, key=myFunc)
print(cars)
['Mitsubishi', 'Ford', 'BMW', 'VW']
Python Tuples¶
- A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.
thistuple = ("apple", "banana", "cherry")
print(thistuple)
('apple', 'banana', 'cherry')
Access Tuple Items
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[1])
print(thistuple[-1])
print(thistuple[2:5])
print(thistuple[-4:-1])
banana mango ('cherry', 'orange', 'kiwi') ('orange', 'kiwi', 'melon')
Change Tuple Values
- Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.
- But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
('apple', 'kiwi', 'cherry')
Loop Through a Tuple
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
apple banana cherry
Check if Item Exists
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Yes, 'apple' is in the fruits tuple
Tuple Length
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
3
Create Tuple With One Item
thistuple = ("apple",) # <class 'tuple'>
print(type(thistuple))
#NOT a tuple
thistuple = ("apple") # <class 'str'>
print(type(thistuple))
<class 'tuple'> <class 'str'>
Delete Tuple
thistuple = ("apple", "banana", "cherry")
del thistuple
Join Two Tuples
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
('a', 'b', 'c', 1, 2, 3)
The tuple() Constructor
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
('apple', 'banana', 'cherry')
Tuple Methods
- The count() method returns the number of times a specified value appears in the tuple.
- The index() method finds the first occurrence of the specified value.
- The index() method raises an exception if the value is not found.
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.count(5)
print(x)
2
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.index(8)
print(x)
3
Python Sets¶
- A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
thisset = {"apple", "banana", "cherry"}
print(thisset)
{'apple', 'cherry', 'banana'}
Access Items
- You cannot access items in a set by referring to an index or a key.
- But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
# Check if "banana" is present in the set:
print("banana" in thisset)
apple cherry banana True
Add Items
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
{'orange', 'apple', 'cherry', 'banana'}
thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)
{'grapes', 'banana', 'mango', 'apple', 'orange', 'cherry'}
Get the Length of a Set
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
3
Remove Item
thisset = {"apple", "banana", "cherry"}
# If the item to remove does not exist, remove() will raise an error.
thisset.remove("banana")
print(thisset)
{'apple', 'cherry'}
thisset = {"apple", "banana", "cherry"}
# If the item to remove does not exist, discard() will NOT raise an error.
thisset.discard("banana")
print(thisset)
{'apple', 'cherry'}
thisset = {"apple", "banana", "cherry"}
# Sets are unordered, so when using the pop() method, you will not know which item that gets removed.
x = thisset.pop()
print(x)
print(thisset)
apple {'cherry', 'banana'}
thisset = {"apple", "banana", "cherry"}
# The clear() method empties the set
thisset.clear()
print(thisset)
set()
thisset = {"apple", "banana", "cherry"}
# The del keyword will delete the set completely
del thisset
#print(thisset) #Error: name 'thisset' is not defined
Join Two Sets
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3 , "a"}
set3 = set1.union(set2)
print(set3)
{'b', 1, 2, 3, 'c', 'a'}
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3 , "a"}
set1.update(set2)
print(set1)
{'b', 1, 2, 3, 'c', 'a'}
The set() Constructor
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)
{'apple', 'cherry', 'banana'}
Set Methods
- The add() method adds an element to the set.
- If the element already exists, the add() method does not add the element.
fruits = {"apple", "banana", "cherry"}
fruits.add("apple")
print(fruits)
{'apple', 'cherry', 'banana'}
- The clear() method removes all elements in a set.
fruits = {"apple", "banana", "cherry"}
fruits.clear()
print(fruits)
set()
- The copy() method copies the set.
fruits = {"apple", "banana", "cherry"}
x = fruits.copy()
print(x)
{'apple', 'cherry', 'banana'}
- The difference() method returns a set that contains the difference between two sets.
- Meaning: The returned set contains items that exist only in the first set, and not in both sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.difference(y)
print(z)
{'banana', 'cherry'}
- The difference_update() method removes the items that exist in both sets.
- The difference_update() method is different from the difference() method, because the difference() method returns a new set, without the unwanted items, and the difference_update() method removes the unwanted items from the original set.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.difference_update(y)
print(x)
{'cherry', 'banana'}
- The discard() method removes the specified item from the set.
fruits = {"apple", "banana", "cherry"}
fruits.discard("banana")
print(fruits)
{'apple', 'cherry'}
- The intersection() method returns a set that contains the similarity between two or more sets.
x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"}
result = x.intersection(y, z)
print(result)
{'c'}
- The intersection_update() method removes the items that is not present in both sets (or in all sets if the comparison is done between more than two sets).
- The intersection_update() method is different from the intersection() method, because the intersection() method returns a new set, without the unwanted items, and the intersection_update() method removes the unwanted items from the original set.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x)
{'apple'}
- The isdisjoint() method returns True if none of the items are present in both sets, otherwise it returns False.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "facebook"}
z = x.isdisjoint(y)
print(z)
True
- The issubset() method returns True if all items in the set exists in the specified set, otherwise it retuns False.
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y)
print(z)
True
- The issuperset() method returns True if all items in the specified set exists in the original set, otherwise it retuns False.
x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}
z = x.issuperset(y)
print(z)
True
- The pop() method removes a random item from the set.
fruits = {"apple", "banana", "cherry"}
fruits.pop()
print(fruits)
{'cherry', 'banana'}
- he remove() method removes the specified element from the set.
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)
{'apple', 'cherry'}
- The symmetric_difference() method returns a set that contains all items from both set, but not the items that are present in both sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)
{'banana', 'google', 'microsoft', 'cherry'}
- The symmetric_difference_update() method updates the original set by removing items that are present in both sets, and inserting the other items.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)
{'banana', 'microsoft', 'cherry', 'google'}
- The union() method returns a set that contains all items from the original set, and all items from the specified sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.union(y)
print(z)
{'apple', 'banana', 'microsoft', 'google', 'cherry'}
- The update() method updates the current set, by adding items from another set.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.update(y)
print(x)
{'apple', 'banana', 'microsoft', 'google', 'cherry'}
Python Dictionaries¶
- A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Accessing Items
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
Mustang
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.get("model")
print(x)
Mustang
Change Values
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
Loop Through a Dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
print(thisdict[x])
brand Ford model Mustang year 1964
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.values():
print(x)
Ford Mustang 1964
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x, y in thisdict.items():
print(x, y)
brand Ford model Mustang year 1964
Check if Key Exists
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Yes, 'model' is one of the keys in the thisdict dictionary
Dictionary Length
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(len(thisdict))
3
Adding Items
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
Removing Items
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
{'brand': 'Ford', 'year': 1964}
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang'}
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
{'brand': 'Ford', 'year': 1964}
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
#print(thisdict) # This will cause an error because "thisdict" no longer exists.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
{}
Copy a Dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Nested Dictionaries
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily)
{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
print(myfamily)
{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}
The dict() Constructor
thisdict = dict(brand="Ford", model="Mustang", year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Dictionary Methods
- The clear() method removes all the elements from a dictionary.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.clear()
print(car)
{}
- The copy() method returns a copy of the specified dictionary.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.copy()
print(x)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
- The fromkeys() method returns a dictionary with the specified keys and the specified value.
x = ('key1', 'key2', 'key3')
y = 0
thisdict = dict.fromkeys(x, y)
print(thisdict)
{'key1': 0, 'key2': 0, 'key3': 0}
x = ('key1', 'key2', 'key3')
thisdict = dict.fromkeys(x)
print(thisdict)
{'key1': None, 'key2': None, 'key3': None}
- The get() method returns the value of the item with the specified key.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.get("model")
print(x)
Mustang
- The items() method returns a view object. The view object contains the key-value pairs of the dictionary, as tuples in a list.
- The view object will reflect any changes done to the dictionary, see example below.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
car["year"] = 2018
print(x)
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2018)])
- The keys() method returns a view object. The view object contains the keys of the dictionary, as a list.
- The view object will reflect any changes done to the dictionary, see example below.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
car["color"] = "white"
print(x)
dict_keys(['brand', 'model', 'year', 'color'])
- The pop() method removes the specified item from the dictionary.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.pop("model")
print(x)
print(car)
Mustang {'brand': 'Ford', 'year': 1964}
- The popitem() method removes the item that was last inserted into the dictionary.
- The removed item is the return value of the popitem() method, as a tuple.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.popitem()
print(x)
print(car)
('year', 1964) {'brand': 'Ford', 'model': 'Mustang'}
- The setdefault() method returns the value of the item with the specified key.
- If the key does not exist, insert the key, with the specified value, see example below
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("model", "Bronco")
print(x)
x = car.setdefault("color", "white")
print(x)
Mustang white
- The update() method inserts the specified items to the dictionary.
- The specified items can be a dictionary, or an iterable object.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.update({"color": "White"})
print(car)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'White'}
- The values() method returns a view object. The view object contains the values of the dictionary, as a list.
- The view object will reflect any changes done to the dictionary, see example below.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x)
car["year"] = 2018
print(x)
dict_values(['Ford', 'Mustang', 1964]) dict_values(['Ford', 'Mustang', 2018])
Python If ... Else¶
- Python supports the usual logical conditions from mathematics:
Equals: a == b Not Equals: a != b Less than: a < b Less than or equal to: a <= b Greater than: a > b Greater than or equal to: a >= b
- These conditions can be used in several ways, most commonly in "if statements" and loops.
if
- An "if statement" is written by using the if keyword.
a = 2
b = 3
if b > a:
print("b is greater than a")
b is greater than a
elif
- The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition".
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
a and b are equal
else
- The else keyword catches anything which isn't caught by the preceding conditions.
a = 3
b = 2
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
a is greater than b
Short Hand If
if a > b: print("a is greater than b")
a is greater than b
Short Hand If ... Else
a = 2
b = 3
print("A") if a > b else print("B")
B
a = 3
b = 3
print("A") if a > b else print("=") if a == b else print("B")
=
And
- The and keyword is a logical operator, and is used to combine conditional statements:
a = 3
b = 2
c = 5
if a > b and c > a:
print("Both conditions are True")
Both conditions are True
Or
- The or keyword is a logical operator, and is used to combine conditional statements:
a = 3
b = 2
c = 5
if a > b or a > c:
print("At least one of the conditions is True")
At least one of the conditions is True
Nested If
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Above ten, and also above 20!
The pass Statement
- if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.
a = 33
b = 200
if b > a:
pass
Python While Loops¶
- With the while loop we can execute a set of statements as long as a condition is true.
i = 1
while i < 6:
print(i)
i += 1
1 2 3 4 5
The break Statement
- With the break statement we can stop the loop even if the while condition is true.
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
1 2 3
The continue Statement
- With the continue statement we can stop the current iteration, and continue with the next.
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
1 2 4 5 6
The else Statement
- With the else statement we can run a block of code once when the condition no longer is true.
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
1 2 3 4 5 i is no longer less than 6
Python For Loops¶
- A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
- With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
apple banana cherry
Looping Through a String
for x in "banana":
print(x)
b a n a n a
The break Statement
- With the break statement we can stop the loop before it has looped through all the items:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
apple
The continue Statement
- With the continue statement we can stop the current iteration of the loop, and continue with the next
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
apple cherry
The range() Function
- The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
for x in range(4):
print(x)
0 1 2 3
for x in range(2, 6):
print(x)
2 3 4 5
for x in range(2, 10, 3):
print(x)
2 5 8
Else in For Loop
- The else keyword in a for loop specifies a block of code to be executed when the loop is finished
for x in range(4):
print(x)
else:
print("Finally finished!")
0 1 2 3 Finally finished!
Nested Loops
a = ["a0", "a1"]
b = ["b0", "b1"]
for x in a:
for y in b:
print(x, y)
a0 b0 a0 b1 a1 b0 a1 b1
The pass Statement
- for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error.
for x in [0, 1, 2]:
pass
Python Functions¶
- A function is a block of code which only runs when it is called.
- You can pass data, known as parameters, into a function.
- A function can return data as a result.
Creating a Function
- A function is defined using the def keyword.
def my_function():
print("Hello from a function")
Calling a Function
- To call a function, use the function name followed by parenthesis.
def my_function():
print("Hello from a function")
my_function()
Hello from a function
Arguments
- Information can be passed into functions as arguments.
- Arguments are specified after the function name, inside the parentheses.
def my_function(fname):
print(fname + " is fname")
my_function("Yash")
my_function("Deepa")
my_function("John")
Yash is fname Deepa is fname John is fname
Arbitrary Arguments, *args
- If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.
- This way the function will receive a tuple of arguments, and can access the items accordingly
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
The youngest child is Linus
Keyword Arguments
- You can also send arguments with the key = value syntax.
- This way the order of the arguments does not matter.
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
The youngest child is Linus
Arbitrary Keyword Arguments, kwargs**
- If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition.
- This way the function will receive a dictionary of arguments, and can access the items accordingly
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
His last name is Refsnes
Default Parameter Value
- If we call the function without argument, it uses the default value.
def my_function(country = "Norway"):
print("I am from " + country)
my_function("India")
my_function()
I am from India I am from Norway
Passing a List as an Argument
- You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
def my_function(food):
print(food)
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
fruits = ("apple", "banana", "cherry")
my_function(fruits)
['apple', 'banana', 'cherry'] apple banana cherry ('apple', 'banana', 'cherry') apple banana cherry
Return Values
- To let a function return a value, use the return statement.
def my_function(x):
return 5 * x
print(my_function(3))
15
The pass Statement
- function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error.
def myfunction():
pass
Recursion
- Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
ans = tri_recursion(6)
1 3 6 10 15 21
Python Lambda¶
- A lambdafunction is a small anonymous function.
- A lambda function can take any number of arguments, but can only have one expression.
- Syntax lambda arguments : expression
- The expression is executed and the result is returned
x = lambda a : a + 10
print(x(5))
15
x = lambda a, b : a * b
print(x(5, 6))
30
Why Use Lambda Functions?
- The power of lambda is better shown when you use them as an anonymous function inside another function.
- Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
22 33
Python Classes and Objects¶
- Python is an object oriented programming language.
- Almost everything in Python is an object, with its properties and methods.
- A Class is like an object constructor, or a "blueprint" for creating objects.
Create a Class
- To create a class, use the keyword class
class MyClass:
x = 5
print(MyClass)
<class '__main__.MyClass'>
Create Object
class MyClass:
x = 5
p1 = MyClass()
print(p1.x)
5
The init () Function
- All classes have a function called init (), which is always executed when the class is being initiated.
- Use the init () function to assign values to object properties, or other operations that are necessary to do when the object is being created
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
John 36
Object Methods
- Objects can also contain methods. Methods in objects are functions that belong to the object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Hello my name is John
The self Parameter
- The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.
- It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Hello my name is John
Modify Object Properties
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.age = 40
print(p1.age)
40
Delete Object Properties
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
del p1.age
# print(p1.age) # Error: 'Person' object has no attribute 'age'
Delete Objects
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
p1 = Person("John", 36)
del p1
# print(p1) # Error: 'p1' is not defined
The pass Statement
- class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error.
class Person:
pass
Python Inheritance¶
- Inheritance allows us to define a class that inherits all the methods and properties from another class.
- Parent class is the class being inherited from, also called base class.
- Child class is the class that inherits from another class, also called derived class.
Create a Child Class from Parent Class
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
pass
x = Student("Mike", "Olsen")
x.printname()
Mike Olsen
Add the init () Function
- The child's init () function overrides the inheritance of the parent's init () function.
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
class Emp(Person):
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
x = Student("Mike", "Olsen")
x.printname()
y = Emp("John", "Olsen")
y.printname()
Mike Olsen John Olsen
Use the super() Function
- Python also has a super() function that will make the child class inherit all the methods and properties from its parent
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
x = Student("Mike", "Olsen")
x.printname()
Mike Olsen
Add Properties
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
x = Student("Mike", "Olsen", 2019)
print(x.graduationyear)
2019
Add Methods
- If you add a method in the child class with the same name as a function in the parent class, the inheritance of the parent method will be overridden.
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
x = Student("Mike", "Olsen", 2019)
x.welcome()
Welcome Mike Olsen to the class of 2019
Python Iterators¶
- An iterator is an object that contains a countable number of values.
- An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
- Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods iter () and next ().
- Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from.
- All these objects have a iter() method which is used to get an iterator
- Strings are also iterable objects, containing a sequence of characters
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
apple banana cherry
mystr = "hey"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
h e y
Looping Through an Iterator
- We can also use a for loop to iterate through an iterable object
- The for loop actually creates an iterator object and executes the next() method for each loop.
Create an Iterator
- To create an object/class as an iterator you have to implement the methods iter () and next () to your object.
- The iter () method acts similar, you can do operations (initializing etc.), but must always return the iterator object itself.
- The next () method also allows you to do operations, and must return the next item in the sequence.
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
1 2 3
StopIteration
- The example above would continue forever if you had enough next() statements, or if it was used in a for loop.
- To prevent the iteration to go on forever, we can use the StopIteration statement.
- In the next () method, we can add a terminating condition to raise an error if the iteration is done a specified number of times
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 6:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)
1 2 3 4 5 6
Python Scope¶
- A variable is only available from inside the region it is created. This is called scope.
Local Scope
- A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.
- The local variable can be accessed from a function within the function.
def myfunc():
x = 300
print(x)
myfunc()
300
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
300
Global Scope
- A variable created in the main body of the Python code is a global variable and belongs to the global scope.
- Global variables are available from within any scope, global and local.
x = 300
def myfunc():
print(x)
myfunc()
print(x)
300 300
Naming Variables
- If you operate with the same variable name inside and outside of a function, Python will treat them as two separate variables, one available in the global scope (outside the function) and one available in the local scope (inside the function).
x = 30
def myfunc():
x = 20
print(x)
myfunc()
print(x)
20 30
Global Keyword
- If you need to create a global variable, but are stuck in the local scope, you can use the global keyword.
- The global keyword makes the variable global.
def myfunc():
global var
var = 300
myfunc()
print(var)
300
- Also, use the global keyword if you want to make a change to a global variable inside a function.
x = 300
def myfunc():
global x
x = 200
myfunc()
print(x)
200
Python Datetime¶
- A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
import datetime
date_time = datetime.datetime.now()
print(date_time)
2020-12-29 14:40:46.348641
Date Output
- When we execute the code print(datetime.datetime.now()) result will be: 2020-12-29 00:27:14.684192
- The date contains year, month, day, hour, minute, second, and microsecond.
- The datetime module has many methods to return information about the date object.
import datetime
date_time = datetime.datetime.now()
print(date_time)
print(date_time.year)
print(date_time.month)
print(date_time.day)
print(date_time.hour)
print(date_time.minute)
print(date_time.second)
print(date_time.microsecond)
2020-12-29 14:40:46.431417 2020 12 29 14 40 46 431417
Creating Date Objects
- To create a date, we can use the datetime() class (constructor) of the datetime module.
- The datetime() class requires three parameters to create a date: year, month, day.
- The datetime() class also takes parameters for time and timezone (hour, minute, second, microsecond, tzone), but they are optional, and has a default value of 0, (None for timezone).
import datetime
date_time = datetime.datetime(2020, 5, 17)
print(date_time)
2020-05-17 00:00:00
The strftime() Method
- The datetime object has a method for formatting date objects into readable strings.
- The method is called strftime(), and takes one parameter, format, to specify the format of the returned string
import datetime
x = datetime.datetime(2018, 12, 31)
print(x.strftime("%B"))
December
Directive | Description | Example |
---|---|---|
%a | Weekday, short version | Wed |
%A | Weekday, full version | Wednesday |
%w | Weekday as a number 0-6, 0 is Sunday | 3 |
%d | Day of month 01-31 | 31 |
%b | Month name, short version | Dec |
%B | Month name, full version | December |
%m | Month as a number 01-12 | 12 |
%y | Year, short version, without century | 18 |
%Y | Year, full version | 2018 |
%H | Hour 00-23 | 17 |
%I | Hour 00-12 | 05 |
%p | AM/PM | PM |
%M | Minute 00-59 | 41 |
%S | Second 00-59 | 08 |
%f | Microsecond 000000-999999 | 548513 |
%z | UTC offset | +0100 |
%Z | Timezone | CST |
%j | Day number of year 001-366 | 365 |
%U | Week number of year, Sunday as the first day of week, 00-53 | 52 |
%W | Week number of year, Monday as the first day of week, 00-53 | 52 |
%c | Local version of date and time | Mon Dec 31 17:41:00 2018 |
%x | Local version of date | 12/31/18 |
%X | Local version of time | 17:41:00 |
%% | A % character | % |
Python Math¶
Built-in Math Functions
- The min() and max() functions can be used to find the lowest or highest value in an iterable
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
5 25
- The abs() function returns the absolute (positive) value of the specified number
x = abs(-7.25)
print(x)
7.25
- The pow(x, y) function returns the value of x to the power of y.
x = pow(4, 3)
print(x)
64
Python math Module¶
- Python has a built-in module that you can use for mathematical tasks.
- The math module has a set of methods and constants
- To use it, you must import the math module
import math
Math Constants
import math
# Print the value of Euler e
print (math.e)
2.718281828459045
import math
# Print the positive infinity
# returns a floating-point positive infinity
print (math.inf)
# Print the negative infinity
print (-math.inf)
inf -inf
import math
# Print the value of nan
# returns a floating-point nan (Not a Number) value. This value is not a legal number.
print (math.nan)
nan
import math
# Print the value of pi , π
print (math.pi)
3.141592653589793
import math
# Print the value of tau
# τ = 2π
print (math.tau)
6.283185307179586
Math Methods
import math
# Return the arc cosine value of numbers
print (math.acos(0.55))
print (math.acos(-0.55))
print (math.acos(0))
print (math.acos(1))
print (math.acos(-1))
0.9884320889261531 2.15316056466364 1.5707963267948966 0.0 3.141592653589793
import math
# Return the hyperbolic arc cosine value of numbers
print (math.acosh(7))
print (math.acosh(56))
print (math.acosh(2.45))
print (math.acosh(1))
2.6339157938496336 4.718419142372879 1.5447131178707394 0.0
import math
# Return the arc sine value of numbers
print (math.asin(0.55))
print (math.asin(-0.55))
print (math.asin(0))
print (math.asin(1))
print (math.asin(-1))
0.5823642378687435 -0.5823642378687435 0.0 1.5707963267948966 -1.5707963267948966
import math
# Return the hyperbolic arc sine value of numbers
print (math.asinh(7))
print (math.asinh(56))
print (math.asinh(2.45))
print (math.asinh(1))
2.644120761058629 4.718578581151767 1.6284998192841909 0.8813735870195429
import math
#find the arctangent of different numbers
print (math.atan(0.39))
print (math.atan(67))
print (math.atan(-21))
0.37185607384858127 1.5558720618048116 -1.5232132235179132
import math
# Return the arc tangent of y/x in radians
print (math.atan2(8, 5))
print (math.atan2(20, 10))
print (math.atan2(34, -7))
1.0121970114513341 1.1071487177940904 1.7738415440483617
import math
#print the hyperbolic arctangent of different numbers
print (math.atanh(0.59))
print (math.atanh(-0.12))
0.6776660677579618 -0.12058102840844402
import math
# Round a number upward to its nearest integer
print(math.ceil(1.4))
print(math.ceil(5.3))
print(math.ceil(-5.3))
print(math.ceil(22.6))
2 6 -5 23
import math
# Initialize the number of items to choose from
n = 7
# Initialize the number of possibilities to choose
k = 5
# Print total number of possible combinations
print (math.comb(n, k))
21
import math
#Return the first value, with the sign of the second value
print(math.copysign(4, -1))
print(math.copysign(-8, 97.21))
print(math.copysign(-43, -76))
-4.0 8.0 -43.0
import math
# Return the cosine of different numbers
print (math.cos(0.00))
print (math.cos(-1.23))
print (math.cos(10))
print (math.cos(3.14159265359))
1.0 0.3342377271245026 -0.8390715290764524 -1.0
import math
# Return the hyperbolic cosine of different numbers
print (math.cosh(1))
print (math.cosh(8.90))
print (math.cosh(0))
print (math.cosh(1.52))
1.5430806348152437 3665.986837772461 1.0 2.395468541047187
import math
# Convert angles from radians to degrees:
print (math.degrees(8.90))
print (math.degrees(-20))
print (math.degrees(1))
print (math.degrees(90))
509.9324376664327 -1145.9155902616465 57.29577951308232 5156.620156177409
import math
# The first point of Euclidean space
p = [3]
# The second point of Euclidean space
q = [1]
## Calculate the distance between point p and q
print (math.dist(p, q))
2.0
import math
# Print the error function of different numbers
print (math.erf(0.67))
print (math.erf(1.34))
print (math.erf(-6))
0.6566277023003051 0.9419137152583654 -1.0
import math
# Print the complementary error function of different numbers
print (math.erfc(0.67))
print (math.erfc(1.34))
print (math.erfc(-6))
0.3433722976996949 0.05808628474163466 2.0
import math
#find the exponential of the specified value
print(math.exp(65))
print(math.exp(-6.89))
1.6948892444103338e+28 0.0010179138409954387
import math
#Return the exponential ex-1
print(math.expm1(32))
print(math.expm1(-10.89))
78962960182679.69 -0.9999813562576685
import math
#Remove - sign of given number
print(math.fabs(-66.43))
print(math.fabs(-7))
66.43 7.0
import math
#Return factorial of a number
print(math.factorial(9))
print(math.factorial(6))
print(math.factorial(12))
362880 720 479001600
import math
# Round a number downward to its nearest integer
print(math.floor(1.4))
print(math.floor(5.3))
print(math.floor(-5.3))
print(math.floor(22.6))
1 5 -6 22
import math
# Return the remainder after modulo operation
print (math.fmod(67, 7))
print (math.fmod(17, 4))
print (math.fmod(16, 4))
4.0 1.0 0.0
import math
#Return mantissa and exponent of a given number
print(math.frexp(4))
print(math.frexp(7.9))
(0.5, 3) (0.9875, 3)
import math
# Add items in a tuple
a = (1, 2, 3, 4, 5)
# Print the sum of all items
print(math.fsum(a))
15.0
import math
# Return the gamma value of different numbers
# The gamma value is equal to factorial(x-1).
print (math.gamma(5))
print (math.gamma(-4.2))
24.0 -0.16406105047761402
import math
#find the highest number that can divide two numbers
print (math.gcd(26, 12))
print (math.gcd(12, 6))
print (math.gcd(10, 0))
print (math.gcd(0, 34))
print (math.gcd(0, 0))
2 6 10 34 0
import math
# Euclidean norm. The Euclidian norm is the distance from the origin to the coordinates given.
# sqrt(x*x + y*y))
# sqrt(x1*x1 + x2*x2 +x3*x3 .... xn*xn)
#set perpendicular and base
parendicular = 4
base = 3
#print the hypotenuse of a right-angled triangle
print (math.hypot(parendicular, base))
#print the Euclidean length from the origin of given coordinates.
print (math.hypot(10,2,4,13))
5.0 17.0
import math
#compare the closeness of two values
# math.isclose(a, b, rel_tol = value, abs_tol = value)
# abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
print(math.isclose(1.233, 1.4566))
print(math.isclose(1.233, 1.233))
print(math.isclose(1.233, 1.233000001))
print(math.isclose(8.005, 8.450, abs_tol = 0.5))
False True True True
import math
# Check whether some values are finite
print (math.isfinite (56))
print (math.isfinite (-45.34))
print (math.isfinite (+45.34))
print (math.isfinite (math.inf))
print (math.isfinite (float("nan")))
print (math.isfinite (float("inf")))
print (math.isfinite (float("-inf")))
print (math.isfinite (-math.inf))
True True True False False False False False
import math
# Check whether some values are infinite
print (math.isinf (56))
print (math.isinf (-45.34))
print (math.isinf (+45.34))
print (math.isinf (math.inf))
print (math.isinf (float("nan")))
print (math.isinf (float("inf")))
print (math.isinf (float("-inf")))
print (math.isinf (-math.inf))
False False False True False True True True
import math
# Check whether some values are NaN or not
# Not A Number
print (math.isnan (56))
print (math.isnan (-45.34))
print (math.isnan (+45.34))
print (math.isnan (math.inf))
print (math.isnan (float("nan")))
print (math.isnan (float("inf")))
print (math.isnan (float("-inf")))
print (math.isnan (math.nan))
False False False False True False False True
import math
# Examples to print the square root of different numbers
print (math.sqrt(10))
print (math.sqrt (13))
print (math.sqrt (68))
print (math.sqrt (100))
# Round square root numbers downward to the nearest integer
print (math.isqrt(10))
print (math.isqrt (13))
print (math.isqrt (68))
print (math.isqrt (100))
3.1622776601683795 3.605551275463989 8.246211251235321 10.0 3 3 8 10
import math
# Return the log gamma value of different numbers
print (math.lgamma(7))
print (math.lgamma(-4.2))
6.579251212010102 -1.8075166614192908
import math
# Return the natural logarithm of different numbers
# math.log(x, base) base Optional. The logarithmic base to use. Default is 'e'
print(math.log(2.7183))
print(math.log(2))
print(math.log(1))
print(math.log(2, 10))
1.0000066849139877 0.6931471805599453 0.0 0.30102999566398114
import math
# Return the base-10 logarithm of different numbers
print(math.log10(2.7183))
print(math.log10(2))
print(math.log10(1))
0.43429738512450866 0.3010299956639812 0.0
import math
# Return the base-2 logarithm of different numbers
print(math.log2(2.7183))
print(math.log2(2))
print(math.log2(1))
1.4427046851812222 1.0 0.0
import math
# Initialize the number of items to choose from
n = 5
# Initialize the number of items to choose
k = 3
# The k parameter is optional. If we do not provide one, this method will return n!
# Print the number of ways to choose k items from n items
print (math.perm(n, k))
60
import math
#Return the value of 9 raised to the power of 3
print(math.pow(9, 3))
729.0
import math
# Convert different degrees into radians
print(math.radians(180))
print(math.radians(100.03))
print(math.radians(-20))
3.141592653589793 1.7458528507699278 -0.3490658503988659
import math
# Find the value n that makes x completely divisible by y
print (math.remainder(9, 2))
print (math.remainder(18, 4))
1.0 2.0
import math
# Return the sine of different values
print (math.sin(0.00))
print (math.sin(-1.23))
print (math.sin(10))
print (math.sin(math.pi))
print (math.sin(math.pi/2))
0.0 -0.9424888019316975 -0.5440211108893698 1.2246467991473532e-16 1.0
import math
# Return the hyperbolic sine of different values
print(math.sinh(0.00))
print(math.sinh(-23.45))
print(math.sinh(23))
print(math.sinh(1.00))
print(math.sinh(math.pi))
0.0 -7641446994.979367 4872401723.124452 1.1752011936438014 11.548739357257746
import math
# Return the square root of different numbers
print (math.sqrt(9))
print (math.sqrt(25))
print (math.sqrt(16))
3.0 5.0 4.0
import math
# Return the tangent of different numbers
print (math.tan(90))
print (math.tan(-90))
print (math.tan(45))
print (math.tan(60))
-1.995200412208242 1.995200412208242 1.6197751905438615 0.320040389379563
import math
# Return the hyperbolic tangent of different numbers
print(math.tanh(8))
print(math.tanh(1))
print(math.tanh(-6.2))
0.9999997749296758 0.7615941559557649 -0.9999917628565104
import math
# Return the truncated integer parts of different numbers
# simply remove the decimals.
print(math.trunc(2.77))
print(math.trunc(8.32))
print(math.trunc(-99.29))
2 8 -99
Python Exceptions¶
- The try block lets you test a block of code for errors.
- The except block lets you handle the error.
- The finally block lets you execute code, regardless of the result of the try- and except blocks.
Exception Handling
- When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
- These exceptions can be handled using the try statement
try:
print(not_defined_variable)
except:
print("An exception occurred")
An exception occurred
Many Exceptions
- You can define as many exception blocks as you want.
try:
print(not_defined_variable)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Variable x is not defined
Else
- You can use the else keyword to define a block of code to be executed if no errors were raised:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Hello Nothing went wrong
Finally
- The finally block, if specified, will be executed regardless if the try block raises an error or not.
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
64 The 'try except' is finished
- This can be useful to close objects and clean up resources:
Try to open and write to a file that is not writable:try: f = open("demofile.txt") f.write("Lorum Ipsum") except: print("Something went wrong when writing to the file") finally: f.close()
Raise an exception
- You can choose to throw an exception if a condition occurs.
- To throw (or raise) an exception, use the raise keyword.
# Raise an error and stop the program if x is lower than 0:
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
--------------------------------------------------------------------------- Exception Traceback (most recent call last) <ipython-input-328-88086f2dfbfe> in <module> 4 5 if x < 0: ----> 6 raise Exception("Sorry, no numbers below zero") Exception: Sorry, no numbers below zero
- You can define what kind of error to raise, and the text to print to the user.
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-329-75047f5dae4a> in <module> 2 3 if not type(x) is int: ----> 4 raise TypeError("Only integers are allowed") TypeError: Only integers are allowed
Python MySQL¶
- Python needs a MySQL driver to access the MySQL database.
- Here we will use the driver "MySQL Connector".
- Download and install "MySQL Connector":
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>python -m pip install mysql-connector-python
import mysql.connector*Create Connection--------------------
mydb = mysql.connector.connect( host="localhost", user="myusername", password="mypassword" )
print(mydb)
*Creating a Database--------------------
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
*Check if Database Exists--------------------
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor: print(x)
*Connecting to the database--------------------
import mysql.connector
mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" )
*Create a table--------------------
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
*Check if Table Exists--------------------
mycursor = mydb.cursor()
mycursor.execute("SHOW TABLES")
for x in mycursor: print(x)
*Create primary key when creating the table--------------------
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
*Create primary key on an existing table--------------------
mycursor = mydb.cursor()
mycursor.execute("ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")
*Insert Into Table--------------------
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
*Insert Multiple Rows--------------------
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = [ ('Peter', 'Lowstreet 4'), ('Amy', 'Apple st 652'), ('Hannah', 'Mountain 21') ]
mycursor.executemany(sql, val)
mydb.commit()
print(mycursor.rowcount, "was inserted.")
*Get Inserted ID--------------------
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("Michelle", "Blue Village")
mycursor.execute(sql, val)
mydb.commit()
print("1 record inserted, ID:", mycursor.lastrowid)
*Select From a Table fetchall()
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult: print(x)
*Select From a Table fetchone()--------------------
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchone()
print(myresult)
*Delete Record--------------------
mycursor = mydb.cursor()
sql = "DELETE FROM customers WHERE address = 'Mountain 21'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
*Delete a Table--------------------
mycursor = mydb.cursor()
sql = "DROP TABLE customers"
mycursor.execute(sql)
*Update Table--------------------
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
Python File Handling¶
File Open
- The key function for working with files in Python is the open() function.
- The open() function takes two parameters; filename, and mode.
- There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist "a" - Append - Opens a file for appending, creates the file if it does not exist "w" - Write - Opens a file for writing, creates the file if it does not exist "x" - Create - Creates the specified file, returns an error if the file exists
- In addition you can specify if the file should be handled as binary or text mode:
"t" - Text - Default value. Text mode "b" - Binary - Binary mode (e.g. images)
Syntax
f = open("demofile.txt") f = open("demofile.txt", "rt") f = open("D:\\myfiles\welcome.txt", "r")
Read File
- The open() function returns a file object, which has a read() method for reading the content of the file.
- By default the read() method returns the whole text, but you can also specify how many characters you want to return.
Syntax
f = open("demofile.txt", "r") print(f.read()) #content print(f.read(5)) #characters print(f.readline()) #line for x in f: #line by line print(x)
Close Files
Syntax
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Write to an Existing File
- To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file "w" - Write - will overwrite any existing content
Syntax
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
Create a New File
- To create a new file in Python, use the open() method, with one of the following parameters:
"x" - Create - will create a file, returns an error if the file exist "a" - Append - will create a file if the specified file does not exist "w" - Write - will create a file if the specified file does not exist
- Syntax
f = open("myfile.txt", "x")
Delete a File
- To delete a file, you must import the OS module, and run its os.remove() function:
Syntax
import os
os.remove("demofile.txt") </pre>.
Check if file exists, then delete it:
import os if os.path.exists("demofile.txt"): os.remove("demofile.txt") else: print("The file does not exist")
Delete Folder
- To delete an entire folder, use the os.rmdir() method:
- Syntax
import os os.rmdir("myfolder")