I ran into Python

Python is blah blah blah,

Python Documentation

Installing Python
http://toomuchdata.com/2012/06/25/how-to-install-python-2-7-3-on-centos-6-2/

Download boto
use new #python2.7 boto/setup.py install

Variable Declaration
var_name = 123

Data Types
Integer – 2 3 4
Float – 1.23 4.21
Boolean – True and False

Python Statement
If you’re familiar with JavaScript, you know that statements end with a semicolon (;). In Python, statements are separated by whitespace.
Just like you can’t toss around semicolons wherever you want in JS, you can’t throw whitespace around in Python.
Eg with Error:

def spam():
eggs = 12
return eggs
print spam()

ERR : IndentationError: expected an indented block

Eg with Correction in it:

def spam():
  eggs = 12
  return eggs

print spam()

Properly indent the code to the right by hitting the spacebar key on your keyboard four times on line 2 (before eggs) and another four times on line 3 (before return).
You should ALWAYS use 4 spaces to indent your code.

Multiline comment is just a regular phrase or sentence starting with “”” and ending with “””. No # needed at all!

Arithmetic Operators

Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Exponentiation (**)
Modulo (%)

Data Type
Strings

Example :
brian = “Hi whats up”
print brian

A string literal is a string created by literally just writing it down between quotation marks (‘ ‘ or ” “).

There is no difference between using single quotes ‘ and double quotes “. However, sometimes it is helpful to use one or the other. If we want to include an apostrophe in our string, it would be smart to use double quotes to create the string like “I’m a string”. If we want to use quotes in the string, we might want to create the string with single quote like ‘The man screamed “I love Python!” so that everyone could hear.’
‘Help! Help! I\’m being repressed!’

The Backslash is the used to escape the ‘ in I’m. Not all special characters within quotes can be taken for granted.

Each character in a string has a subscript or offset, which is a fancy way of saying it has a number attached to it. The number starts at 0 for the leftmost character and increases by one as you move character-by-character to the right. Check out the diagram in the editor!

fifth_letter = “MONTY”[4]
print fifth_letter
O/P: Y

Four commonly used String Methods:
len() : to find the length of a string, eg: len(strvariable)
lower() : to convert to lower case, eg: strvariable.lower()
upper() : to convert to uppercase, eg: strvariable.upper()
str() : The str() method returns a string containing a nicely printable representation of whatever you put between the parentheses. It makes strings out of non-strings!

Dot notation works on string literals (“The Ministry of Silly Walks”.upper()) and variables assigned to strings (ministry.upper()) because these methods are specific to strings—that is, they don’t work on anything else.

By contrast, len() and str() can work on a whole bunch of different objects (which we’ll get to later), so they aren’t tied to strings with dot notation.

If you use the + operator between two strings, it concatenates them (glues them together).
eg:
print “Spam ” + “and” + ” eggs”
O/P: Spam and eggs

str()–You’re explicitly telling Python, “Hey, I know this isn’t a string, but I want to turn it into one.” Contrast this with just putting quotes around a sequence of characters to make it a string.

Making a number into a string can let you glue together strings and numbers (which Python normally won’t allow). Check it out:
eg: print “The value of pi is around ” + str(3.14)
O/P:The value of pi is around 3.14

NOTE
we use Python version 2.7.3. This version of Python is very widely used and is the main stable version of Python. It is used in a wide range of real-world applications. However, there is also a newer version of Python called Python 3. Python 3 is slightly different from Python 2.7. One of the biggest differences is that Python 3 requires that print statement be written print( things to print ). We can achieve the same behavior in Python 2.7 by writing from __future__ import print_function on the first line of the file. In our code you will see the old way of writing print statements – print THINGS TO PRINT.

String Formatting with %
string_1 = “Camelot”
string_2 = “place”

print “Let’s not go to %s. ‘Tis a silly %s.” % (string_1, string_2)
O/P: Let’s not go to Camelot. ‘Tis a silly place.

The % string formatter replaced the %s (the “s” is for “string”) in our string with the variables in parentheses. (We could have done that by just putting “Camelot” and “place” in parentheses after the string, but we wanted to show you how it works with variables.)

