|
|
|
|
Python SQL Server |
|
|
|
About |
In this tutorial, you will learn about Python basics and a set of built-in methods that you can use to store data. Storing simple data in lists, Dictionary, tuple etc is the first step toward efficiently working with huge amounts of data.
You can practice with the codes in this tutorial using Jupyter notebook. You can download Jupyter (Anaconda) notebook from here
Jupyter Notebooks offer a good environment for using pandas to do data exploration and modeling, but pandas can also be used in text editors just as easily.
Jupyter Notebooks give us the ability to execute code in a particular cell as opposed to running the entire file.# Other programming languages uses {}, ; etc to indicate block of codes. In Python however,the indentation is very important.
# Python uses indentation to indicate a block of code.
# Example 1: This is a valid Python code. Note the indentation before print.
if 5 > 2:
print("Five is greater than two!")
# Example 2: This contains 2 blocks of codes because of the two separated IF statement. Note that for each code, as long as the
# space is ONE or MORE the code will be valid.
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
# Example 3: This is not a valid Python code. Note that there is no indentation before print.
# Comment out and execute to see the error.
#if 5 > 2:
#print("Five is greater than two!")
# Example 4: You have to use the same number of spaces in the same block of code, otherwise Python will give you an error: Note
# that this is just one block of code ie one if statement.
# Comment out and execute to see the error.
#if 5 > 2:
#print("Five is greater than two!")
#print("Five is greater than two!")
# Example 5 : Please note that indentation is not needed when you are running an output immediately after variable declaration.
# Example 5 is valid while example 6 is not
# let's declare variable x as awesome
x = "awesome"
print("Python is " + x)
# Example 6 : Not valid
# Comment out and execute to see the error.
#x = "awesome"
#print("Python is " + x)
Variables are containers for storing data values. Unlike other programming languages, Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. By using = sign. 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). A variable name cannot contain space ie my name : this is not a valid variable.
# Example 1: assign value of 7 to x variable and value of Mark to y variable: Note that there is no indentation when you call
# the 2 prints function.
x = 7
y = "Mark"
print(x)
print(y)
# Example 2: Python allows you to assign values to multiple variables in one line: I won't recommend variables declaration this
# way.
x , y, z = 6 , "Johnson" , 9 # this line is the same as x = 6, y = "Johnson" , z = 9
print(x)
print(y)
print(z)
# You can assign the same value to multiple variables in one line:
x = y = z = "The value for x,y and z is the same"
print(x)
print(y)
print(z)
# Example 3: To combine both text and a variable, Python uses the + character: For this to work, the combined object must be the
#same data type
test = "Awesome"
print( "The value assigned to test variable is " + test)
# Example 4: this combination will fail without casting
# Comment out and execute to see the error.
#a = 4
#print("My variable string value is " + a)
# To correct example 4 above you can either cast variable a as string by using a = str(4) or a = "4"
a = str(4)
print("My variable cast value is " + a)
a = "4"
print("My variable string value is " + a)
a = 4
print("My variable string value is " + str(a))
# When the combined variables are string, the output is concatenated but if the combining variables are numbers, mathematical
# operation is carried out.
# this concatenate the 2 variables
x = "I am letter x ,"
y = "I am letter y"
print(x + y )
# this adds the 2 variables
x = 50
y = 100
print(x + y )
IT IS EXTREMELY IMPORTANT TO NOTE THAT ALL VARIABLES ARE GLOBAL UNLESS DECLARED INSIDE A FUNCTION. ALL THE VARIABLES IN THE EXAMPLES ABOVE ARE ALL GLOBAL.
THAT IS, YOU CAN CALL THEM FROM ANY PART OF THE CODE. A VARIABLE DECLARED INSIDE A FUNCTION IS LOCAL TO THAT FUNCTION. THAT IS, YOU CAN ONLY USE IT INSIDE THAT FUNCTION.IF YOU WANT TO USE IT OUTSIDE THE FUNCTION, THEN YOU MUST TURN IT FROM LOCAL VARIABLE TO GLOBAL VARIABLE BY USING THE KEYWORD, global BEFORE THE VARIABLE ie global a where a is the variable name.
# Example 5: This is a good example of creating a global variable x and using it inside a function. Please note that in Python a
# function is defined using the def keyword:
# Also note that you do not preceed the global variable x with the keyword global. The keyword global is only needed if you want
# to convert your local variable that is created inside a funtion to a global variable.
# Note that when you create a function, you must call that function otherwise, the codes after the function declaration will not
# be executed. Test this by commenting out #myfunc(). You call your function without indentation.
x = "really awesome"
def myfunc():
print("Python is " + x)
myfunc()
# Example 6, In this example, the first x is global variable while the second x declared inside the function is local. The first
# print inside the function will call the local x while the second print outside the function will call the global variable x.
x = "I am global"
def myfunc():
x = "I am local"
print( x)
myfunc()
print( x)
# Example 7, In this example, the first x is global variable while the second x is now turned from local to global.
# Since both are now global, the second x simply changed the value of the first x.
x = "I am global"
def myfunc():
global x # note you first declare with the keyword global and then assign value as in next line below
x = "I am now global and i've changed the value of the first global x. "
print( x)
myfunc()
print( x)
# This is string data type
x = "Hello World"
print(x)
print(type(x))
# This is int data type
x = 20
print(x)
print(type(x))
# This is float data type
x = 20.5
print(x)
print(type(x))
# This is list data type
x = ["pepper", "banana", "orange"]
print(x)
print(type(x))
# This is tuple data type
x = ("pepper", "banana", "orange")
print(x)
print(type(x))
# This is range data type
x = range(6)
print(x)
print(type(x))
# This is dictionary data type
x = {"name" : "John", "age" : 36}
print(x)
print(type(x))
# This is set data type
x = {"apple", "honey", "sugar"}
print(x)
print(type(x))
# This is boolean data type
x = True
print(x)
print(type(x))
# This is byte data type
x = b"Hello"
print(x)
print(type(x))
# PYTHON CASTING
a = 1 # a is of type integer
a = float(1) # cast a as float
print(a)
b = 2.0 # b is of type float
b = int(b) # cast b as an integer
print (b)
c = 3.0 # c is of type float
c = str(c) # cast c as a string
print(c)
d = "4" # d is a string
d = int(d) # cast d as an integer
print(d)
# The double equals sign "==" is used to check whether the values to the right and left are equal to one another
# The sign "!=" is used to check whether the values to the right and left are not equal to one another
# 'and' , 'or', > , < , <=, >= are also a valid conditions
a = 100
b = 2
c = a/b
d = a* b
print(a == 200)
print( c ==50)
print(a == 100 and b == 2)
print(a == 100 or b == 7)
print(a > 200)
print(a < 200)
print(a <= 99)
print(a >= 99 and d == 200)
print(a >= 99 and a < 200)
if a > b :
print("a is greater than b")
else :
print("a is not grater than b")
# Get subset of a string. You use [:]. In the example below, you get the first character in the string starting at position 2
# through 5. Note that the character in 5th string will be excluded. You start counting from zero. ie in "Hello" H is the first
# character, followed by e as the second character.
# Example 1
b = "Hello, World!"
print(b[2:5])
# Get the characters from position 5 , starting the count from the end of the string: Note that the character in -2 (postion 2
# from the back) string will be excluded. The counting from back start at 1 not zero.
# Example 2
b = "Hello, World!"
print(b[-5:-2])
# Example 3 : Give me the first 5 characters starting at 0
b = "Hello, World!"
print(b[:5])
# To get the length of a string, use the len() function.
a = "Hello, World!"
print(len(a))
# The strip() method removes any whitespace from the beginning or the end
# strip() example
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
# The lower() method returns the string in lower case
# lower() example
a = "Hello, World!"
print(a.lower())
# The upper() method returns the string in upper case:
# upper() example
a = "Hello, World!"
print(a.upper())
# get rid of whitespace and then turn to lower case
a = " Hello, World. No WHITESPACE IN LOWERCASE "
a = a.strip()
print(a.lower())
# The replace() method replaces a string with another string:
# replace example: replace H with J
a = "Hello, World!"
print(a.replace("H", "J"))
# The split() method splits the string into substrings if it finds instances of the separator you provided.
# split() example
a = "Hello, World!. The names are John, Michael, Ade , Love and Funmi"
print(a.split(","))
# CHECK STRING : To check if a certain phrase or character is present in a string, we can use the keywords in or not in.
# Example : Check if the phrase "ain" is present in the following text:
txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x)
# Example : Check if the phrase "ain" is not present in the following text:
txt = "The rain in Spain stays mainly in the plain"
x = "ain" not in txt
print(x)
# concatenate a and b and separate by spsce.
a = "Hello"
b = "pretty"
c = a + " , " + b
print(c)
## Lists can contain any kind of objects, as long as they're between square brackets []
cities = ["Tokyo",'Los Angeles','New York','San Francisco']
print(cities)
## lists are zero-indexed, meaning the first item has an index of 0
## Let's get the second item in the list
print (cities[1])
# Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc
thislist = ["water", "honey", "sugar"]
print(thislist[-2])
# Range : Return the third, fourth, and fifth item: Note that the search will start at index 2 (included) and end at index 5
# (not included)
# .ie melon will be excluded
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
# This example returns the items from the beginning to "orange": Note that item in index 4 is excluded.
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
# This example returns the items from "cherry" and to the end:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
# This example returns the items from index -4 (included) to index -1 (excluded)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
# Remember that Lists is changeable. Let's change the second item name from banana to blackcurrent
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
# To determine if a specified item is present in a list use the "in" keyword: Check if "apple" is present in the list:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
#Check if "appless" is present in the list
thislist = ["apple", "banana", "cherry"]
if "appless" not in thislist:
print("No, appless' is not in the fruits list")
# To determine how many items a list has, use the len() function:Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
# To add an item to the end of the list, use the append() method: Add orange to the end of the list.
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
# To add an item at the specified index, use the insert() method: Insert orange at the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
# Remove Item : There are several methods to remove items from a list:
# The remove() method removes the specified item: This removes banana from the list
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
# The pop() method removes the specified index, (or the last item if index is not specified):This removes banana
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
# This removes cherry being the last item because we do not specify any index with pop() method.
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
# Delete banana from the list
thislist = ["apple", "banana", "cherry"]
del thislist[1]
print(thislist)
# The del keyword can also delete the list completely: Try not to use this method because it might give an error. Use clear()
# instead.
thislist = ["apple", "banana", "cherry"]
del thislist
# The clear() method empties the list:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
# Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
# Make a copy of a list with the list() method: You can also use this method to change list to tuple or set by calling tuple or
# set instead of list
thislist = ["apple", "banana", "cherry","cucumber"]
mylist = list(thislist)
print(mylist)
# Joining 2 lists together. You can use + or extend() method.
# Use + to add list2 to list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3, 4]
newlist = list1 + list2
print(newlist)
# Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3 ,4 ,5]
list1.extend(list2)
print(list1)
# A tuple is a collection which is ordered and UNCHANGEABLE. In Python, tuples are written with round brackets.
# Just like list:
# You can access tuple items by referring to the index number, inside square brackets:
# Negative indexing means beginning from the end, -1 refers to the last item
# You can specify a range of indexes by specifying where to start and where to end the range
# To determine if a specified item is present in a tuple use the "in" keyword
# To determine how many items a tuple has, use the len() method
# This is a tuple
thistuple = ("apple", "banana", "cherry")
print(thistuple)
# But you cannot change tuple Values
# Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.
# Example: let's change the value of apple in the tuple to cucumber
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") # this is tuple
# Comment the line below out and execute to see the error.
#thistuple[0] = "cucumber" # change apple to cucumber
print(thistuple)
# But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.
# Example: let's change the value of apple in the tuple to cucumber
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") # this is tuple
thistuple = list(("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")) # change tuple to list
thistuple[0] = "cucumber" # change apple to cucumber
newlist = tuple(thistuple)
print(newlist)
# similar method above can be use to add an item or delete an item from a tuple. You need to convert to list, make your changes
# and then convert back to tuple.
# To add an item at the specified index, use the insert() method: Insert orange at the second position:
thistuple1 = ("apple", "banana", "cherry")
thistuple1 = list(("apple", "banana", "cherry"))
thistuple1.insert(1, "orange")
thistuple = tuple(thistuple1)
print(thistuple1)
# To create a tuple with ONLY ONE item, you will add a comma after the item, otherwise Python will not recognize it as a tuple.
# One item tuple, remember the commma:
thistuple = ("apple",)
print("This is a " + str(type(thistuple)))
#NOT a tuple
thistuple = ("apple")
print("This is a " + str(type(thistuple)))
# A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
# Note: Sets are unordered, so you cannot be sure in which order the items will appear.
# You cannot access items in a set by referring to an index, since sets are unordered the items has no index
# This is a set
thisset = {"apple", "banana", "cherry"}
print(thisset)
# Check if "banana" is present in the set:
thisset = {"apple", "banana", "cherry"}
if "banana" in thisset :
print("banana in thisset")
# Once a set is created, you cannot change its items since you don't kmow the order, but you can add new items using add() or
# update().
# Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
# Add multiple items to a set, using the update() method:
thisset = {"apple", "banana", "cherry"}
thisset.update({"orange", "mango", "grapes"})
print(thisset)
# To determine how many items a set has, use the len() method just like in list and tuple:
# To remove an item from the set use remove() or discard() method. Note that remove will give an error if the item to be removed
# is not in the set. discard will not give an error.
# using remove
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
# using discard
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
# You can also use the pop() method to remove an item, but this method will remove the last item. You cannot use index with
# pop() for set.
# You can use clear() to clear the content of the set
# You can use delete(), to delete the set.
# Join 2 sets together: Note: Both union() and update() will exclude any duplicate items.
# The union() method returns a new set with all items from both sets:
set1 = {"a", "b" , "c",3}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
# The update() method inserts the items in set2 into set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3 }
set1.update(set2)
print(set1)