Wednesday, January 30, 2019

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element. Suppose you have a text file or a list or element which contains multiple elements , the enumerate() function can be used to numbering them. As in the example below -I have a file which has multiple lines of text. I can number each line by using this simple technique -Here we open a file and read the lines but while reading we can count the line no by using enumerate.

                                               abc=open('abc.txt')
                                               for count,text in enumerate(abc.readlines()):
                                                   print (count,text)

Also, we can enumerate lists and dictionary with this function in the same way.



Friday, January 18, 2019

Python Trivia Post: .format() function numbering



Look closely at the code snippet given below - 

days = 8
lyrics = "{} days a week is not enough to love you.But I will not be here {1}"
print(lyrics.format(days,"Sunday"))

Can you guess the output of the program? No. It is not what you are thinking. It is an error code - 


ValueError: cannot switch from automatic field numbering to manual field specification


why? As the .format is like an array of elements. So you have to mention the index number to use or you have to leave the numbering blank, so that it can auto-number. You can not use both formats. So in the above program first call of {} and then {1} lead to the error. you can use {0} and {1}  or leave both the places void.

Friday, January 11, 2019

Python Trivia Post: Raw Strings

We generally know that to print a string in python we need to write simply -

print (" You are my sunshine , if you are here , then I am fine !")

But to print a new line we need to write something like this - 

print (" You are my sunshine ,\n if you are here ,\n then I am fine !")

But sometimes we need the raw string, I don't know when but a hacker friend of mine told me it helps while hacking as it is related to raw string searching. To print a raw string write -

print ( r"You are my sunshine ,\n if you are here ,\n then I am fine !") 

and it will print this - 

"You are my sunshine ,\n if you are here ,\n then I am fine !"

Nice one!!!


Thursday, June 14, 2018

Difference of Single Aterisk * to Double Asterisk ** in python argument


The single asterisk in argument is given to read multiple arguments at once . In the below code if we call multiply(3,4,5,6) then the code will read all the inputs and then multiply. Otherwise we can not read multiple arguments.

def multiply(*args):
    total=1
    for arg in args:
        total*=arg
    return total

>>> multiply(3,4,5)
....  60
====================== 
If we want to read a dictionary as argument or arbitrary keyword arguments then ** is needed.e.g.

def accept(**kwargs):
    for keyword, value in kwargs.items():
        print("%s -> %r" % (keyword, value))

>>> accept(foo=2,faa=3,gaa="gaa")
('foo', 2)
('faa', 3)
('gaa', 'gaa')
>>> 

====================== 

Sunday, April 22, 2018

Reportlab Module

Hey guys, I have found a cool module to print anything to pdf format. The name of the module is reportlab. If you have pip installed in your system then simply write the following in command prompt.

>>> pip install reportlab

The reportlab will automatically be detected anddownloaded if you have a proper internet connection.
Below is a simple code to run and print pdf file form python -

from reportlab.pdfgen import *
def hello(c):
    c.drawString(100,100,"Hello World")
c=canvas.Canvas("hello.pdf")
hello(c)
c.showPage()
c.save()

The code will create a file hello.pdf with "Hello World" written on it. If you want to learn more about reportlab below is the link to learn more - 

Sunday, October 22, 2017

How to Create Your Own Module

The simplest way to create your own module is by using function in Python. Python provide a cest way to create your own module. For example suppose you have function like below -

def myModule(wannasay):
'''This module will say whatever you wanna say'''
return "I wanna say"+str(wannasay)
def calculate(x,y): '''This will add two numbers''' return x+y

    
Save the above code by naming it myModule.py and save it in same directory where you want to create a file which will call it.This is the way we have created the module with methods MyModule and calculate. In the program where we need the module we have to do only one thing is just to import it by the 'import' statement. Lets see how it is done -

import myModule

print "I wanna say something"
myModule.myModule("I am a bad ass lier")

print "Now I wanna calculate"
myModule.calculate(4,6) 


Up, we have imported the file. We put the module file in the same location as the file which called it. We can also put the module in the path of python, where the calling file will automatically search.  Now we used the functions in the module the same way we generally use function in python.

You can find the files here to test yourself -
https://drive.google.com/file/d/0Bx4xTppgmBd-N2wtY2ktVUItQm8/view?usp=sharing
https://drive.google.com/file/d/0Bx4xTppgmBd-SWQ3Uk9GWUZPRUU/view?usp=sharing


Monday, October 16, 2017

How to use python to create Union as in C


The below example shows how to use python to create a union and use it.
from ctypes import *
class barley_amount(Union):
   _fields_ = [
   ("barley_long", c_long),
   ("barley_int", c_int),
   ("barley_char", c_char * 8),
 ]
value = raw_input("Enter the amount of barley to put into the beer vat:")
my_barley = barley_amount(int(value))
print "Barley amount as a long: %ld" % my_barley.barley_long
print "Barley amount as an int: %d" % my_barley.barley_long
print "Barley amount as a char: %s" % my_barley.barley_char
  


(ref: gray hat python) 

Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...