Basic Python Training at Arcesium - Day 2

Apr 15-18, 2019 Vikrant Patil

These notes are available online at http://notes.pipal.in/2019/arcesium_basic_apr/day2.html

© Pipal Academy LLP

Day 1 | Day 2 | Day 3 | Day 4

We will be using python 3 (>= 3.0) from anaconda for this training. You can download it from

https://www.anaconda.com/download/

methods - recap

In [1]:
text = "Some text with some words in it"
In [2]:
text.startswith("S")
Out[2]:
True
In [3]:
text.lower()
Out[3]:
'some text with some words in it'
In [4]:
text.upper()
Out[4]:
'SOME TEXT WITH SOME WORDS IN IT'
In [5]:
text.split()
Out[5]:
['Some', 'text', 'with', 'some', 'words', 'in', 'it']
In [6]:
words = text.split()
In [7]:
words
Out[7]:
['Some', 'text', 'with', 'some', 'words', 'in', 'it']
In [8]:
"-".join(words)
Out[8]:
'Some-text-with-some-words-in-it'
In [9]:
"_".join(words).split()
Out[9]:
['Some_text_with_some_words_in_it']
In [10]:
"_".join(words).split("_")
Out[10]:
['Some', 'text', 'with', 'some', 'words', 'in', 'it']
In [11]:
words
Out[11]:
['Some', 'text', 'with', 'some', 'words', 'in', 'it']
In [12]:
words.append("One")
In [13]:
words
Out[13]:
['Some', 'text', 'with', 'some', 'words', 'in', 'it', 'One']
In [14]:
words.pop(0)
Out[14]:
'Some'
In [15]:
words
Out[15]:
['text', 'with', 'some', 'words', 'in', 'it', 'One']
In [16]:
words.insert(0, "Some")
In [17]:
words
Out[17]:
['Some', 'text', 'with', 'some', 'words', 'in', 'it', 'One']
In [18]:
words.extend(["two", "three", "four"])
In [19]:
words
Out[19]:
['Some',
 'text',
 'with',
 'some',
 'words',
 'in',
 'it',
 'One',
 'two',
 'three',
 'four']
In [20]:
words.pop()
Out[20]:
'four'
In [21]:
words
Out[21]:
['Some', 'text', 'with', 'some', 'words', 'in', 'it', 'One', 'two', 'three']
In [22]:
words.pop(-1)
Out[22]:
'three'

problem

  • Write a function to count_zeros count zeros in given integer.
>>> count_zeros(1000)
3
In [23]:
max(text)
Out[23]:
'x'
In [24]:
numbers= [1, 2, 3,4 , 5]
In [25]:
t = (1, 2, 3, 4, 5)
In [26]:
numbers[0] = 0
In [27]:
numbers
Out[27]:
[0, 2, 3, 4, 5]
In [28]:
t[0] = 0
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-28-51595a4035f3> in <module>
----> 1 t[0] = 0

TypeError: 'tuple' object does not support item assignment
In [29]:
t[0]
Out[29]:
1
In [31]:
def foo(x):
    return x*x+1
In [32]:
foo(5)
Out[32]:
26
In [33]:
foo(3)
Out[33]:
10
In [34]:
def count_zeros(n):
    return str(n).count("0")
In [35]:
count_zeros(1000**100)
Out[35]:
300

list splicing

In [36]:
list(range(1, 30, 5))
Out[36]:
[1, 6, 11, 16, 21, 26]
In [37]:
list(range(10))
Out[37]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [38]:
list(range(1,10))
Out[38]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [39]:
words 
Out[39]:
['Some', 'text', 'with', 'some', 'words', 'in', 'it', 'One', 'two']
In [41]:
words = "Wizard of oz is python programmer".split()
In [42]:
words
Out[42]:
['Wizard', 'of', 'oz', 'is', 'python', 'programmer']
In [43]:
words[0]
Out[43]:
'Wizard'
In [44]:
words[-1]
Out[44]:
'programmer'
In [45]:
words[2:5]
Out[45]:
['oz', 'is', 'python']
In [46]:
words[1:5:2]
Out[46]:
['of', 'is']
In [47]:
digits = list(range(10))
In [48]:
digits
Out[48]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [49]:
digits[1:8:2]
Out[49]:
[1, 3, 5, 7]
In [51]:
digits[:] # copy of digits
Out[51]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

pitfalls