The syntax went like this:
print “%s” % (string_variable)

eg:
name = raw_input(“What is your name?”)
quest = raw_input(“What is your quest?”)
color = raw_input(“What is your favorite color?”)

print “Ah, so your name is %s, your quest is %s, ” \
“and your favorite color is %s.” % (name, quest, color)
The datetime Library
On line 1, we need to have the statement:
from datetime import datetime

Importing special functionality into your programs
To Print Date in the following format:
mm/dd/yyyy
Remember that concatenation only works with strings!
print str(current_month) + “/” + str(current_day) + “/” + str(current_year)
O/P: 10/27/2013

An Example Program in Python to print date & time

from datetime import datetime

now = datetime.now()
print now

current_year = now.year
current_month = now.month
current_day = now.day
current_hour = now.hour
current_minute = now.minute
current_second = now.second
print str(current_month) + "/" + str(current_day) + "/" + str(current_year) + " " + str(current_hour) + ":" + str(current_minute) + ":" + str(current_second)
-------
O/P:
2013-10-27 14:18:43.958919
10/27/2013 14:18:43

Comparators
Equal to (==)
Not equal to (!=)
Less than (<)
Less than or equal to (<=)
Greater than (>)
Greater than or equal to (>=)

Logical Operators
and
or
not

Defining functions

def functionname():
  code
  code
  code
  return # to exit the function
#Calling the  function
functionname()

If Loop

if variable == "value" or variable == "value2":
   code
elif variable == "value3" or variable == "value4":
   code
else:
   code

Conditional Statement

IF STATEMENT
In Javascript you know that the block of code an if statement executes is bound by curly braces ({}). In Python, whitespace (tabs or spaces) does this work for us.

if 8 < 9:
  print "Eight is less than nine!"

if is always followed by an expression, which is followed by a colon (:). The code block (the code to be executed if the expression evaluates to True) is indented four spaces.

IF ELSE Statement –

if 1 == 1:
  print "Hi"
else:
  print "Bye"

IF ELSEIF ELSE Statement

def greater_less_equal_5(answer):
  if answer > 5:
    return 1
  elif answer < 5:
    return -1
  else:
    return 0

print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)
Output:
-1
0
1

A Sample Python Program !

def the_flying_circus():
# Start coding here!
  answer = raw_input("Enter a Number ?")

  if answer == "5" and answer !=  "0":
    print "5 is the ANSWER"
    return True
  elif answer > "10" and answer < "20":
    print "medium Double Digit Number!"
    return "Hai Hai"
  else:
    print "Final Point"
    return "Yo"

output = the_flying_circus()
print "%s is the output of the function :-)" % (output)

Difference between return and print
Print is used to print onto the screen (stdout) whereas return is used to get a value/result from a function. Return is also used to control the flow execution by exiting the function.

Always check value taken from User is valid or not before it is been used in the program.

For Example – When name of a person is entered:
Check if user entered empty value or not by the len() function.

original = raw_input("What is your name ?")
if len(original) > 0:
  print "%s" % (original)
else:
  print "EMPTY"

Further adding to this, User can be tricky by giving numbers. To verify its alphabets use isalpha() function.

x = "J123"
x.isalpha() # False

Note :
When user input is recieved and if its number it needs to be converted as well, eg:

n = raw_input("Enter the number")
n = int(n)

Functions with Splat Arguments
Speaking of not knowing what to expect: your functions not only don’t know what arguments they’re going to get ahead of time, but occasionally, they don’t even know how many arguments there will be.

Solution = Use Splat Arguments in Functions

def favorite_actors(*names):
    print "Your favorite actors are:" , names

favorite_actors("Michael Palin", "John Cleese", "Graham Chapman")

Output:
Your favorite actors are: ('Michael Palin', 'John Cleese', 'Graham Chapman')

Importing Modules
A module is a file that contains definitions—including variables and functions—that you can use. It would clutter up the interpreter to keep all these variables and functions around all the time, so you just import the module you want when you need something from it.

