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 has an incredible rich fully features standard library, as well as the PyPi Package Index for 3rd party package.

Python Style Guide

#PEP8 is Python coding standard, that sets guidelines for how our Python code should look like

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.
# 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
# String
user = "Jon Doe"
welcomeMessage = """
                 Welcome !! Users. I would like to welcome you with Long multi-line strings that can be represented in between Triple Quotes. Whitespace will be part of the string
                 """

greetings = f"Hello, {user}"
# 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)

String

  • 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")

Lists

  • 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
Syntax Description
my_list.append(item) Add item to the end of the list
my_list.insert(pos,item) Insert item at position
my_list.pop() Remove last item
my_list.remove(item) Removes first item of the list
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
users.append('Nabin')

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

# Copying a List
usersCopy = users[:]

# Checking
check = 'Nabin' in usersCopy

Dictionaries

  • 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])
Nepal
None

03. Loops and Control Statement

For Statement

words = ['Happy', 'Empathy', 'Grateful']
for w in words:
  print (w, len(w))

for num in range(5):
  print(f"The number is: ${num}")

break breaks out of smallest enclosing for or while loop

If Statement and Conditionals

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'
else:
    print 'Not a Valid Number'

While Statement

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

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.
# Positional Arguments are required
def add_numbers(x, y):
    """ Add Two Numbers"""
    return x + y

# Keyword Arguments with default values
def sayHello(user="Bob"):
  """Display Message to Say Hello"""
  print('Hello, %s' %user)

sayHello('Jon')
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.

# hello.py

def say_hello(name):
  print ("Hello " + name)
# main.py
import hello

def main():
  hello.say_hello('Aayush')

if __name__ == '__main__':
  main()

06. References