Aviram
Aviram

Reputation: 3

Try and Except with Conditionals in Python

I am a beginner and wrote the following program as part of a Python exercise:

try:
    hours = raw_input ('Enter number of hours \n')
    int(hours)
    rate = raw_input ('Enter your hourly rate \n')
    int(rate)
except:
    print 'Enter an integer value'
    quit()
if hours > 40:
    overtime = hours - 40
    base = 40*rate
    additional = overtime * (1.5 * rate) 
    print 'Your total wage including overtime is', additional + base
else:
    wage = rate * hours
    print 'Your total wage before tax is', wage

However, I receive a TypeError in line 10 that reads unsupported operand type(s) for -: 'str' and 'int'

What's weird is when I enter hours say as 10 and rate as five, it should skip the first if statement and jump directly to the else...but for some reason that isn't happening. Also, when I made the first version of the same program without the try and except bit:

hours = float(raw_input('Enter number of hours \n'))
rate = float(raw_input('Enter your hourly rate \n'))
if hours > 40:
    overtime = hours - 40
    base = 40*rate
    additional = overtime * (1.5 * rate) 
    print 'Your total wage including overtime is', additional + base
else:
    wage = rate * hours
    print 'Your total wage before tax is', wage

This works fine.

Upvotes: 0

Views: 300

Answers (2)

BattleDrum
BattleDrum

Reputation: 818

Your Conversion from string to int is not saved into hours. To achieve this do this:

hours=int(hours) # this is in the 3rd line of your code. Do the same for rate

Upvotes: 0

Bhargav Rao
Bhargav Rao

Reputation: 52191

int(hours) is not in-place. From the docs

Return an integer object constructed from a number or string x, or return 0 if no arguments are given

You need to re-assign it back to the variable

hours = int(hours)

Upvotes: 1

Related Questions