Python 101
A concise tutorial to a concise language
YDP
21st August 2016
Contents
- Background
- Python Variables, Types & Lists
- Basic Operators
- String Formatting & Operations
- Conditions & loops
- Functions
- Classes and Objects
- Files - I/O operations
- Dictionaries, tuples
- Modules & Packages
A quick background
- Multipurpose
- Web, GUI, Scripting
- Object oriented
- Interpreted
- Focus on readability & productivity
Is Python used enough?
Who uses Python?
- NASA
- ebay
- Quora
- YouTube
- Mozilla Firefox
Hello World!
print "Hello World!"
hello.py
Variables & Types
- Numbers
- Integers
- Float
- Strings
- Null
one = 1
two = 2
three = one + two
hello = "hello"
world = "world"
helloworld = hello + world
Mixing operators between numbers and strings is not supported
Lists
- Similar to arrays, but heterogeneous
- Appending to a list
- Extending a list
- Accessing list items
mylist = []
mylist.append(1)
mylist.append("hello")
print(mylist[1])
colors = ['red', 'brown', 'blue', 'green', 'white']
colors[1]
#brown
colors[2:4]
#['blue', 'green']
Basic Operators
- Addition, multiplication,
- Subtraction, division
- Modulus (%)
- Power operator
- Strings with operators
- Lists with operators
number = 1 + 2 * 10 / 5.0
remainder = 11 % 5
squared = 5 ** 2
cubed = 5 ** 3
#string operations
helloworld = "hello" + "world"
lotsofhellos = "hello" * 10
#list operations
even_numbers = [2,4,6,8]
odd_numbers = [1,3,5,7]
all_numbers = odd_numbers + even_numbers
print [1,2,3] * 3
Exercise
The Meal
You've finished eating at a restaurant, and received this bill:
-
Cost of meal: $44.50
-
Restaurant tax: 6.75%
-
Tip: 15%
You'll apply the tip to the overall cost of the meal (including tax). Display the tip calculated.
Basic Operators
- Addition, multiplication,
- Subtraction, division
- Modulus (%)
- Power operator
- Strings with operators
- Lists with operators
number = 1 + 2 * 10 / 5.0
remainder = 11 % 5
squared = 5 ** 2
cubed = 5 ** 3
#string operations
helloworld = "hello" + "world"
lotsofhellos = "hello" * 10
#list operations
even_numbers = [2,4,6,8]
odd_numbers = [1,3,5,7]
all_numbers = odd_numbers + even_numbers
print [1,2,3] * 3
String formatting
- C style formatting
- The % operator
- () parenthesis
- Argument specifiers:
- %s - Strings
- %f - floating point
- %d - integers
- %.<digits>f - Floating point number with fixed digits
name = "John"
age = 23
print "%s is %d years old." % (name, age)
# John is 23 years old
# This prints out: A list: [1, 2, 3]
mylist = [1,2,3]
print "A list: %s" % mylist
String Operations
- Wide variety of operations like:
- len
- index
- count
- slicing
- reverse
- [start:stop:step]
- upper/lower
- split
s = "Hey there! what should this string be?"
print "Length of s = %d" % len(s)
print "The first occurrence of the letter a = %d" % s.index("a")
print "a occurs %d times" % s.count("a")
# Slicing the string into bits
print "The first five characters are '%s'" % s[:5] # Start to 5
print "The next five characters are '%s'" % s[5:10] # 5 to 10
print "The twelfth character is '%s'" % s[12] # Just number 12
print "The characters with odd index are '%s' " %s[1::2] #(0-based indexing)
print "The last five characters are '%s'" % s[-5:] # 5th-from-last to end
# Convert everything to uppercase
print "String in uppercase: %s" % s.upper()
# Convert everything to lowercase
print "String in lowercase: %s" % s.lower()
# Check how a string starts
if s.startswith("Str"):
print "String starts with 'Str'. Good!"
# Check how a string ends
if s.endswith("ome!"):
print "String ends with 'ome!'. Good!"
# Split the string into three separate strings,
# each containing only a word
print "Split the words of the string: %s" % s.split(" ")
Exercise
You will need to write a format string which prints out the data using the following syntax:
Hello John Doe! Your current balance is 53.44$.
- Boolean values True and False
- Conditions help us select from options
- what if?
- == and !=
- The in operator
- The is operator v/s == operator
- The not operator
- Indentation
name = "Ram"
if name in ["Ram", "Bharat"]:
print "Your name is either Ram or Bharat."
people = 30
cars = 40
if cars > people:
print "We should take the cars."
elif cars < people:
print "We should not take the cars."
else:
print "We can't decide."
print not False # Prints out True
Conditions
Loops
- Loops help us iterate over a piece of code
- for loop
- while loop
- Iterating over a list of items
- Iterating over a sequence of numbers
primes = [2, 3, 5, 7]
for prime in primes:
print prime #prime acts as iterator
# we can also build lists, first start with an empty one
elements = []
for i in range(0, 6):
elements.append(i)
for x in range(3, 6):
print x
Loops - while
- Repeats as long as a certain Boolean condition is met
- break
- continue
- The else part for loops
count = 0
while count < 5:
print count
count += 1
# Prints out only odd numbers - 1,3,5,7,9
for x in xrange(10):
# Check if x is even
if x % 2 == 0:
continue
print x
Console Input
#Two types - input() and raw_input()
username = raw_input('What is your name? ')
#only for strings
myage = input("What is your age? ")
#all types except string
Exercise - Pig Latin
In this exercise, you have to write a Pig Latin translator.
Pig Latin is a language game, where you move the first letter of the word to the end and add "ay." If a word begins with a vowel, just add “way” in the end. So "Python" becomes "ythonpay." “object” becomes “objectway”, and so on.
To write a Pig Latin translator in Python, here are the steps we'll need to take:
-
Ask the user to input a word in English.
-
Convert the word from English to Pig Latin.
- Display the translation result.
Functions
- Functions are a convenient way to divide your code into useful blocks
- Defining a function
- Passing arguments
- Returning from a function
- Calling a function
def my_function():
print "Hello there!"
def sum_two_numbers(a, b):
return a + b
#Prints "Hello there!"
my_function()
x=sum_two_numbers(10,15)
#x now holds the sum of 10 and 15
print x
Exercise - Twin Primes
Twin prime numbers are a pair of prime numbers that have a difference of 2 between them. For example, (3,5), (5,7), (11,13), (29,31), etc.
Given a number n, display the first n pairs of twin primes
To do the above,
-
Create a function prime(n) that checks if a number is prime or not
-
Find a prime number and check if a twin prime exists for it
- Find n such pairs
Classes and Objects
- Objects are an encapsulation of variables and functions
- Class is a template for an object
- Defining a class
- Creating objects
- Accessing object variables and functions
class MyClass(object):
variable = "blah"
def function(self):
print "This is a message inside the class."
myobjectx = MyClass()
myobjecty = MyClass()
myobjecty.variable = "yackity"
print myobjectx.variable # This would print "blah".
print myobjecty.variable # This would print "yackity".
myobjectx.function()
print type(myobjectx)
Exercise
In this exercise, we are going to create a banking system.
Create a class called Account that represents a customer account. It must contain the following variables and functions:
- Account Type- savings, personal or corporate
- User name- A string
- Account number- A number that uniquely identifies each account. This must be auto-generated
- Current balance- a floating point value that represents the current balance
- displayBal()- A function that displays the current balance
- DepositCash(amt) - A function that adds ‘amt’ to the current balance and updates it. In the case of savings accounts, the current balance cannot fall below 500
- DrawCash(amt) - A function that carries out cash withdrawals of ‘amt’ from the current balance. The funds must first be checked and then updated
Create two objects of type Account:
- ‘Acct1’ is a savings account that belongs to “Mishra” and has a current balance of Rs. 10000.00. He makes a deposit of Rs. 1500.00 into it, followed by a withdrawal of Rs. 7000.
- ‘Acct2’ is a personal account that belongs to “Chopra” and has a current balance of Rs. 5000. He makes 2 withdrawals of Rs. 4000 and Rs. 2000 each.
File I/O operations
- Opening and closing a file
- Reading from a file
- Writing to a file
- Appending to a file
f = open("test.txt", "r")
#opens file with name of "test.txt" for read-only
print(f.read(10))
#Reads 10 characters and prints them or the entire line if number of characters is not specified
print(f.readLine())
#Reads an entire line and prints it
my_list = [i**2 for i in range(1,11)]
# Generates a list of squares of the numbers 1 - 10
f = open("output.txt", "w")
#opens file with name of "output.txt" in read-write
for item in my_list:
f.write(str(item) + "\n")
f.close()
f = open("output.txt", "a")
#opens file with name of "output.txt" in append mode
f.write("Goodbye!")
#Appends "Goodbye!" to the end of the file
f.close()
Dictionaries
- Like arrays, but but works with keys and values instead of indexes
- Creating dictionaries
- Iterating
- Removing values
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
"Jake" : 998833221
}
#Prints all the phone numbers in the dictionary
for name, number in phonebook.iteritems():
print "Phone number of %s is %d" % (name, number)
#Deletes the entries of John and Jake from the phonebook
if "John" not in phonebook:
print "John is not listed in the phonebook."
else:
del phonebook["John"]
phonebook.pop("Jake")
Exercise
Given a list containing the key-words searched on Google by a user, count the number of occurrences of each key-word and display in the form of an array
For example, given this input -
Key_word_list = [‘cricket’, ‘india’, ‘football’, ‘cricket’, ‘yahoo’, ‘google’, ‘india’, ‘cricket’]
We should get this as the output:
cricket - 3, india - 2, football - 1, yahoo - 1, google -1
Tuples
- Like lists, but cannot be changed
myList = [1,2,3]
myList.append(4)
print (myList)
myTuple = (1,2,3)
print (myTuple)
myTuple.append(4)
#Generates an error!
print (myTuple)
Modules
- A module is a .py file containing Python definitions and statements
- Importing modules
- Writing your own modules
# Fibonacci numbers module
# write Fibonacci series up to n
def fib(n):
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
# return Fibonacci series up to n
def fib2(n):
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
>>> import fibo
>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'
Packages
- Packages contain multiple packages and modules themselves
- For ex, the module name A.B designates a submodule named B in a package named A
- Like directories, but with a twist
#Package foo
#Defines packages & modules in foo
__init__.py:
#a list of packages and modules
__all__ = ["bar"]
>>> import foo.bar
>>> from foo import bar
Thank You!
Questions?
Resources used:
Python-101
By Abhiram Ravikumar
Python-101
Python Tutorial for Prakat- Day 1
- 2,644