Tech Notes

Learn Python — Quick Notes

Quick reference notes for Python beginners: printing, strings, lists, dictionaries, loops, functions, dates and classes.

This article is for anyone starting out with Python. It’s also a quick reference for keywords, lists, data types and classes. Learn Python quickly ;)

Note: these notes use Python 2 syntax (for example, print "Hello" without brackets). In Python 3, print is a function, so write print("Hello"), and use input() instead of raw_input().

1. Print something

print "Hello World"
 
x = 7 
print x 
 
str  = "Technology World"
print str
 
# Print float value - adjust for 2 decimal places
print("%.2f" % sum )
 
fruit = "Apple"
print "A for  %s." % (fruit)

2. Console input

name = raw_input("What is your name?")
print name

3. Boolean variables

x = True
y = False

4. Comments

# Single line
 
""" 
Multiple lines 
comments in Python.
 
Use triple quotes
 
"""

5. Operators

# Add
c = a + b
 
# Subtract
c = a  - b
 
# Multiply
c = a * b
 
# Divide 
c = a / b
 
# Mod 
c = a % b 
 
# Exponent - a to the power b
c  = a ** b

6. Strings

# Prints 3rd letter of a string 
print "TECH"[2]
 
# Length of a string  - Prints 4
print len("TECH")
 
#  To Lower - Prints tech
print "TECH".lower()
 
#  To Upper - Prints TECH
print "tech".upper()
 
# To get string value
val = 5.33 
# prints "5.33"
print str(val)
 
# Concatenate two strings 
print "Technology " + "and" + " Digital media"
 
print "Total value = " + str(33.33)
 
temp_string = "digital"
 
# The first three characters of temp_string
temp_string[:3]

7. Lists

# List of numbers 
numbers = [11, 10, 1, 2, 3, 4 ]
 
# Printing second element 
print numbers[1]
 
# Sort list
numbers.sort()
 
# Sum of numbers 
print sum(numbers)
 
# List of strings 
fruits = ["orange", "apple", "mango", "plum", "peach" ]
 
# To get the length of the list 
print len(fruits)
 
# Printing second element 
print fruits[1]
 
# Adding another element to the list 
fruits.append("banana")
 
# Slice list 
# [start:end:stride]
 
# Prints [1, 3]
print numbers[2:6:2]
 
# Reverse list 
print numbers[::-1]
 
# The first and second elements
fruits[0:2]  
 
# Third and fourth elements
fruits[2:4]              
 
# The last two items 
fruits[4:6]              
 
# Get list index
print fruits.index("mango")
 
# Replace an element in an index 
fruits.insert(3, "strawberry" )
 
# Remove an item 
fruits.remove('mango')
 
# Join two lists 
list1 = [1,2,4,5]
list2 = [6,7,8,9]
 
new_list = list1+list2
 
# join string array as string 
print  " " . join(fruits)
 
# Build list 
even_numbers = [i for i in range(100) if i % 2 == 0]

8. Dictionary

fruits_count = {'apple': 34, 'orange': 55, 'mango': 6}
print fruits_count['apple']
 
temp = { "tech": "Technology and Digital media"}
 
# Dump dictionary 
fruits_count.items()
fruits_count.keys()
fruits_count.values()

9. Loops

# For loop 
for num in numbers:
    print num
 
for fruit in fruits:
    print fruit
 
# Looping through a string
sentence = "I love technology and digital media"
 
# Print the letter in a string if it is equal to "t"
for l in sentence:
    if l == "t":
        print l
 
# With dictionaries 
fruits_count = {'apple': 34, 'orange': 55, 'mango': 6}
for key in fruits_count:
    print key + " " + fruits_count[key]
 
# For loop to iterate with index and element 
for index, element in enumerate(fruits_count):
    print index+1, element
 
# For loop for multiple arrays
list_x = [1,2,4,5,9]
list_y = [6,7,8,9]
 
for x, y in zip(list_x, list_y):
     if  x == y :
         print x
     else:
        print y
else: 
  print "End of loop"
 
# While loop
i = 0  
while i <= 9:
    print i
    i += 1
# With break 
while i <= 9:
    print i
    if i == 6 
       break
    i += 1
 
# With else  
while i <= 9:
    print i
    if i == 6 
       break
    i += 1
else:
  print "Exit loop"

10. Comparators

# Equal to (==)
if a == b:
   print True
 
# Not equal to (!=)
if a != b:
   print True
 
# Less than (<)
if a < b:
   print True
 
# Less than or equal to (<=)
if a <= b:
   print True
 
# Greater than (>)
if a > b:
   print True
 
# Greater than or equal to (>=)
if a >= b:
   print True

11. Control flow

# if else syntax 
 
if myVar == "tech" or myVar == "techno":
   print "Technology"
elif myVar == "And" and pre == "A":
   print "and"
else:
   print "Digital"
 
if not a > b:
   print "a is not greater than b "
 
if a > b and not b == 0:
   print "a is not greater than b and b is not zero"

12. Functions

def add(a,b):   
    return a+b
 
print add(5,4)
 
# Pass a list of arguments 
def get_max(*args):
    return max(args)
 
# Pass a list of arguments 
get_max(0, -2 , -4, 5 , 7 )
 
# Function to return the absolute value 
def get_abs(val):
    return abs(val)

13. Built-in functions

# Returns data  type  
type(var) 
 
# Prints int 
print type(5)
 
# Prints str
print type("Tech")
 
# Returns max from arguments  
max()
print max(2,3,5,6)
# Returns min from arguments  
min()
print min(2,3,5,6)
 
# Return absolute value 
abs()
 
# Array of numbers from 0 to 9 
range(0,10) 
 
# Generates a random integer between 0 and 999  
randint(0, 999)
 
# Round for two decimal numbers 
round(12.5489, 2)

14. Anonymous functions

numbers = [11, 10, 1, 2, 3, 4 ]
# Filers all the numbers divisible by 2 
print filter(lambda x: x % 2 == 0, numbers )
 
# lambda - Writes functions that does not bound a  name.

15. Importing the time library

from datetime import datetime
from module import *
 
import math 
 
# List everything in a module 
all = dir(math)
print  all

16. Date and time

from datetime import datetime
 
# Current date 
current_date = datetime.now() 
print current_date
 
# Day 
current_date.day()
 
# Month 
current_date.month()
 
# Year 
current_date.year()
 
 
# Hour
current_date.hour()
 
 
# Minute
current_date.minute()
 
 
# Seconds
current_date.second()

17. Bitwise operators

# Shift Right
print 5 >> 3 
 
# Shift Left
print 4 << 2
 
# AND  
print 3 & 2 
 
# OR
print 7 | 3  
 
# XOR
print 23 ^ 12 
 
# NOT
print ~45     
 
# Convert to binary - 0b11
print bin(3)

18. Classes

class Student(object):
    # Initialize 
    def __init__(self, name, age, sex ):
        self.name = name
        self.age  = age
        self.sex  = sex
    # Short representation of the class object 
    def __repr__(self):
        return "(%d, %d, %d)" % (self.name, self.age, self.sex )
 
    def get_age(self):
        return self.age
 
    def is_male(self):
       if sex == "m"
          return True
       else 
          return False
 
stud = Student("Sarath", 30 , "London")
 
print stud 
print stud.get_age()
 
 
# Inheritance 
class University(object):   
  def __init__(self, student_id):
      self.student_id = student_id
  def get_class(self):
      return "A" 
 
  def calculate_grade(self):
      return "Super Class"
 
class Students_details(University):
  def get_grade(self):
      return "Grades not available"  
 
  # Overrides function
  def calculate_grade(self):
      return "Child Class"
 
 
obj = Students_details("STUD_123")
 
obj.get_class()
obj.get_grade()
obj.calculate_grade()