Print¶

Print an object to the console.

In [ ]:
print("Hello World")
In [ ]:
print(100)
In [ ]:
print(True)

Data Types¶

Commonly used data types.

In [ ]:
import datetime as dt # import datetime module

num = 102                   # integer
text = "Hello World"        # string
boolean = True              # boolean
date = dt.datetime.now()    # datetime
decimal = 10.2              # float

print(num)
print(text)
print(boolean)
print(date)
print(decimal)
In [ ]:
# Let's find the data type of the variables
print(type(num))
print(type(text))
print(type(boolean))
print(type(date))
print(type(decimal))
In [ ]:
print(num+num)          # addition
print(text+text)        # concatenation
print(boolean+boolean)  # addition
In [ ]:
# Convert the type of the variables
print(num)
print(type(num)) # integer

print("")
print(float(num))
print(type(float(num))) # float

print("")
print(str(num))
print(type(str(num))) # string

String data type¶

In [ ]:
str = "Hello world" # string

# all lower case
print(str.lower()) 

# all upper case
print(str.upper()) 

# capitalize
print(str.capitalize())

# title
print(str.title())

# swap case
print(str.swapcase())

# length
print(len(str))

# replace
print(str.replace("world", "class"))

# split
print(str.split(" "))

# strip
str = "   Hello World   "
print(str.strip())
In [ ]:
# More on string

# multi line string
str = """Hello, 
I am writing to you in regards to the Python class. 

Regards,
Wriju"""

print(str) 
In [ ]:
# string formatting
name = "Wriju"
age = 55
print("Hello, my name is %s and I am %d years old" % (name, age))       # old style

print("Hello, my name is {} and I am {} years old".format(name, age))   # new style

print("Hello, my name is {0} and I am {1} years old".format(age, name)) # new style, position based
In [ ]:
# find in the string
str = "Hello World"
print(str.find("World")) # 6 - position of the word "World"
print(str.find("world")) # -1 - word not found
In [ ]:
bigstr = " A quick brown fox jumps over the lazy dog "
x = "ox" in bigstr # True
print(x)
In [ ]:
# special characters in string
print("Hello \n World") # new line
print("Hello \t World") # tab
print("Hello \\ World") # backslash
print("Hello \" World") # double quote
print("Hello \' World") # single quote

Condition¶

In [ ]:
a = 10
b = 20

if a > b: 
    print("a is greater than b")
else:
    print("a is not greater than b")

    
In [ ]:
a = 10
b = 20
c = 30

if a > b:
    print("a is greater than b")
elif b > c: 
    print("b is greater than c")
else:
    print("a is not greater than b and b is not greater than c")
    
In [ ]:
# nested if statement
a = 10
b = 20
c = 30

if a > b:
    print("a is greater than b")
else:
    if b > c:
        print("b is greater than c")
    else:
        print("a is not greater than b and b is not greater than c")

Other operators are <, <=, >, >=, ==, !=

Collections¶

  • List
  • Tuple
  • Set
  • Dictionary

List - Collection¶

In [ ]:
# List collection
# list is a collection of items
# list is a mutable collection
# list is a ordered collection
# list can contain duplicate items
# list can contain different data types
# list can be accessed by index
# list can be sliced
# list can be sorted
# list can be nested

# List methods
theList = [1, 2, 6, 4, 5]
print(theList)          # print the list
print(type(theList))    # print the type of the list
print(len(theList))     # print the length of the list
print(theList[0])       # print the first item of the list
print(theList.sort())   # sort the list

theList.insert(0, 9)    # insert at the beginning
print(theList)

Tuple - Collection¶

In [ ]:
# Tuple collection

# tuple is a collection of items
# tuple is a immutable collection
# tuple is a ordered collection
# tuple can contain duplicate items

# tuple can contain different data types

# tuple can be accessed by index
# tuple can be sliced
# tuple can be nested

# Tuple methods
theTuple = (1, 2, 6, 4, 5, 5, 5, "numbers", True)
print(theTuple)         # print the tuple
print(type(theTuple))   # print the type of the tuple
print(len(theTuple))    # print the length of the tuple
print(theTuple[0])      # print the first item of the tuple

# immutable hence there will be an error. 
# Uncomment to see the error
# theTuple.add(9) 
# print(theTuple)

Set - Collection¶

In [ ]:
# Set collection

# set is a collection of items
# set is a mutable collection
# set is a unordered collection
# set can not contain duplicate items
# set can contain different data types
# set can not be accessed by index
# set can not be sliced
# set can not be nested