In [53]:
x = [1,1,1,1]
In [54]:
y = x
In [55]:
x.append(0)
In [56]:
x
Out[56]:
[1, 1, 1, 1, 0]
In [57]:
y
Out[57]:
[1, 1, 1, 1, 0]
In [58]:
y.pop()
Out[58]:
0
In [59]:
y
Out[59]:
[1, 1, 1, 1]
In [60]:
x
Out[60]:
[1, 1, 1, 1]
In [61]:
z = x[:] # new copy
In [62]:
z
Out[62]:
[1, 1, 1, 1]
In [63]:
x.append(0)
In [64]:
x
Out[64]:
[1, 1, 1, 1, 0]
In [65]:
z
Out[65]:
[1, 1, 1, 1]
In [66]:
digits[2:] #drop frist two
Out[66]:
[2, 3, 4, 5, 6, 7, 8, 9]
In [67]:
digits[:5] #take first 5
Out[67]:
[0, 1, 2, 3, 4]
In [68]:
digits[:-1]
Out[68]:
[0, 1, 2, 3, 4, 5, 6, 7, 8]
In [70]:
digits[::-1] ## reverser the list
Out[70]:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

splicing also works for strings

In [71]:
text[:10]
Out[71]:
'Some text '
In [72]:
text[::-1]
Out[72]:
'ti ni sdrow emos htiw txet emoS'
In [73]:
digits[2:7] # start at index 2 till index 6 (excludes 7)
Out[73]:
[2, 3, 4, 5, 6]
In [74]:
digits[2:] # starts at index 2 ..till end
Out[74]:
[2, 3, 4, 5, 6, 7, 8, 9]
In [75]:
digits[:5] # starts at index 0 till index 4 (excluded 5)
Out[75]:
[0, 1, 2, 3, 4]
In [76]:
numbers = list(range(1, 10))
In [77]:
numbers
Out[77]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [78]:
numbers[:4]
Out[78]:
[1, 2, 3, 4]
In [79]:
numbers[3]
Out[79]:
4
In [80]:
def head(seq, n):
    return seq[:n]
In [82]:
head(words, 3)
Out[82]:
['Wizard', 'of', 'oz']
In [83]:
head
Out[83]:
<function __main__.head(seq, n)>

Question

When to use round bracket and when to use square bracket?

When you want to call a function you use round bracket.

when you want to access element from a list, string, tuple, dictionary you should use square bracket

In [84]:
seq
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-84-e916cee2b9d0> in <module>
----> 1 seq

NameError: name 'seq' is not defined
In [85]:
def func(x):
    return x*x
In [86]:
x = 5
In [87]:
func(7)
Out[87]:
49
In [88]:
func(x)
Out[88]:
25

modules

In [89]:
import math
In [90]:
math
Out[90]:
<module 'math' from '/home/vikrant/anaconda3/lib/python3.7/lib-dynload/math.cpython-37m-x86_64-linux-gnu.so'>
In [91]:
def cyl_volume(radius, height):
    area = math.pi*radius**2
    return area*height
In [92]:
cyl_volume(1, 10)
Out[92]:
31.41592653589793
In [93]:
math.sin(math.pi)
Out[93]:
1.2246467991473532e-16
In [94]:
help(math.ceil)
Help on built-in function ceil in module math:

ceil(x, /)
    Return the ceiling of x as an Integral.
    
    This is the smallest integer >= x.

In [95]:
math.ceil(4.3)
Out[95]:
5
In [96]:
math.ceil(4.9)
Out[96]:
5
In [97]:
from math import ceil
In [98]:
ceil(30.4)
Out[98]:
31
In [99]:
help(sorted)
Help on built-in function sorted in module builtins:

sorted(iterable, /, *, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.
    
    A custom key function can be supplied to customize the sort order, and the
    reverse flag can be set to request the result in descending order.

In [100]:
def sumofsquares(x,y):
    def square(a):
        return a*a
    return square(x) + square(y)

Just like there can be function inside function. There can be module in inside module.

In [101]:
from os import path
In [103]:
path.exists("c:")
Out[103]:
False
In [105]:
help(math)
Help on module math:

NAME
    math

MODULE REFERENCE
    https://docs.python.org/3.7/library/math
    
    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    This module is always available.  It provides access to the
    mathematical functions defined by the C standard.

FUNCTIONS
    acos(x, /)
        Return the arc cosine (measured in radians) of x.
    
    acosh(x, /)
        Return the inverse hyperbolic cosine of x.
    
    asin(x, /)
        Return the arc sine (measured in radians) of x.
    
    asinh(x, /)
        Return the inverse hyperbolic sine of x.
    
    atan(x, /)
        Return the arc tangent (measured in radians) of x.
    
    atan2(y, x, /)
        Return the arc tangent (measured in radians) of y/x.
        
        Unlike atan(y/x), the signs of both x and y are considered.
    
    atanh(x, /)
        Return the inverse hyperbolic tangent of x.
    
    ceil(x, /)
        Return the ceiling of x as an Integral.
        
        This is the smallest integer >= x.
    
    copysign(x, y, /)
        Return a float with the magnitude (absolute value) of x but the sign of y.
        
        On platforms that support signed zeros, copysign(1.0, -0.0)
        returns -1.0.
    
    cos(x, /)
        Return the cosine of x (measured in radians).
    
    cosh(x, /)
        Return the hyperbolic cosine of x.
    
    degrees(x, /)
        Convert angle x from radians to degrees.
    
    erf(x, /)
        Error function at x.
    
    erfc(x, /)
        Complementary error function at x.
    
    exp(x, /)
        Return e raised to the power of x.
    
    expm1(x, /)
        Return exp(x)-1.
        
        This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
    
    fabs(x, /)
        Return the absolute value of the float x.
    
    factorial(x, /)
        Find x!.
        
        Raise a ValueError if x is negative or non-integral.
    
    floor(x, /)
        Return the floor of x as an Integral.
        
        This is the largest integer <= x.
    
    fmod(x, y, /)
        Return fmod(x, y), according to platform C.
        
        x % y may differ.
    
    frexp(x, /)
        Return the mantissa and exponent of x, as pair (m, e).
        
        m is a float and e is an int, such that x = m * 2.**e.
        If x is 0, m and e are both 0.  Else 0.5 <= abs(m) < 1.0.
    
    fsum(seq, /)
        Return an accurate floating point sum of values in the iterable seq.
        
        Assumes IEEE-754 floating point arithmetic.
    
    gamma(x, /)
        Gamma function at x.
    
    gcd(x, y, /)
        greatest common divisor of x and y
    
    hypot(x, y, /)
        Return the Euclidean distance, sqrt(x*x + y*y).
    
    isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
        Determine whether two floating point numbers are close in value.
        
          rel_tol
            maximum difference for being considered "close", relative to the
            magnitude of the input values
          abs_tol
            maximum difference for being considered "close", regardless of the
            magnitude of the input values
        
        Return True if a is close in value to b, and False otherwise.
        
        For the values to be considered close, the difference between them
        must be smaller than at least one of the tolerances.
        
        -inf, inf and NaN behave similarly to the IEEE 754 Standard.  That
        is, NaN is not close to anything, even itself.  inf and -inf are
        only close to themselves.
    
    isfinite(x, /)
        Return True if x is neither an infinity nor a NaN, and False otherwise.
    
    isinf(x, /)
        Return True if x is a positive or negative infinity, and False otherwise.
    
    isnan(x, /)
        Return True if x is a NaN (not a number), and False otherwise.
    
    ldexp(x, i, /)
        Return x * (2**i).
        
        This is essentially the inverse of frexp().
    
    lgamma(x, /)
        Natural logarithm of absolute value of Gamma function at x.
    
    log(...)
        log(x, [base=math.e])
        Return the logarithm of x to the given base.
        
        If the base not specified, returns the natural logarithm (base e) of x.
    
    log10(x, /)
        Return the base 10 logarithm of x.
    
    log1p(x, /)
        Return the natural logarithm of 1+x (base e).
        
        The result is computed in a way which is accurate for x near zero.
    
    log2(x, /)
        Return the base 2 logarithm of x.
    
    modf(x, /)
        Return the fractional and integer parts of x.
        
        Both results carry the sign of x and are floats.
    
    pow(x, y, /)
        Return x**y (x to the power of y).
    
    radians(x, /)
        Convert angle x from degrees to radians.
    
    remainder(x, y, /)
        Difference between x and the closest integer multiple of y.
        
        Return x - n*y where n*y is the closest integer multiple of y.
        In the case where x is exactly halfway between two multiples of
        y, the nearest even value of n is used. The result is always exact.
    
    sin(x, /)
        Return the sine of x (measured in radians).
    
    sinh(x, /)
        Return the hyperbolic sine of x.
    
    sqrt(x, /)
        Return the square root of x.
    
    tan(x, /)
        Return the tangent of x (measured in radians).
    
    tanh(x, /)
        Return the hyperbolic tangent of x.
    
    trunc(x, /)
        Truncates the Real x to the nearest Integral toward 0.
        
        Uses the __trunc__ magic method.

DATA
    e = 2.718281828459045
    inf = inf
    nan = nan
    pi = 3.141592653589793
    tau = 6.283185307179586

FILE
    /home/vikrant/anaconda3/lib/python3.7/lib-dynload/math.cpython-37m-x86_64-linux-gnu.so


In [106]:
import os
In [107]:
os.getcwd() # get current working directory
Out[107]:
'/home/vikrant/trainings/2019/arcesium_basic_apr'
In [108]:
os.listdir()
Out[108]:
['.ipynb_checkpoints',
 'push',
 'day1.ipynb',
 'day2.ipynb',
 'day2.html',
 'python_training',
 'Makefile',
 'day1.html']
In [110]:
os.listdir("/home/vikrant/") # windows users can give c:
Out[110]:
['.lesshst',
 '.gimp-2.8',
 '.dmrc',
 'usr',
 '.sudo_as_admin_successful',
 '.mozilla',
 '.emacs.d',
 '.Xauthority',
 '.bash_logout',
 '.webex',
 '.bash_history',
 '.atom',
 'Downloads',
 '.xsession-errors',
 '.vnc',
 '.gitconfig',
 '.ICEauthority',
 'npm-debug.log',
 '.gphoto',
 '.linuxmint',
 '.nano',
 '.gconf',
 '.profile',
 '.octave_hist',
 'trainings',
 '.dbus',
 '.adobe',
 '.chitragupta',
 '.aptitude',
 '.isomaster',
 'Templates',
 '.ssh',
 '.face',
 '.macromedia',
 '.conda',
 '.local',
 '.var',
 '.idlerc',
 '.anaconda',
 'website.odg',
 '.bashrc-anaconda3.bak',
 '.thumbnails',
 '.bashrc',
 '.xsession-errors.old',
 '.purple',
 'programming',
 '.cinnamon',
 'bin',
 '.npm',
 '.jupyter',
 '.java',
 '.icons',
 'Desktop',
 'anaconda3',
 '.cache',
 '.gnome2',
 'Music',
 '.wget-hsts',
 '.sqlite_history',
 'Videos',
 'Pictures',
 'Public',
 '.bashrc~',
 'x.yaml',
 '.gnome',
 '.node_repl_history',
 '.condarc',
 '.subversion',
 '.python_history',
 '.pki',
 '.node-gyp',
 '.gksu.lock',
 '.viminfo',
 '.config',
 'snap',
 '.thunderbird',
 '.oracle_jre_usage',
 'Documents',
 '.audacity-data',
 '.themes',
 '.ipython',
 'VirtualBox VMs',
 '.xinputrc',
 'AnacondaProjects',
 '.netrc']
In [111]:
def countfiles(directory):
    contents = os.listdir(directory)
    return len(contents)
In [114]:
cwd = os.getcwd()
countfiles(cwd)
Out[114]:
8
In [117]:
os.path.exits("hello.txt") # relative path, looked into current directory
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-117-e456c37945c2> in <module>
----> 1 os.path.exits("hello.txt") # relative path, looked into current directory

AttributeError: module 'posixpath' has no attribute 'exits'
In [118]:
os.path.exists("/home/vikrant/trainings") # absolute path. for windows it starts with drive name
Out[118]:
True
In [119]:
cwd
Out[119]:
'/home/vikrant/trainings/2019/arcesium_basic_apr'
In [120]:
os.path.sep
Out[120]:
'/'
In [121]:
cwd = os.getcwd()
In [122]:
filename = "hello.txt"
In [123]:
cwd + "/" + filename
Out[123]:
'/home/vikrant/trainings/2019/arcesium_basic_apr/hello.txt'
In [126]:
filepath = os.path.sep.join([cwd, filename])
In [128]:
filepath
Out[128]:
'/home/vikrant/trainings/2019/arcesium_basic_apr/hello.txt'
In [129]:
os.path.exists(filepath)
Out[129]:
False
In [131]:
os.path.exists(os.path.join(cwd, "day1.html"))
Out[131]:
True
In [132]:
os.path.getsize("day1.html")
Out[132]:
474130
In [133]:
def biggestfile(directory):
    files = os.listdir(directory)
    return max(files, key=os.path.getsize)
In [135]:
biggestfile(os.getcwd())
Out[135]:
'day1.html'
In [137]:
files = os.listdir(cwd)
In [138]:
files
Out[138]:
['.ipynb_checkpoints',
 'push',
 'day1.ipynb',
 'day2.ipynb',
 'day2.html',
 'python_training',
 'Makefile',
 'day1.html']
In [139]:
max(files)
Out[139]:
'python_training'
In [140]:
max(files, key=len)
Out[140]:
'.ipynb_checkpoints'
In [141]:
max(files, key=os.path.getsize)
Out[141]:
'day1.html'

Question

  • Where do we use dot?

We dot while calling methods from objects like string, list, dictionary, set...

while calling functions from modules or accessing variable data from module.

In [142]:
math.pi
Out[142]:
3.141592653589793
In [143]:
os.path.sep
Out[143]:
'/'
In [144]:
"_".join(["hello", "world"])
Out[144]:
'hello_world'
In [145]:
join()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-145-457e937ff984> in <module>
----> 1 join()

NameError: name 'join' is not defined
In [146]:
def mysum(x, y, z):
    return x+y+z
In [147]:
mysum(1, 2, 4)
Out[147]:
7
In [148]:
mysum(1, 2, 3,4, 5, 6, 7)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-148-bd4cf0e409a7> in <module>
----> 1 mysum(1, 2, 3,4, 5, 6, 7)

TypeError: mysum() takes 3 positional arguments but 7 were given
In [149]:
def mysum1(numbers):
    return sum(numbers)
In [150]:
mysum1([1,2,34,45,12,3,5])
Out[150]:
102

Writing our own modules

In [151]:
%%file mymath.py

mypy = 22.0/7

def square(x):
    return x*x

def sqrt(x):
    return x**0.5
Writing mymath.py
In [152]:
os.listdir()
Out[152]:
['.ipynb_checkpoints',
 'push',
 'day1.ipynb',
 'mymath.py',
 'day2.ipynb',
 'day2.html',
 'python_training',
 'Makefile',
 'day1.html']
In [153]:
os.path.exists("mymath.py")
Out[153]:
True
In [154]:
import mymath
In [156]:
mymath.mypy
Out[156]:
3.142857142857143
In [157]:
mymath.sqrt(2)
Out[157]:
1.4142135623730951
In [160]:
from mymath import sqrt
In [161]:
sqrt(5)
Out[161]:
2.23606797749979
In [162]:
%%file mymath1.py

mypy = 22.0/7

def square(x):
    return x*x

def sqrt(x):
    return x**0.5

print(sqrt(5))
Writing mymath1.py
In [163]:
!python mymath1.py
2.23606797749979

To make your program reusable it is necessary to pass some inputs to your script. Those inputs should be used by the pythom script. We will pass inputs using command line arguments.

In [164]:
%%file mymath2.py
import sys 

mypy = 22.0/7

def square(x):
    return x*x

def sqrt(x):
    return x**0.5

print("Arguments ->", sys.argv)

z = float(sys.argv[1])
print(sqrt(z))
Writing mymath2.py
In [165]:
!python mymath2.py 5 argg1 arg2 arg3 arg4 jlkdsjf sdlfkjsdlkfjs sdlkfjsd
Arguments -> ['mymath2.py', '5', 'argg1', 'arg2', 'arg3', 'arg4', 'jlkdsjf', 'sdlfkjsdlkfjs', 'sdlkfjsd']
2.23606797749979
In [166]:
!python mymath2.py
Arguments -> ['mymath2.py']
Traceback (most recent call last):
  File "mymath2.py", line 13, in <module>
    z = float(sys.argv[1])
IndexError: list index out of range
In [167]:
import mymath2
Arguments -> ['/home/vikrant/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py', '-f', '/run/user/1000/jupyter/kernel-a2b0e3ff-23f3-4a31-b4b9-7b1c22af2882.json']
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-167-1dacc6b73d24> in <module>
----> 1 import mymath2

~/trainings/2019/arcesium_basic_apr/mymath2.py in <module>
     11 print("Arguments ->", sys.argv)
     12 
---> 13 z = float(sys.argv[1])
     14 print(sqrt(z))

ValueError: could not convert string to float: '-f'
In [168]:
from mymath2 import sqrt
Arguments -> ['/home/vikrant/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py', '-f', '/run/user/1000/jupyter/kernel-a2b0e3ff-23f3-4a31-b4b9-7b1c22af2882.json']
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-168-cb7270162a4a> in <module>
----> 1 from mymath2 import sqrt

~/trainings/2019/arcesium_basic_apr/mymath2.py in <module>
     11 print("Arguments ->", sys.argv)
     12 
---> 13 z = float(sys.argv[1])
     14 print(sqrt(z))

ValueError: could not convert string to float: '-f'
In [169]:
def foo():
    print("foo")
In [170]:
foo()
foo
In [171]:
def hello():
    print("hello")
In [172]:
def hello():
    print("foo")
In [173]:
hello()
foo
In [174]:
%%file mymath3.py
import sys 

mypy = 22.0/7

def square(x):
    return x*x

def sqrt(x):
    return x**0.5


def main():
    print("Arguments ->", sys.argv)
    
    z = float(sys.argv[1])
    print(sqrt(z))
Writing mymath3.py
In [175]:
from mymath3 import sqrt

conditions

In [176]:
"hello.py".endswith(".py")
Out[176]:
True
In [177]:
words
Out[177]:
['Wizard', 'of', 'oz', 'is', 'python', 'programmer']
In [178]:
"python" in words
Out[178]:
True
In [179]:
"java" not in words
Out[179]:
True
In [180]:
stock = {"name":"HCL", "value":500, "exchange":"BSE"}
In [195]:
"name" in stock # check if name exists in keys
Out[195]:
True
In [182]:
"gain" in stock
Out[182]:
False
In [183]:
x = 2
In [184]:
x == 2
Out[184]:
True
In [185]:
x != 3
Out[185]:
True
In [186]:
x > 5
Out[186]:
False
In [187]:
x <= 4
Out[187]:
True
In [188]:
x >= 0
Out[188]:
True
In [189]:
"hello" == "hello"
Out[189]:
True
In [190]:
"hello" == "HELLO".lower()
Out[190]:
True
In [192]:
stock.keys()
Out[192]:
dict_keys(['name', 'value', 'exchange'])
In [193]:
stock.values()
Out[193]:
dict_values(['HCL', 500, 'BSE'])
In [196]:
"BSE" in stock.values() # check if BSE exists in values
Out[196]:
True
In [197]:
if "name" in stock:
    print(stock['name'], stock['value'])
HCL 500
In [198]:
if "name" in stock and "value" in stock:
    print(stock['name'], stock['value'])
HCL 500
In [199]:
if "name" in stock and "gain" in stock:
    print(stock['name'], stock['gain'])
else:
    print("Data is not there!")
Data is not there!
In [200]:
languanges =  ["python3", "java", "c", "english"]
if "python" in languanges:
    print("python there!")
elif "french" in languanges:
    print("frennch is there")
elif "telugu" in languanges:
    print("telugu is there")
else:
    print("No comman langauage found!")
No comman langauage found!
In [206]:
%%file mymath4.py
import sys 

mypy = 22.0/7

def square(x):
    return x*x

def sqrt(x):
    return x**0.5


def main():
    print("Arguments ->", sys.argv)
    
    z = float(sys.argv[1])
    print(sqrt(z))
    
print(__name__)
Overwriting mymath4.py
In [202]:
!python mymath4.py
__main__
In [203]:
import mymath4
mymath4
In [211]:
%%file mymath5.py
import sys 

mypy = 22.0/7

def square(x):
    return x*x

def sqrt(x):
    return x**0.5


def main():
    print("Arguments ->", sys.argv)
    
    z = float(sys.argv[1])
    print(sqrt(z))

    
print("__name__ =", __name__)
if __name__ == "__main__":
    main()
Overwriting mymath5.py
In [208]:
!python mymath5.py 8
Arguments -> ['mymath5.py', '8']
2.8284271247461903
In [209]:
from mymath5 import sqrt
In [210]:
foobar()

def foobar():
    print("foobar")
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-210-5b738b61060a> in <module>
----> 1 foobar()
      2 
      3 def foobar():
      4     print("foobar")

NameError: name 'foobar' is not defined
In [212]:
%%file mymath6.py
import sys 

mypy = 22.0/7

def square(x):
    return x*x

def sqrt(x):
    return x**0.5


def main():
    print("Arguments ->", sys.argv)
    
    z = float(sys.argv[1])
    print(sqrt(z))

    
print("__name__ =", __name__)
if __name__ == "__main__":
    main()
Writing mymath6.py
In [213]:
!python mymath6.py 7
__name__ = __main__
Arguments -> ['mymath6.py', '7']
2.6457513110645907
In [214]:
import mymath6
__name__ = mymath6

problem

  • Write a python script add.py which will add two number given from command line.
    python add.py 5 6
    11
  • Write a python script palindrom.py which will can tell if given word/number is palindrom or not.
    python palindrom.py madam
    True
    python palindrom.py hello
    False
  • Write a python script rearrangemax.py which will rearrage digits of a number to from maximum number
    python rearrangemax.py 4236
    6432
In [219]:
%%file add.py
import sys

def main():
    print(float(sys.argv[1]) + float(sys.argv[2]))

if __name__ == "__main__":
    main()
Overwriting add.py
In [220]:
!python add.py 54 4
58.0
In [221]:
%%file add1.py
import sys


print(float(sys.argv[1]) + float(sys.argv[2]))
Writing add1.py
In [223]:
!python add1.py 4 5
9.0
In [224]:
import add1
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-224-5ffa442179a0> in <module>
----> 1 import add1

~/trainings/2019/arcesium_basic_apr/add1.py in <module>
      2 
      3 
----> 4 print(float(sys.argv[1]) + float(sys.argv[2]))

ValueError: could not convert string to float: '-f'
In [226]:
list(map(float, ["1", "2", "3"]))
Out[226]:
[1.0, 2.0, 3.0]
In [227]:
def square(x):
    return x*x

list(map(square, [1, 2, 3, 4]))
Out[227]:
[1, 4, 9, 16]
In [228]:
%%file addmany.py
import sys

def main():
    values = sys.argv[1:]
    numbers = map(float, values)
    print(sum(numbers))
    
if __name__ == "__main__":
    main()
Writing addmany.py
In [229]:
!python addmany.py 2 3 4 1 12.4 5 
27.4
In [230]:
!python addmany.py 2 3 4 1
10.0
In [231]:
%%file palindrom.py
import sys

def is_palindrom(word):
    return word == word[::-1]

if __name__ == "__main__":
    print(is_palindrom(sys.argv[1]))
Writing palindrom.py
In [232]:
!python palindrom.py madam
True
In [233]:
!python palindrom.py 1221
True
In [234]:
!python palindrom.py 12211
False
In [235]:
s = "7787340"
In [237]:
sorted(s, reverse=True)
Out[237]:
['8', '7', '7', '7', '4', '3', '0']
In [238]:
list(s)
Out[238]:
['7', '7', '8', '7', '3', '4', '0']
In [239]:
%%file rearrangemax.py
import sys


def rearrangemax(n):
    s = str(n)
    return int(rearrange_s(s))

def rearrange_s(value):
    digits = sorted(value, reverse=True)
    return "".join(digits)

if __name__ == "__main__":
    print(rearrange_s(sys.argv[1]))
Writing rearrangemax.py
In [240]:
!python rearrangemax.py 6345
6543
In [241]:
from rearrangemax import rearrangemax
In [242]:
rearrangemax(45677)
Out[242]:
77654
In [243]:
del rearrangemax
In [244]:
def rearrangemax(n):
    s = str(n)
    return int(rearrange_s(s))
In [245]:
rearrangemax(34343)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-245-8c76193210f4> in <module>
----> 1 rearrangemax(34343)

<ipython-input-244-71bbe64abc0a> in rearrangemax(n)
      1 def rearrangemax(n):
      2     s = str(n)
----> 3     return int(rearrange_s(s))

NameError: name 'rearrange_s' is not defined
In [246]:
def rearrange_s(value):
    digits = sorted(value, reverse=True)
    return "".join(digits)
In [247]:
rearrangemax(3432)
Out[247]:
4332
In [248]:
del rearrangemax
In [249]:
def rearrangemax(n):
    s = str(n)
    return int(rearrange_s(s))

def rearrange_s(value):
    digits = sorted(value, reverse=True)
    return "".join(digits)
In [250]:
rearrangemax(45454)
Out[250]:
55444

loops

In [251]:
import time
In [253]:
n = 10

while n>0:
    print("Tick-" + str(n))
    time.sleep(1)
    n = n - 1 
    
print("Boooom!!!!")
Tick-10
Tick-9
Tick-8
Tick-7
Tick-6
Tick-5
Tick-4
Tick-3
Tick-2
Tick-1
Boooom!!!!
In [254]:
n = 10

while n>0:
    print("Tick-" + str(n))
    time.sleep(1800)
    n = n - 1 
    
print("Boooom!!!!")
Tick-10
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-254-d8ce42509cee> in <module>
      3 while n>0:
      4     print("Tick-" + str(n))
----> 5     time.sleep(1800)
      6     n = n - 1
      7 

KeyboardInterrupt: 
In [ ]:
print("hello")

problem

  • Write a function print_evens which prints first n even numbers.
    >>> print_evens(5)
    0
    2
    4
    6
    8
In [255]:
n = 10
i = 0
while i<n:
    print(i)
    i = i+1
0
1
2
3
4
5
6
7
8
9
In [256]:
def even(x):
    return x%2==0
In [257]:
even(5)
Out[257]:
False
In [258]:
even(4)
Out[258]:
True
In [261]:
n = 10
i = 0
count = 0
while count<n:
    if even(i):
        print(i)
        count = count+1
    i = i+1
0
2
4
6
8
10
12
14
16
18
In [264]:
def print_evens(n):
    nums = list(range(0, 2*n, 2))
    nums.reverse()
    while nums:
        print(nums.pop())
In [265]:
print_evens(5)
0
2
4
6
8
In [278]:
def print_evens(n):
    nums = list(range(0, 2*n, 2))
    while nums:
        print(nums.pop(0))
In [279]:
print_evens(6)
0
2
4
6
8
10
In [266]:
def empty(x):
    if x:
        print("Non empty")
    else:
        print("Empty")
In [267]:
empty("")
Empty
In [268]:
empty({})
Empty
In [269]:
empty([])
Empty
In [280]:
x, y , z = 1, 2, 3 # multiple assignments in single statement
In [272]:
x
Out[272]:
1
In [273]:
y
Out[273]:
2
In [274]:
z
Out[274]:
3
In [275]:
x, y = [4,5]
In [276]:
x
Out[276]:
4
In [281]:
x, y = x+y, 5
In [282]:
x
Out[282]:
3
In [283]:
y
Out[283]:
5

for loops

In [285]:
list(map(int, ["2","3","5"]))
Out[285]:
[2, 3, 5]
In [286]:
words
Out[286]:
['Wizard', 'of', 'oz', 'is', 'python', 'programmer']
In [287]:
for w in words:
    print(w.rjust(10))
    Wizard
        of
        oz
        is
    python
programmer
In [290]:
for word in words:
    print(word.rjust(10))
    Wizard
        of
        oz
        is
    python
programmer
In [291]:
for n in range(5):
    print(n)
0
1
2
3
4
In [292]:
for n in range(5):
    print(n, end=" ")
0 1 2 3 4 
In [293]:
words
Out[293]:
['Wizard', 'of', 'oz', 'is', 'python', 'programmer']
In [294]:
for w in words:
    print(w, end=" ")
Wizard of oz is python programmer 
In [295]:
def mysum(seq):
    s = 0
    for item in seq:
        s = s + item
    return s
In [296]:
mysum([1, 2, 3, 4, 5])
Out[296]:
15
In [297]:
mysum(words)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-297-3b3e1a10b402> in <module>
----> 1 mysum(words)

<ipython-input-295-4c6fe0334394> in mysum(seq)
      2     s = 0
      3     for item in seq:
----> 4         s = s + item
      5     return s

TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [299]:
def mysum(seq, initial=0):
    s = initial
    for item in seq:
        s = s + item
    return s
In [300]:
mysum([1,2,3,4,5])
Out[300]:
15
In [301]:
mysum(words, "")
Out[301]:
'Wizardofozispythonprogrammer'
In [302]:
def product(numbers):
    p = 1
    for n in numbers:
        p = p*n
    return p
In [303]:
product([1,2,3,4,5])
Out[303]:
120
In [304]:
def factorial(n):
    return product(range(1, n+1))
In [305]:
factorial(3)
Out[305]:
6
In [306]:
factorial(5)
Out[306]:
120
In [307]:
def square(numbers):
    s = []
    for n in numbers:
        s.append(n*n)
    return s
In [308]:
square(range(5))
Out[308]:
[0, 1, 4, 9, 16]
In [309]:
def toint(seq):
    i = []
    for item in seq:
        i.append(int(item))
    return i
In [310]:
toint(["1","34","5"])
Out[310]:
[1, 34, 5]
In [312]:
def odds(seq):
    o = []
    for item in seq:
        if not even(item):
            o.append(item)
    return o
In [313]:
odds(range(20))
Out[313]:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

References