import math
print math.sqrt(25)
Output = 5

Importing the entire math module is kind of annoying for two reasons, though: first, we really only want the sqrt function, and second, we have to remember to type math.sqrt() any time we want to retrieve that function from the math module.

Thankfully, it’s possible to import only certain variables or functions from a given module. Pulling in just a single function from a module is called a function import, and it’s done using the from keyword, like so:

from module import function

where “module” and “function” are replaced by the names of the module and function you want. The best part is, now you only have to type sqrt() to get the square root of a number—no more math.sqrt()!

from math import *

The above function import all fucntions in Math module and also enable us not to use math during function call for eg.

sqrt(25)  - would suffice to find the square root .

if you import * from several modules at once, there won’t be any way for you to figure out which variable or function came from where. It’d be like having someone dump a ton of random stuff from a bunch of different boxes in your apartment, then throwing the boxes away so you can’t even see where the stuff came from.

For these reasons, it’s best to stick with either import module and suffer the inconvenience of having to type module.name, or just import specific variables and functions from various modules as needed.

Some more examples on functions:
showing you some of the cool functions that are built in to Python (no modules required!).

You already know about some of the built-in functions we’ve used on (or to create) strings, such as .upper(), .lower(), str(), and len(). These are great for doing work with strings, but what about something a little more analytic?

def biggest_number(*args):
    print max(args)
    return max(args)

def smallest_number(*args):
    print min(args)
    return min(args)

def distance_from_zero(arg):
    print abs(arg)
    return abs(arg)

biggest_number(-10, -5, 5, 10)
smallest_number(-10, -5, 5, 10)
distance_from_zero(-10)

output:
10
-10
10

TYPE function :
print type(42)
print type(4.2)
print type(‘spam’)
print type({‘Name’:’John Cleese’})
print type((1,2))

output
<type ‘int’>
<type ‘float’>
<type ‘unicode’>
<type ‘dict’>
<type ‘tuple’>

Note: (The ‘unicode’ type is a special type of string.)

Function Exercise
Write a function, shut_down, that takes one parameter (you can use anything you like; in this case, we’d use s for string). The shut_down function should return “Shutting down…” when it gets “Yes”, “yes”, or “YES” as an argument, and “Shutdown aborted!” when it gets “No”, “no”, or “NO”.

If it gets anything other than those inputs, the function should return “Sorry, I didn’t understand you.”
HINT:
Rather than creating a separate if/elif branch for each capitalization case of “yes” and “no”, try calling .lower() or .upper() on the function input in order to make all cases the same. (If you try it another way, there would be 12 different cases you’d have to worry about!)

Make sure your function outputs appear exactly as shown, including punctuation! Also, make sure your function returns the above values rather than printing them.

Answer:

def shut_down(s):
    new = s.lower()
    if new == "yes":
        return "Shutting down..."
    elif new == "no":
        return "Shutdown aborted!"
    else:
        return "Sorry, I didn't understand you."

Lists

Lists are a datatype you can use to store a collection of different pieces of information as a sequence under a single variable name. (Datatypes you’ve already learned about include strings, numbers, and booleans.)

You can assign items to a list with an expression of the form

list_name = [item_1, item_2]
with the items in between brackets. A list can also be empty: empty_list = [].

Lists are very similar to strings, but there are a few key differences.

Example:

zoo_animals = ["pangolin", "cassowary", "sloth", "donkey"];

if len(zoo_animals) > 3:
print "The first animal at the zoo is the " + zoo_animals[0]
print "The second animal at the zoo is the " + zoo_animals[1]
print "The third animal at the zoo is the " + zoo_animals[2]
print "The fourth animal at the zoo is the " + zoo_animals[3]

Access by Index
You can access an individual item on the list by its index. An index is like an address that identifies the item’s place in the list. The index appears directly after the list name, in between brackets, like this: list_name[index].

List indices begin with 0, not 1! You access the first item in a list like this: list_name[0]. The second item in a list is at index 1: list_name[1]. Computer scientists love to start counting from zero.

