Auto AdSense

Sunday, 30 November 2014

A First Python Program

  • First Python Program:
    #!/usr/bin/python

    print "Hello, Python!";
  • Quotation in Python:
    word = 'word'
    sentence = "This is a sentence."
    paragraph = """This is a paragraph. It is
    made up of multiple lines and sentences."""
  • Comments in Python:
    #!/usr/bin/python

    # First comment
    print "Hello, Python!"; # second comment
  • Waiting for the User:
    #!/usr/bin/python

    raw_input("\n\nPress the enter key to exit.")
  • Multiple Statement Groups as Suites:
    if expression :
    suite
    elif expression :
    suite
    else :
    suite
  • Assigning Values to Variables:
    #!/usr/bin/python

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

    print counter
    print miles
    print name
  • Multiple Assignment:
    a = b = c = 1
    a, b, c = 1, 2, "john"
  • Python Strings:
    #!/usr/bin/python

    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
  • Python Lists:
    #!/usr/bin/python

    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
  • Python Tuples:
    #!/usr/bin/python

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

    print tuple # Prints complete list
    print tuple[0] # Prints first element of the list
    print tuple[1:3] # Prints elements starting from 2nd till 3rd
    print tuple[2:] # Prints elements starting from 3rd element
    print tinytuple * 2 # Prints list two times
    print tuple + tinytuple # Prints concatenated lists
  • Python Dictionary:
    #!/usr/bin/python

    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

No comments:

Post a Comment