12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

11.7. Long integers 111count = 0def example3():count = count + 1# WRONGIfyou runit you get:UnboundLocalError: local variable 'count' referenced before assignment<strong>Python</strong> assumes that count is local, which means that you are reading it before writing it. Thesolution, again, istodeclarecountglobal.def example3():global countcount += 1Iftheglobal value ismutable, you can modifyit without declaring it:known = {0:0, 1:1}def example4():known[2] = 1Soyoucanadd,removeandreplaceelementsofagloballistordictionary,butifyouwanttoreassignthevariable, you have todeclare it:def example5():global knownknown = dict()11.7 Long integersIfyou computefibonacci(50),you get:>>> fibonacci(50)12586269025LTheLat the end indicates that theresult isalong integer 2 , or typelong.Valueswithtypeinthavealimitedrange;longintegerscanbearbitrarilybig,butastheygetbiggerthey consume more space and time.Themathematical operators workonlong integers,and thefunctions inthemathmodule, too, soingeneral any code that works withintwillalsowork withlong.Any time the result of a computation is too big to be represented with an integer, <strong>Python</strong> convertstheresult as along integer:>>> 1000 * 10001000000>>> 100000 * 10000010000000000L2 In<strong>Python</strong>3.0, typelongis gone;all integers, evenreally bigones, are typeint.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!