Monday, January 23, 2017

python lists

Python Lists


%d int, %s string, %f/%g floating point # % operator text = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')
colors = ['red', 'blue', 'green'] print colors[0] print colors[2] print len(colors) b = colors squares = [1, 4, 9, 16] sum = 0 for num in squares: sum +=num print sum list = ['larry', 'curly', 'moe'] if 'curly in list: print 'yay' num = 1234 lst = [int(i) for i in str(num)] i= 37107287533902102798797998220837590246510135740250L >>> lst = [int(j) for j in str(i)] >>> lst [3, 7, 1, 0, 7, 2, 8, 7, 5, 3, 3, 9, 0, 2, 1, 0, 2, 7, 9, 8, 7, 9, 7, 9, 9, 8, 2, 2, 0, 8, 3, 7, 5, 9, 0, 2, 4, 6, 5, 1, 0, 1, 3, 5, 7, 4, 0, 2, 5, 0] http://stackoverflow.com/questions/780390/convert-a-number-to-a-list-of-integers range creates a list holding all the values while xrange creates an object that can iterate over the numbers on demand In python 2**3 equates to pow(2,3)
  • pow
  • xrange
  • str
>>>def main(): total = 0 for number in xrange(1, 1001): total += pow(number, number) print(str(total)[-10:]) >>> if __name__ == '__main__': main() 9110846700 __name__ : Every module in Python has a special attribute called __name__. It is a built-in variable that returns the name of the module. __main__ : Like other programming languages, Python too has an execution entry point i.e. main. 'main' is the name of the scope in which top-level code executes. Basically you have two ways of using a Python module: Run it directly as a script, or import it. When a module is run as a script, its __name__ is set to __main__. Thus,the value of __name__ attribute is set to __main__ when the module is run as main program. Otherwise the value of __name__ is set to contain the name of the module. http://stackoverflow.com/questions/419163/what-does-if-name-main-do

No comments:

Post a Comment