Wednesday, December 28, 2016

Learning Python

Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language.Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands

Python is processed at runtime by the interpreter.
Python is interactive shows prompt and interact with the interpreter directly to write your programs.
Python supports Object-Oriented style or technique of programming that encapsulates code within objects.


>>> print ("Hello, World!") 
#!/usr/bin/python3

counter = 100          # An integer assignment
miles   = 1000.0       # A floating point
name    = "John"       # A string

print (counter)
print (miles)
print (name)

Python has five standard data types − Numbers, String, List, Tuple, Dictionary
Numbers :
var1 = 1
var2 = 10
del var
del var_a, var_b
Python supports four different numerical types −
  • int (signed integers)
  • float (floating point real values)
  • complex (complex numbers)
string :
str = 'Hello World!'

print (str)          # Prints complete string
print (str[0])       # Prints first character of the string
print (str[2:5])     # Prints characters starting from 3rd to 5th
print (str[2:])      # Prints string starting from 3rd character
print (str * 2)      # Prints string two times
print (str + "TEST") # Prints concatenated string
list :
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print (list)          # Prints complete list
print (list[0])       # Prints first element of the list
print (list[1:3])     # Prints elements starting from 2nd till 3rd 
print (list[2:])      # Prints elements starting from 3rd element
print (tinylist * 2)  # Prints list two times
print (list + tinylist) # Prints concatenated lists
Tuples
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For example −
#!/usr/bin/python3

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
tinytuple = (123, 'john')

print (tuple)           # Prints complete tuple
print (tuple[0])        # Prints first element of the tuple
print (tuple[1:3])      # Prints elements starting from 2nd till 3rd 
print (tuple[2:])       # Prints elements starting from 3rd element
print (tinytuple * 2)   # Prints tuple two times
print (tuple + tinytuple) # Prints concatenated tuple
Dictionary :
Python's dictionaries are kind of hash table type. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object. Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For example −
#!/usr/bin/python3

dict = {}
dict['one'] = "This is one"
dict[2]     = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print (dict['one'])       # Prints value for 'one' key
print (dict[2])           # Prints value for 2 key
print (tinydict)          # Prints complete dictionary
print (tinydict.keys())   # Prints all the keys
print (tinydict.values()) # Prints all the values
This produce the following result −
This is one
This is two
{'code': 6734, 'name': 'john', 'dept': 'sales'}
dict_keys(['code', 'name', 'dept'])
dict_values([6734, 'john', 'sales'])
Dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out of order"; they are simply unordered.

Introductory Program showing function , loop, condition and printing :

Example 1 : given an input integer N, print output as 123.....N without using any special data types

from __future__ import print_function
if __name__ == '__main__':
    n = int(raw_input())
    i = 0
    j = 0
    result = 0
    num = 0
    while i <= n :
        num = i
        while num :
            j+=1
            num/=10
        result = result *(10**j) + i
        i+=1
        j = 0
    print (result)



Example 2 :  bear, honey and gold game :

from sys import exit

def gold_room():
print "This room is full of gold. How much do you take?"
next = raw_input("> ")
if "0" in next or "1" in next:
how_much = int(next)
else:
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice, you are not greedy, you win!"
exit(0)
else:
dead("You are greedy bastard!")

def bear_room():
print "There is a bear here."
print "The bear has a bunch of honey."
print "The fat bear is in front of another door."
print "How are you going to move the bear?"
bear_moved = False

while True:
next = raw_input("> ")

if next == "take honey":
dead("The bear looks at you then slaps your face off.")
elif next == "taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go through it now."
bear_moved = True
elif next == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your leg off.")
elif next == "open door" and bear_moved:
gold_room()
else:
print "I got no idea what that means."

def cthulhu_room():
print "Here you see the great evil Cthulhu."
print "He, it, whatever stares at you and you go insane."
print "Do you flee for your life or eat your head?"

next = raw_input("> ")

if "flee" in next:
start()
elif "head" in next:
dead("Well that was tasty!")
else:
cthulhu_room()

def dead(why):
print why, "Good job!"
exit(0)

def start():
print "You are in a dark room."
print "There is a door to your right and left."
print "Which one do you take?"

next = raw_input("> ")

if next == "left":
bear_room()
elif next == "right":
cthulhu_room()
else:
dead("You stumble around the room untill you starve.")

start()