We help IT Professionals succeed at work.

# Python compiler throwing an error while executing the program ca not defined

sam_2012 asked
Hi Team,

Iam trying to run the below code in python , Iam getting an error while calculating the ca value .Kindly help me with the casue of the error
''' write a program to calulate the gross salary of the employee
if his basic salary less than 2000 then HRA 10% of basic salary
DA 90% of basic salary , ca=10
> 2000 , hra 5%  bs and da 20 percent of basic salary '''

basicSalary=int(input("Enter the basic salary"))
if basicSalary < 2000:
hra=basicSalary * 0.1
da=basicSalary * 0.9
ca=10
else:
hra=basicSalary * 0.05
da=basicSalary * 0.2

grossSalary=basicSalary+hra+da+ca
print (" the gross salary of employees is ",grossSalary)

C:\Users\sam\Desktop\MyPythonPrograms>python mypythonIf3.py
Enter the basic salary2300
Traceback (most recent call last):
File "mypythonIf3.py", line 15, in <module>
grossSalary=basicSalary+hra+da+ca
NameError: name 'ca' is not defined
Comment
Watch Question

## View Solution Only

Excel & VBA Expert
SILVER EXPERT
Most Valuable Expert 2018
Awarded 2015
That's because ca is only initialized if the basic salary is less than 2000.
If the basic salary is greater than or equal to 2000, the else part is executed and ca is not defined in the else part and when the following line gets executed, it finds that ca is not defined but still used in the calculation.

`grossSalary= basicSalary + hra + da + ca`

To handle this, either you initialize ca before the If statement like this...
```ca = 0
if basicSalary < 2000:```
Or initialize it within the else part
```else:
ca = 0
hra = basicSalary * 0.05
da = basicSalary * 0.2```

So you may try this...
```basicSalary=int(input("Enter the basic salary"))
ca = 0
if basicSalary < 2000:
hra = basicSalary * 0.1
da = basicSalary * 0.9
ca = 10
else:
hra = basicSalary * 0.05
da = basicSalary * 0.2

grossSalary= basicSalary + hra + da + ca
print ("the gross salary of employees is ",grossSalary)```

Infrastructure Architect
BRONZE EXPERT
Hi,

To manage wrong input value you can add this code to replace input line:

while True:
try:
basicSalary = int(input("Enter the basic salary"))
except ValueError:
print('invalid input value, please retry with an integer')
else:
break

Commented:
thanks  alot for quick help.
Excel & VBA Expert
SILVER EXPERT
Most Valuable Expert 2018
Awarded 2015
You're welcome Sam!