# Set methods
theSet = {1, 2, 6, 4, 5, 5, 5, "numbers", True} # duplicate items are removed
print(theSet)       # print the set           
print(type(theSet)) # print the type of the set
print(len(theSet))  # print the length of the set

theSet.add(10)      # add an item to the set
print(theSet)

Dictionary - Collection¶

In [ ]:
# Dictionary collection

# dictionary is a collection of items
# dictionary is a mutable collection
# dictionary is a unordered collection
# dictionary can not contain duplicate items
# dictionary can contain different data types
# dictionary can be accessed by key
# dictionary can not be sliced
# dictionary can be nested

# Dictionary methods
theDict = {
    1: "one", 
    2: "two", 
    3: "three"
}

print(theDict)          # print the dictionary
print(type(theDict))    # print the type of the dictionary
print(len(theDict))     # print the length of the dictionary
print(theDict[1])       # access by key
print(theDict.get(3))   # same as above
print(theDict.keys())   # get all the keys
print(theDict.values()) # get all the values
print(theDict.items())  # get all the items
print(theDict.pop(1))   # remove by key
print(theDict)          # print the dictionary

For loop¶

In [ ]:
# for loop
theList = [1, 2, 6, 4, 5]

for item in theList:        # item is a variable
    print(item)
In [ ]:
# for loop with range
for item in range(1, 10):       # 10 is not included
    print(item)
In [ ]:
# for loop with range and step
for item in range(1, 10, 2):    # start, end, step
    print(item)
In [ ]:
# for loop in string collection
theString = "Hello World. I am learning Python."

for item in theString:      # iterate through each character
    print(item)
In [ ]:
# break a loop upon a condition
theString = "Hello World. Hey, I am learning Python."

for item in theString:
    if item == ",":         # break the loop if comma is found
        break
    print(item)

While Loop¶

In [ ]:
# while loop

# while loop with break
i = 1
while i < 10:
    print(i)
    if i == 5:
        break        # break the loop if i is 5
    i += 1
    
In [ ]:
# while loop with continue
i = 1
while i < 10:
    i += 1
    if i == 5:
        continue     # skip the rest of the code and continue the loop
    print(i)
    
In [ ]:
# while loop with else
i = 1
while i < 10:
    print(i)
    i += 1
else:           # else will be executed when the condition is false
    print("i is not less than 10")

Function / Method¶

In [ ]:
# function with no parameter
def sayHello():
    print("Hello World")

sayHello()
In [ ]:
# function with parameter
def sayHello(name):
    print("Hello " + name)  # concatenate the name with the string

sayHello("Wriju")
In [ ]:
# function with parameter and return value
def sayHello(name):
    return "Hello " + name  # concatenate the name with the string

print(sayHello("Wriju"))
In [ ]:
# function with parameter and default value
def sayHello(name="World"):
    return "Hello " + name # concatenate the name with the string

print(sayHello())

Error handling¶

In [ ]:
# exception handling
x = 100
try:
    print(x/0)  # division by zero
except:
    print("An exception occurred")
In [ ]:
# exception handling with specific exception
x = 100
try:
    print(x/0)  # division by zero
except ZeroDivisionError:
    print("A ZeroDivisionError exception occurred. You can not divide by zero.")
In [ ]:
# exception halding with specific exception and else
x = 100
try:
    print(x/1)  # division by zero
except ZeroDivisionError:
    print("A ZeroDivisionError exception occurred. You can not divide by zero.")
else:
    print("No exception occurred")

Input¶

In [ ]:
name = input("Enter your name: ") # input from user
print("Hello " + name)

# input from user with type conversion
num = int(input("Enter a number: "))
print(num)

File Handling¶

In [ ]:
# file handling - write
f = open("test.txt", "w")   # open a file in write mode
f.write("Hello World.")     # write to the file
f.close()                   # close the file
In [ ]:
# file handling - read
f = open("test.txt", "r")   # open a file in read mode
print(f.read())             # read the file
f.close()
In [ ]:
# file handling - read in function
def readFile():
    try:
        f = open("test.txt", "r")
        print(f.read())
        f.close()
    except:
        print("File not found to read.")

readFile()
In [ ]:
# file handling - append
f = open("test.txt", "a")       # open a file in append mode
f.write(" Hello World again.")  # append to the file
f.close()

readFile()
In [ ]:
# file handling - delete
import os

try:
    os.remove("test.txt")               # delete the file
except:
    print("No file found to delete.")   # file not found

readFile()                              # as the file is deleted above, it will not be found