import math # 1. Complex arithmetic # 2. Conditionals # 3. Lists # 4. tuples def sep() : sepstring = "" sepstring += " " for i in range(75) : sepstring += "-" sepstring += " " print sepstring def header(s) : print " " sep() print " " + s sep() print " " # One more arithmetic operator : % # As some of you have observed for numbers n and d the quotient and # the remainder are given by header("Integer division") n = input("divident : ") d = input("divisor : ") print "Quotient = %d, remainder = %d." % (n/d, n%d) # 1. Complex arithmetic header("Complex aritmetic") u = 1 + 1j v = 0.70710678 + 0.70710678j w = math.sqrt(1.0/2) + math.sqrt(1.0/2) * 1j u2 = u * u v2 = v * v w2 = w ** 2 print "u^2 = %g + %gj; v^2 = %g + %gj and w^2 = %g + %gj" % (u2.real, \ u2.imag, v2.real, v2.imag, w2.real, w2.imag) # introducing line break. # This does not work # print math.sqrt(-1) # However this works import cmath print "Square root of -1 is %g + %gj" % (cmath.sqrt(-1).real, cmath.sqrt(-1).imag) #ipython and timing commands. # 2. Conditionals # let us use a conditional here. n = input("Find the square root of the complex number : ") n = complex(n) if n.imag == 0 : if n.real >= 0 : root_real = math.sqrt(n.real) root_imag = 0 else : root_real = 0 root_imag = math.sqrt(-n.real) else : root = cmath.sqrt(n) root_real = root.real root_imag = root.imag print "The root is %g + %g j" % (root_real, root_imag) # else is always not necessary f = input("To find the absolute value of the real no. : ") if f < 0 : f = -f print f # 3. Lists header("Lists") # We encountered lists when we saw the range function. print "range(10) = " print range(10) print "range(3, 10) = " print range(3, 10) print "range(-5) = " print range(-5) mylist = ["Bread", 0, 1, math.e] print mylist print "mylist[2] = %g" % (mylist[2]) mylist.append("new element") print "After appending \'new element\': ", print mylist mylist.insert(1,42) print "Inserting the answer to the qn on Life, Universe and Everything at \ position 1 : " print mylist print "Deleting entry 2" del mylist[2] print mylist newlist = ["some", 2, "more", 54, "elements"] print "newlist : ", print newlist mylist = mylist + newlist print "appending new list to mylist : ", print mylist print "mylist entries from 2 - 4 : ", print mylist[2:5] print "mylist entries from 2 onwards : " + str(mylist[2:]) print "mylist entries upto 5 : " + str(mylist[:6])