Python Notes-9

In continuation from
Python Notes-8
Python Notes-7
Python Notes-6
Python Notes-5
Python Notes-4
Python Notes-3
Python Notes-2
Python Notes-1

Some important points to review:

Converting ascii to char and vice-versa. Python gives a very good way to do this using chr() and ord() functions.

>>> chr(0)
>>> ord('0')

reverse a string:


python ‘is’ operator compares references

reverse a list in place: (So string and tuple doesn’t have this method)


join a list to create a string.

‘ABC'.join(['My', 'name', 'is', 'Simon'])

Notice that the string join() calls on is inserted between each string of the list argument

['My', 'name', 'is', 'Simon']

Creating a package

Each package in Python is a directory which MUST contain a special file called This file can be empty, and it indicates that the directory it contains is a Python package, so it can be imported the same way a module can be imported.

If we create a directory called foo, which marks the package name, we can then create a module inside that package called bar. We also must not forget to add the file inside the foo directory.

To use the module bar, we can import it in two ways:


from foo import bar

The file can also decide which modules the package exports as the API, while keeping other modules internal, by overriding the __all__ variable, like so:

__all__ = ["bar"]

Global variables

It is recommended to avoid global variable as much as possible because it make the code cryptic and hard to debug but sometime you want to get things done fast and easy.

In python you can access global variable wherever you want but when you assign something into it becomes slightly tricky. The assignment creates a new local variable in that scope(weird huh). It may be made like this to make life tough as changing global variable here and there in the code will result in problems hard to track down.
So whenever you want to change global variable in different scope you have to specifically tell python that you are doing this knowingly by declaring the variable first with global keyword.


var = 9
def test():
  print(var)  # will print 9
  var = 10    # this will not change the global var
              # but will create a new local var named variable.
  print(var)  #10

def func():
  global var
  var = 10    # Now global var is modified 
print(var)   # will print 9

print(var)   # will print modified value 10

To be continued …


3 thoughts on “Python Notes-9

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s