Thursday, July 26, 2012

Python: AttributeError: 'list' object has no attribute 'join'

Current post is on how to recover from AttributeError: 'list' object has no attribute 'join'.


Started working on python and got struck in 'JOIN' function?

Got the "AttributeError: 'list' object has no attribute 'join' " error when trying to JOIN list in Python?

Just change the list and argument place.

Reason is we are wired to think like  object.some_function arguments but here its like argument.some_function object(s)


List JOIN in Python:


mypythonlist = ['ListElement1', 'ListElement2']
mypytonlist.join('-')   #Incorrect Usage which gave the AttributeError

'-'.join(mypythonlist)  #Correct Usage

# It will return 'ListElement1-ListElement2'

For detailed information refer to 'JOIN' function post

Hope this post saved your time.


Appreciate your feedback via comments. Thanks.

Python: JOIN Function for Iterable

Current post is on how JOIN function works in Python.


Recently started working on Python and got stuck in 'JOIN' function?

Not sure how the JOIN function works?

JOIN Function for iterable in Python:


string str.join(iterable)

where,
          str = string which will be used to append the elements in iterable
          iterable = any iterable in python like list, string

          string = returns the joined string

Confused ??

Reason is we are wired to think like  object.some_function arguments but here its like argument.some_function object(s)


List JOIN in Python:


mypythonlist = ['First', 'Second']
mypytonlist.join('-')   #Incorrect Usage, it will cause AttributeError

'-'.join(mypythonlist)  #Correct Usage

# It will return 'First-Second'


String JOIN in Python:


mypythonstr = 'MyPythonString'
mypythonstr.join('-')  #Incorrect Usage

'-'.join(mypythonstr)   #Correct Usage

# It  will return 'M-y-P-y-t-h-o-n-S-t-r-i-n-g'

I hope now you understand how 'JOIN' function works in Python.


Appreciate your feedback via comments. Thanks.

Python: Converting VbScript Left-Right Function

Current post is on how to convert Left-Right Function of VBScript in Python 3.2.


Converting or migrating a VbScript project to Python?

Stuck in converting Left or Right function of VbScript in Python?


VBScript Left Function:


Left(string, Length)

where,
          string = your text string
          length = number of character from left you want to extract

Example:

myleftstring = Left("Hello from Left, noting more!!!",15);

//myleftstring will contain 'Hello from Left'.


VBScript Right Function:


Right(string, Length)


where,
          string = your text string
          length = number of character from right you want to extract


Example:


myrightstring = Right("Hello from Left, noting more!!!",15);


//myrightstring will contain ', noting more!!!'.


Python: Array Slicing:


Array slicing is done using [ : ] operator.

Example:

text = 'Hello from Python 3.2'
leftslicedtext = text[:11]

//leftslicetext will contain 'Hello from'

rightslicedtext = text[11:]

//rightslicedtext will contain ' Python 3.2'

frombehind = text[-3:]

//frombehind will contian '3.2'

Summarize:


To convert the VbScript Left / Right Function, use the array slicing feature of Python.

It is simple, clean and readable.

Appreciate your feedback via comments. Thanks.

Saturday, July 14, 2012

India Income Tax e-Filling : 2012

Current Post is on how a salaried individual residing in India file tax return online (e-return) for 2011-2012 (A.Y. 2012-2013) from Form 16 & Form 12 BA

Prerequisite: Registered User at Income Tax India e-Filing Site.

If not refer to Steps to register at Income Tax India e-Filing Site.

Sections:


1. Downloading the Form (Excel Sheet).
2. Filling the Form (Excel Sheet)
3. Generating the XML
4. Uploading the XML


1. Downloading the Form (Excel Sheet):


- Login into Income Tax India e-Filling Site with your valid credentials. (PAN number and password)

- Assuming you are a salaried individual with / without income from Other Sources (only Interest Income or Family Pension) , ITR-1 (SAHAJ) is the form that needs to be filled. OR If you had Income from house or other sources, respective ITR form needs to be downloaded.

- To download the ITR-1 (SAHAJ), Go to Download Section, 'e-Filling A.Y. 2012-2013 >> Individual,HUF' menu option.


 

2. Filling the Form (Excel Sheet):


- Unzip the 'ITR1_2012_13_R2' zip file and open the '2012_ITR1_PR18.xls' excel sheet.

- Excel sheet will have 4 sheets.
  1. Income Details
  2. TDS
  3. Taxes Paid and Verification
  4. 80G - Not covered in current post
Basic Instructions:
  • Compulsory Fields - Green Background & Red Color Label
  • Optional Fields - Green Background & Black Color Label
  • Auto-calculated Fields - White Background & Blue Color  Label
