1

I'm trying to get an accurate age but this doesn't work it gives me errors and sometimes repeats itself. I've been trying to get it to work for hours. But I can't figure it out, I think the problem is in finally. I tried except but it just gives me errors. How should I fix it?

end04 = False                      
while not end04:
    Age = input("Age: ")
    try:
        int(Age)
        end04 = True
    finally:
        if Age[-1:] == 'w':
            Age.replace('w','')
            int(Age)
            Age /= 52
            end04 = True
        elif Age[-1:] == 'm':
            Age.replace('m', '')
            int(Age)
            Age /= 12
            end04 = True
        else:
            end04 = False
            print("Only enter m or w after number or just number")

if I put finally It just repeats saying "Only enter m or w after a number or just number"

If I put except it gives an error (When I enter 3m)

int(Age) ValueError: invalid literal for int() with base 10: '3m'

Lohith
  • 866
  • 1
  • 9
  • 25
  • 2
    "*I'm trying to get an accurate age*" -- help us understand what your program is *meant* to do. Please [edit] your question to show intended input & expected output. – costaparas Feb 14 '21 at 05:45
  • "*this doesn't work it gives me errors and sometimes repeats itself*" -- what errors do you get when you try to run the code, and with what inputs do these errors occur? Please [edit] your question to show the full error messages. – costaparas Feb 14 '21 at 05:46
  • When you do `int(Age)` you aren't assigning the result anywhere. You want `Age = int(Age)`. Similarly for `Age.replace('w','')` and `Age.replace('m', '')`. These functions don't modify `Age`, they return a new value, which you must then assign to `Age`. – costaparas Feb 14 '21 at 06:08
  • And you would want to use `except` rather than `finally`. Your program attempts to convert `Age` to an `int` initially, if it fails, it will then go into the `except` clause. The purpose of `finally` is completely different, as [explained here](https://stackoverflow.com/questions/11551996/why-do-we-need-the-finally-clause-in-python). – costaparas Feb 14 '21 at 06:08
  • As a complete aside, the [tag:python-requests] tag is completely irrelevant here (that's meant to be used for code that utilizes the `requests` library itself), and I'd argue the [tag:list] tag isn't necessary either. – costaparas Feb 14 '21 at 06:14

2 Answers2

1
end04 = False                      
while not end04:
    Age = input("Age: ")
    try:
        int(Age)
        end04 = True
    except ValueError: # Here your are trying to catch the Exception (when m/w in input), so you need to use except with the Exception you want to catch
        if Age[-1:] == 'w':
            Age = Age.replace('w','') # string.replace function return's the replaced string therefore need to assign it back to Age Variable.
            Age = int(Age) # similarly int() also returns the type casted value.
            Age /= 52
            end04 = True
        elif Age[-1:] == 'm':
            Age = Age.replace('m', '')
            Age = int(Age)
            Age /= 12
            end04 = True
        else:
            end04 = False
            print("Only enter m or w after number or just number")

I have fixed your code.

Do also look into,

  1. string.isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Try using that instead of using try except.
  2. The finally block lets you execute code, regardless of the result of the try- and except blocks. But in your case you wanted to catch the Exception when there is a character in the input therefore except is appropriate here.
0

This is how your final program would look like, in simpler way and handling all sort of inputs.

import re

end04 = False
divider = 1
while not end04:
    Age = input("Age: ")
    try:
        age = re.findall(r'\d+\w', Age)
        if len(age) > 0:
            letter = age[0][-1]
            if letter.isnumeric() or (letter in ['w', 'm']):
                if letter in ['w', 'm']:
                    age = int(age[0][:-1])
                    divider = 12
                    if letter == 'w':
                        divider = 52

                else:
                    age = int(age[0])
                print('age', age)
                age /= divider
                print('output', age)
                end04 = True
    finally:
        if not end04:
            print("Only enter m or w after number or just number")

output:

Age: 32
age 32
output 32.0

Age: 32w
age 32
output 0.6153846153846154

Age: 32m
age 32
output 2.6666666666666665
Lohith
  • 866
  • 1
  • 9
  • 25