Python Basics

01. Overview

Python is a dynamic programming language created by Guido Van Rossum in the late 1980s. It is good for quick turn around and automation since there’s no code compilation taking place. Python is case sensitive. Python is complete open source language. Python has wide variety of application from Machine Learning, Hardware & Micro-controllers, Web Development and Scripting.

  • Dynamic Language
  • Simple to Use, Efficient
  • Efficient High Level Data Structures (Batteries Included)
  • Object Oriented

Python Style Guide


02. Basic Data Types

Variables and DataTypes

Python variables can’t start with with a number. In general, they’re named all lower case, separated by underscores. Unlike other languages, that name their variables with camelCase.

  • Python Standard Data Types
    • Numbers
      • Integer
      • Float
      • Complex Numbers
    • String
    • List
    • Tuple
    • Dictionary
  • In python you don’t have to declare variables types explicitly.

# String

welcomeMessage = 'Welcome !! '
user = "Jon Doe"

# These are all integers
x = 4
y = -193394
z = 0

# These are all floats
x = 5.0
y = -3983.2

# This is a complex number
x = 42j

# List
userHobbies = ['Chess', 'Photography', 'Reading']
print (userHobbies)

# Tuple
userAddress = ('1234 Jon Doe Street, Quincy, Boston', '02467')
print (userAddress)

# Dictionary
userDetails = {'education': 'Massachusetts Institute of Technology', 'volunteering': 'Habitata for Humanity', 'karmaPoints': 100}
print (userDetails)


  • Represented via Single Quotes ' (Single Quotes) or " (Double Quotes)
  • Long String using """
  • Common Methods
    • upper()
    • lower()
    • count()
    • replace()
    • split()
  • Strings are immutable, which means once you create a variable they cannot be changed
msg = 'Hello World'
anotherMsg = "Hello User"
print (msg)
print (anotherMsg)

# String Functions
firstName = 'John'
lastName = 'Goldo'
fullName = firstName + ' ' + lastName
print (fullName)
print ("In Uppercase -", fullName.upper())
print ("In Lowercase -", fullName.lower())
print ("Counting occurances of o -", fullName.count('o'))
print ("Using Replace -", fullName.replace('John', 'Bill'))
print ("Welcome - {0} from {1}".format(fullName, "ART"))
print ("Welcome - %s from %s" %(fullName, 'ART'))

# Using fStrings
print (f"Welcome - {fullName} from ART")


  • Ordered Collection of Items
  • Squared Brackets [] are used to define a list
  • Comma , is used to separate individual items in the list
  • Elements inside List are accessed using Index or Within Loop
  • Common Methods
    • my_list.append(item) - Add to the end
    • my_list.insert(pos,item) - Insert at position
    • my_list.pop() - Remove last item
    • my_list.remove(item) - Removes first instance of the item
    • item in my_list - Check value exists in List
    • len(my_list) - Returns number of items in a List
    • my_list.count(item) - Count of Items
users = ['John', 'Adam', 'Bob']
print (users)

# Size of List
print (len(users))

# Getting First Item in List
print (users[0])

# Getting Last Item in List
print (users[-1])

# Looping Through List
for user in users:
    print ('Hello {0} !'.format(user))

# Adding Item to List

# Making Numerical List
squares = [x**2 for x in range(1, 11)]

# Copying a List
usersCopy = users[:]

# Checking
check = 'Nabin' in usersCopy


  • Hash-Table (Key-Value Pair)
  • keys() - Returns List of Keys
  • values() - Returns List of Values
# Initiating a Dictionary
nepal = {'name': 'Nepal', 'capital': 'Kathmandu'}
print (nepal)

# Store Item in Dictionary
nepal['area'] = 147181

# List All Keys
print (nepal.keys())

# List All Values
print (nepal.values())

# Using GET
print (nepal.get('name'))
print (nepal.get('gdp'))
{'name': 'Nepal', 'capital': 'Kathmandu'}
dict_keys(['name', 'capital', 'area'])
dict_values(['Nepal', 'Kathmandu', 147181])

03. Control Statement

If / Else If Statement

num = 21
if num == 20:
    print 'The Number is 20'
elif num > 20:
    print 'Number is Greater Than 20'
elif num < 20:
    print 'Number if Less Than 20'
    print 'Not a Valid Number'

While Statement

print 'Using While Statement'
current_value = 1
while current_value <= 5:
  print current_value
  current_value += 1

For Statement

words = ['Happy', 'Empathy', 'Grateful']
for w in words:
  print (w, len(w))
  • break breaks out of smallest enclosing for or while loop

04. Functions

Functions help us organize our code in a way that’s reusable, and accept arguments and defaults where needed.

  • Keyword def specifies function definition
  • Support for default arguments, Arguments without defaults are required arguments
  • A function can accept all of one type or the other, but arguments need to go in a specific order.
def sayHello(user="Bob"):
  """Display Message to Say Hello"""
  print('Hello, %s' %user)

def add_numbers(x, y):
    """ Add Two Numbers"""
    return x + y

sum = add_numbers(5,5)

05. Python Modules

Python modules are python libraries which can be subsequently imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level). The file name is the module name with the suffix .py appended.


def say_hello(name):
  print ("Hello " + name)
import hello

def main():

if __name__ == '__main__':

06. References