Follow the steps mentioned in ITR1 (SAHAJ) Form Filling post which will help you fill excel sheet from Form 16 & Form 12 BA


3. Generating the XML:


- Validate each sheet  by clicking the 'Validate' button present on each sheet

- Click on 'Calculate Tax' button

- Click on 'xml Generate' button

- Click 'OK' on following pop-ups.



- New 'Pre-XML Check' sheet would be created.

- Check the following details:
  • TDS on Salary - If no amount then redo the Generate XML Steps
  • All the Verification Columns
- After verifying all the details, click the 'Save XML' button

- Click 'OK' following pop-ups.

- File named 'ITR1_PANCARD.xml' will be saved on mentioned path.



4. Uploading the XML:


- Login into Income Tax India e-Filling Site with your valid credentials. (PAN number and password)

- Under 'Submit Return' section, select 'Select Assessement Year >> AY 12-13'

- Following screen will be displayed. Select 'ITR-1' and click 'Next'



- Click 'Browse' to select the 'ITR1_PANCARD.xml' file we generated from Excel sheet.



- On Clicking 'Upload' Button, following pop-up will come.




- Select 'OK'

- The XML will be uploaded and following screen will appear.


- From 'here' link, download the ITR-V Form.

- As we didn't digitally signed the XML, we need to send ITR-V Form to nearest Income Tax Office. In current case, the City was 'Bangalore', hence the address of Bangalore Income Tax Office came, where I need to send the ITR- V Form.

- Print the ITR-V Form on normal A4 size paper and signed the Form.

- Send it via SPEED POST or ordinary POST within 120 days post you upload the XML.


Done. We e-Filed our income tax return for 2011-2012 (Assessment Year 2012-2013).

Appreciate your feedback & suggestions via comments.

Thanks.

India Income Tax ITR-1 (SAHAJ) Form Filling

Current Post is on how to fill ITR-1 (SAHAJ) Income Tax Form for 2011-2012 from Form 16 & Form 12BA (A.Y. 2012-2013)

Post covers the filling of ITR-1 (SAHAJ) form for e-Filing. But if you are planning to manual fill the paper form, it will be on similar line.

Friendly advice: Do e-Filing, it is faster, convenient and refunds are quicker.

Assuming you have downloaded the form from Income Tax India e-Filing Site.

- Unzip the 'ITR1_2012_13_R2' zip file and open the '2012_ITR1_PR18.xls' excel sheet.

- Excel sheet will have 4 sheets.
  1. Income Details
  2. TDS
  3. Taxes Paid and Verification
  4. 80G - Not covered in current post
Basic Instructions:
  • Compulsory Fields - Green Background & Red Color Label
  • Optional Fields - Green Background & Black Color Label
  • Auto-calculated Fields - White Background & Blue Color  Label

1. Income Details Sheet:


- Fill the following cells:
  • First Name
  • Middle Name
  • Last Name
  • PAN Number
  • Flat \ Door \ Building
  • Status - I Individual
  • Area \ Locality
  • Date of Birth (DD \ MM \ YYYY)
  • Town \ City \ District
  • State - Select from Drop-down option, don't manual write it
  • Pincode - In hurry don't write your permanent address or office address pincode
  • Sex - Select from Drop-down option, don't manual write it
  • Email Address 
  • Employer Category - Mostly it will be OTH, kindly fill as per your category
  • Return Filed under section - Select from Drop-down 11 - BeforeDueDt 139(1) (if all your taxes are paid and submitting before 31 July 2012)
  • Whether original or revised return - Select from Drop-down respective return.
  • Residential Status - Select from Drop-down respective status
  • Tax Status - Select from Drop-down as per your tax valuation
  • Income from Salary / Pension - Fill the value from Form 16 - INCOME CHARGEABLE UNDER THE HEAD 'SALARIES' 
  • Income from other sources - Fill the total value from other sources
  • Fill the 'Deductions under ChapterVI A' as per Form 16
  • Tax payable on Total Income - Fill the value from Form 16 - Tax on total Income
  • Education cess... - Fill the value from Form 16 - Education cess... 
  • Relief under Section 89 - Mostly 0
  • Relief under Section 90/ 91- Mostly 0

- Following fields will be automatically calculated / filled:
  • 4 Gross Total Income (1+2+3)
  • 7 Total Income (4-6)
  • 10 Total Tax, Surcharge and Education Cess (Payable) (8 + 9)
  • 13 Balance Tax Payable (10 - 11 - 12)
  • 15 Total Tax and Interest Payable (13 + 14)  

2. TDS Sheet:


- Fill the following cells:

  • Under 23 Tax deducted at source from SALARY
  • TAN of Employer - Fill the value from Form 12BA - TAN
  • Name of the Employer - Fill the value from Form 12BA - Name & Address of the Employer
  • Income charged under Head of the salaries - Fill the value from Form 16 -  INCOME CHARGEABLE UNDER THE HEAD 'SALARIES'
  • Total Tax deducted  - Fill the value from Form 16 -  Tax Payable
  • Under 24 Tax deducted at source of Income other then Salary - Fill as per receipt details

3. Taxes Paid & Verification:

 - Fill the following cells:

  • Enter your Bank Account Number - To which Bank Account one needs the cheque \ transfer for refund amount
  • Refund Type - Select from Drop-down 'Yes' for direct deposit, it will be faster
  • MICR Code - MICR Code of Bank
  • Type of Account - Select from Drop-down the account type of Bank Account number you mentioned above
  • Name - Same as in PAN card
  • son/ daugher of - Same as in PAN card
  • Place
  • Date
  • PAN Card
- Following fields will be automatically calculated / filled:
  • 16a  Advance Tax (from item 25)
  • 16b TDS (Total from item 23 + item 24)a
  • 16c Self Assessment Tax (item 25)
  • 17 Total Taxes Paid (16a + 16b + 16c)
  • 18 Tax Payable - Mostly the amount should be zero, unless one has to pay the tax
  • 19 Refund - Check the amount
And we are done finally :). 
I hope it didn't took more then 15-20 minutes to complete the form.

Appreciate your feedback via comments.

Thanks.
Mehul

Friday, July 13, 2012

Python: Global Variable Access

Current post is on how to access the global variables in Python 3.2. 


Global variables can be easily accessed by using the keyword global.

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.

Names listed in a global statement must not be used in the same code block textually preceding that global statement.

Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement.

Example 1: Change the global variable
globalVariable = False

def ChangeGlobalFunction():
      """Function that changes global variable"""
      global  globalVariable  #Global statement
      globalVariable = True

def PrintGlobalFunction():
      """Function that prints global variable"""
      print(globalVariable)

PrintGlobalFunction()
ChangeGlobalFunction()
PrintGlobalFunction()
Output:
False
True

Python: Check for file existence

Current post is on how to check whether file exists on system running Python 3.2.


First import the 'os.path' module.  os.path module implements some useful functions on pathname.

import os.path

Add the following line to check file.
  
os.path.exists(filename)

It returns True if filename exists else returns False


To make sure it is file and it exists, one can use:

os.path.isfile(filename)

It returns True only if the type is of file and it exists else returns False


Example 1: File Check using 'exists' function

      if os.path.exists("HelloWorld.py"):
           print("Hello World")
      else:
           print("No World !!!")

Example 2: File Check using 'isfile' function

      if os.path.isfile("HelloWorld.py"):
           print("Hello World")
      else:
           print("No World !!!")


Python: Message Box in Windows

Current post is on how to show message box in Python 3.2 running on Microsoft Windows OS.


First import the 'ctypes' module. ctypes module provides C compatible data types and allows calling functions in DLLs or shared libraries.

import ctypes

Next we need is the messagebox function pointer

messageBox = ctypes.windll.user32.MessageBoxW  *

After having the function pointer, we just need to call the function with required arguments.

returnValue = messageBox(ParentHandle,Error Text,Title Text,ButtonEnumValue)

where,
           ParentHandle = Handle to parent window
           Error Text = Text one wants to show to end user
           Title Text = Text that will appear on Title bar of message box
           ButtonEnumValue = Which button one needs to show

Detailed information can be found on Microsoft MessageBox Documentation

Based on return value, one can take the required action.

Example 1: Message Box with OK button.

      import ctypes

      messageBox = ctypes.windll.user32.MessageBoxW

      returnValue = messageBox(None,"Message Box!!!","Hello",0x40 | 0x0)


 
Example 2: Message Box with OK-Cancel button & ReturnValue Check


      import ctypes

      messageBox = ctypes.windll.user32.MessageBoxW

      returnValue = messageBox(None,"Message Box!!!","Hello",0x40 | 0x1)

      if returnValue = = 1:
            print("Pressed OK")
     elif returnValue = = 2:
           print("Pressed Cancel")


* Python 3.x takes unicode only.


Disclaimer:

The above post and all the posts in the blog are derived from facts, information, logical interpretation and logical conclusion of printed and internet materials available to me, perceived and produced by 99 gm brain of mine, which by no means always be accurate, consistent and complete.

All the posts are for personal quick reference only.

If any suggestion, correction, misinterpretation, misconception commented, which will be moderated and deleted if required, to avoid unforeseen issues.

If any trademark / copywrite issue is present, do send in a mail and appropriate tag (logo, name, website link) will be attached to the same.

Additional disclaimer will be attached wherever required in the post.