02 Conditional Statements
02 Conditional Statements
2. connect(uname='admin', pword='admin123',
'pec.ac.in') -- INVALID
def even_fib(n):
total = 0
f1, f2 = 1, 2
while f1 < n:
if f1 % 2 == 0:
total = total + f1
f1, f2 = f2, f1 + f2
return total
if __name__ == "__main__":
limit = input(“Max Fibonacci number: “)
print(even_fib(int(limit)))
Modules
I can run our module directly at the command line.
In this case, the module’s __name__ variable has
the value “__main__”.
$ python fib.py
Max Fibonacci number: 4000000
4613732
$ python
>>> import fib
>>> fib.even_fib(4000000)
4613732
Mini module quiz
''' Module bar.py '''
def print_hello():
print "Hello from bar!"
if __name__ == "__main__":
print "bar's __name__ is __main__"
''' Module foo.py'''
import bar
if __name__ == "__main__":
print "foo's __name__ is __main__"
bar.print_hello()
Mini module quiz
$ python bar.py
Hi from bar's top level!
bar's __name__ is __main__
$ python foo.py
Hi from bar's top level!
Hi from foo's top level!
foo's __name__ is __main__
Hello from bar!
Mini module quiz
$ python
>>> import foo
Hi from bar's top level!
Hi from foo's top level!
>>> import bar
>>>
Random Module
• To generate random numbers
• Some functions:
– random.seed(a=None, version=2) : to seed from a
specific value, default is system time or provided by
OS. Generates float value in range [0,1).
>>> random.seed(1)
– random.randrange(stop)
random.randrange(start, stop[,step]): retunrs a
randomly selected element form the range.
>>> random.randrange(1, 100, 5)
Random Module
– random.randint(a,b): Return a random integer N such
that a <= N <= b. Alias for randrange(a, b+1)
– random.getstate(): return an object capturing the
current internal state of the generator. This object can
be passed to setstate() to restore the state
– random.setstate(): state should have been obtained
from a previous call to getstate(), and setstate()
restores the internal state of the generator to what it
was at the time getstate() was called.
– random.random(): to generate random numbers
Command line arguments
• Command line arguments are stored in
the sys module’s argv attribute as a list: