Powered by Ajaxy
Digg StumbleUpon LinkedIn YouTube Flickr Facebook Twitter RSS Reset

Python: create a simple switch statement

def show(s):
    print s
def switch(ch):
    try:
      {'1': lambda : show("January"),
       '2': lambda : show("February"),
       '3': lambda :

Python: Read String from standard input.

import math as operation
while 1:
    val1=raw_input("Enter X: ")
    val1= int(val1)
    val2=raw_input("Enter Y: ")
    val2= int(val2)
    if va

Python: Using the break statement in a for structure.

x=0
while x<=10:
    print x
    x+=1
    if(x==5):
        break  # Quit
print "Loop stopped at: ",x

Python: How tocatch several exceptions

def division(x, y):
      try:
          return(x/y)
      except ZeroDivisionError:
          print "Cannot divide",x,"by zeo"  
      except Type

Python: How to assign a value to multiple variables

#Initialize three variables with the same value
a= b= c= 0
print a,b,c 
x= y= None
print x,y

Python: Using while loops

total=0;
average=0;
counter=1;
while counter<=10:
   score=raw_input("Enter student score #%d: "%(counter)) # Read from keyboard
   score=int(score

Python: raise an IOError exception

try:
    f = open("test.txt")
except IOError:
    print "trying to open a nonexistent file."

Python: Using Exceptions

a=[3, 4, 0, 8, 2, 11, 0, 18]
for x in a:
    try:
     print "%f"%(5/x)
    except ZeroDivisionError:
        print "divide-by-0 exception"
[/pytho

Python: Using ‘for’ loops

for x in range( 1, 10):
   if (x%2==0): #Skip even numbers
      continue
   print x,     #print odd numbers
   if x==8:
       break;

Python: How to use while loops

x = 1
while x < 10:
    x += 1
    print x

Python: print a list of Python keywords

import keyword
for reserved in keyword.kwlist:
    print "#"+reserved
# ce module affiche ça
#and
#as
#assert
#break
#class
#continue
#def
#del
#eli

Python: Deleting Variables

# Initialize two variables
a, b = "Monday", "January"
# Display the values ??of two variables
print a, b
# remove the two variables
del a, b
# This