Late Arrivals & List Length
A list doesn’t have to have a fixed length—you can add items to the end of a list any time you like! In Python, we say lists are mutable: that is, they can be changed.

You can add items to lists with the built-in list function append(), like this:

list_name.append(item)

Check it out: we’ve appended a string to suitcase on line 2.

You can get the number of items in a list with the len() function (short for “length”), like so:

len(list_name)

One note before we begin. On the last line we are printing suitcase. When this prints out, depending on your browser/OS configuration, you may notice a that the contents seem a little different. Each word might have a small u at the beginning. This is because, under the hood, strings in our version of Python are really unicode objects. You don’t need to know anything about that, except that strings will have type unicode and that “string” == u’string’ is True.

List Slicing
If you only want a small part of a list, that portion can be accessed using a special notation in the index brackets. list_name[a:b] will return a portion of list_name starting with the index a and ending before the index b.

If you tell Python my_list = [0, 1, 2, 3], then my_list[1:3] will return the list [1, 2], leaving the original list unchanged!

Slicing Lists and Strings
You can slice a string exactly like a list! In fact, you can think of strings as lists of characters: each character is a sequential item in the list, starting from index 0.
Example

animals = "catdogfrog"
cat =    animals[:3]
dog =    animals[3:6]
frog =   animals[6:10]

Maintaining Order
You can search through a list with the index() function. my_list.index(“dog”) will return the first index that contains the string “dog”. An error will occur if there is no such item.

Items can be added to the middle of a list (instead of to the end) with the insert() function. my_list.insert(4,”cat”) adds the item “cat” at index 4 of my_list, and moves the item previously at index 4 and all items following it to the next index (that is, they all get bumped towards the end by one).

For One and All
If you want to do something with every item in the list, you can use a for loop. If you’ve learned about for loops in JavaScript, pay close attention! They’re different in Python.

Here’s the syntax:

for variable in list_name:
# Do stuff!

A variable name follows the for keyword; it will be assigned the value of each list item in turn. in list_name designates list_name as the list the loop will work on. The line ends with a colon (:) and the indented code that follows it will be executed once per item in the list.

Example:

my_list = [1,9,3,8,5,7]

for number in my_list:
print number*2

If your list is a jumbled mess, you may need to sort() it. my_list.sort() will sort the items in my_list in increasing numerical/alphabetical order.

It’s worth noting that sort() does not return a new list; instead, your existing my_list is sorted in place (the sorted version replaces the unsorted version).

Example II with “sort”:

start_list = [5, 3, 1, 2, 4]
square_list = []  # Empty List square_list

for numbers in start_list:
square_list.append(numbers**2)
square_list.sort()

print square_list

Dictionary

A dictionary is similar to a list, but you access values by looking up a key instead of an index. A key can be any string or number. Dictionaries are enclosed in curly braces, like so:

d = {'key1' : 1, 'key2' : 2, 'key3' : 3}

This is a dictionary called d with three key-value pairs. The key ‘key1’ points to the value 1, ‘key2’ to 2, and so on.

Dictionaries are great for things like phone books (pairing a name with a phone number), login pages (pairing an e-mail address with a username), and more!

Accessing dictionary values by key is just like accessing list values by index
Example :
residents = {‘Puffin’ : 104, ‘Sloth’ : 105, ‘Burmese Python’ : 106}
print residents[‘Puffin’] # Prints Puffin’s room number
print residents[‘Sloth’]
print residents[‘Burmese Python’]

New Entries
Like Lists, Dictionaries are “mutable”. This means they can be changed after they are created. One advantage of this is that we can add new key/value pairs to the dictionary after it is created like so:

dict_name[new_key] = new_value

An empty pair of curly braces {} is an empty dictionary, just like an empty pair of [] is an empty list.

The length len() of a dictionary is the number of key-value pairs it has. Each pair counts only once, even if the value is a list. (That’s right: you can put lists inside dictionaries!)

No append() or insert() used unlike in List.

Modify Dictonary
Because dictionaries are mutable, they can be changed in many ways. Items can be removed from a dictionary with the del command:

del dict_name[key_name]

will remove the key key_name and its associated value from the dictionary.

A new value can be associated with a key by assigning a value to the key, like so:

dict_name[key] = new_value

Let’s go over a few last notes about dictionaries

A single dictionary can hold many types of values. The inventory dict here has both int and list values.

A dictionary’s keys MUST be both immutable and hashable. Don’t worry if you don’t understand what that means. In general, we only use strings, numbers or tuples as keys, but not lists, dictionaries or sets. The values can be anything you’d like.

When you access a value in a dictionary you have access to that value directly. So if we have something like:

my_dict = {"hello":["h","e","l","l","o"]}

we can write my_dict[“hello”][1] and the result will be “e”.

And one new thing about lists. Lists have a method called .remove(VALUE) which will remove the first instance of the value passed to it. For example:

beatles = ["john","paul","george","ringo","stuart"]
beatles.remove("stuart")
print beatles
>> ["john","paul","george","ringo"]

A sample code here ! with some operations on Dictonary :

inventory = {'gold' : 500,
'pouch' : ['flint', 'twine', 'gemstone'],
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']}

# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']

# Sorting the list found under the key 'pouch'
inventory['pouch'].sort()
# Here the dictionary access expression takes the place of a list name

inventory['pocket'] = ['seashell','strange berry','lint']
inventory['backpack'].sort()
inventory['backpack'].remove("dagger")
inventory['gold'] = 500+50

Using FOR loop for List and Dictonary

for loops allow us to iterate through all of the elements in a list from the left-most (or zeroth element) to the right-most element. A sample loop would be structured as follows:

a = ["List of some sort”]
for x in a: 
    # Do something for every x

This loop will run all of the code in the indented block under the for x in a: statement. The item in the list that is currently being evaluated will be x. So running the following:

for item in [1, 3, 21]: 
    print item

would print 1, then 3, and then 21. The variable between for and in can be set to any variable name (currently item), but you should be careful to avoid using the word “list” as a variable, since that’s a reserved word (that is, it means something special) in the Python language.

Example Prog:

names = ["Adam","Alex","Mariah","Martine","Columbus"]

for UnNi in names:
    print UnNi

Use with Dictonary
You can also use a for loop on a dictionary to loop through its keys with the following:

# A simple dictionary
d = {"foo" : "bar"}

for key in d: 
    print d[key]  # prints "bar"

Note that dictionaries are unordered, meaning that any time you loop through a dictionary, you will go through every key, but you are not guaranteed to get them in any particular order.

Example Programme

webster = {
    "Aardvark" : "A star of a popular children's cartoon show.",
    "Baa" : "The sound a goat makes.",
    "Carpet": "Goes on the floor.",
    "Dab": "A small amount."
}

# Add your code below!
for apple in webster:
    print webster[apple]

Control Flow and Looping
The blocks of code in a for loop can be as big or as small as they need to be. While looping, you may want to perform different actions depending on the particular item in the list. This can be achieved by combining your loops with control flow (if/else statements) that might resemble the following:

for item in numbers: 
    if condition: 
        # Do something

Make sure to keep track of your indentation or you may get confused!

Lists + Functions
Functions can also take lists as inputs and perform various operations on those lists.

Write a function called fizz_count that takes a list x as input and returns the count of the string “fizz” in that list.

For example, fizz_count([“fizz”,”buzz”,”fizz”]) should return 2. (Make sure your function returns the number instead of printing it.)

Programe:

def fizz_count(x):
    counter = 0
    for i in x:
        if i == "fizz":
            counter = counter + 1
    print counter
    return counter

fizz_count(["fizz","buzz","fizz"])

String Looping
As we’ve mentioned, strings are like lists with characters as elements. You can loop through strings the same way you loop through lists! we’ve put an example in the editor of how looping through a string might work.

for letter in "Codecademy":
    print letter

# Empty lines to make the output pretty
print
print

word = "Programming is fun!"

for letter in word:
    # Only print out the letter i
    if letter == "i":
        print letter
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s