samedi 17 octobre 2020

My code containing if block and replace function working more than I expect but I do not know why

I'm writing a manual currency conversion program and this is my code:

import math


def converter():
    while True:
        def convert():
            hint = '1-eur 2-gbp 3-nzd 4-aud 5-pln 6-aed 7-zar 8-cad 9-chf 10-dkk 11-inr 12-brl 13-hkd 14-pen 15-czk' \
                   ' 16-jpy 17-nok 18-sek 19-qar 20-cny'
            currency_hint = ['EUR', 'GBP', 'NZD', 'AUD', 'PLN', 'AED', 'ZAR', 'CAD', 'CHF', 'DKK', 'INR', 'BRL', 'HKD',
                             'PEN', 'CZK', 'JPY', 'NOK', 'SEK', 'QAR', 'CNY']
            currency_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
            domain_extension = input('Enter domain extension: ')
            if domain_extension[0] == '.':
                domain_extension = domain_extension.replace(domain_extension[0], '')
                print(domain_extension)
            '''if domain_extension[-1] == '.':
                domain_extension = domain_extension.replace(domain_extension[-1], '')'''
            currency = int(input(f'What is the currency? {hint}: '))

            try:
                if currency == currency_list[0]:
                    amount = float(input('How much? ')) * 1.17  # euro
                    return f'You chose extension .{domain_extension} with currency {currency_hint[0]} and it is ' \
                           f'{math.ceil(amount)} USD.'
            except IndexError:
                return 'Try Again'
        me = convert()
        print(me)
        break


converter()

What I'm getting now is: I enter my extension like ....com.... and I choose number 1 which is EUR and I set the amount to 1 for example. In this case I expected to return value like You chose extension .com.... with currency EUR and it is 2 USD., but if fact I'm getting You chose extension .com with currency EUR and it is 2 USD. and I really do not know why.

My assumption is:

My while loop iterates over domain_extension variable and its 1st position to remove . character from the beginning until it has no other . characters, and then goes to the try...except block.

What I did not get is why . at the end are removed? I did not write any codes to replace them with anything. At first I thought if domain_extension[-1] == '.' block was doing that, but when I comment this part, it's still removing . from the end.

And if I comment if domain_extension[0] == '.' block, I get domain name like .....com.....

The question is why am I getting this result? Would you please help me regarding this?

I should note that I am happy I'm getting this result, but because I wrote this code I do not understand why and how it is working and it made me thinking a lot but I got no clear answer yet.

Aucun commentaire:

Enregistrer un commentaire