lundi 21 mars 2022

Is there a better way of referring to the index of a digit within an integer? [duplicate]

Python newbie The purpose of the code is to add together the two digits within a random two-digit number (e.g. 11 = 1+1 = 2)

import random

def add_double_digits():
    num = random.randrange(10, 99)
    snum = str(num)

    print(num)
    print(int(snum[0]) + int(snum[1]))

add_double_digits()

I've had to create a variable called "snum" (string number) which converts the number into a string and then back again so that I can get the index of the individual digits. I hope I'm using the correct terminology. Is there a more efficient way of doing this/ am I lacking some fundamental knowledge here or is this the way it should be done? Thanks.




Aucun commentaire:

Enregistrer un commentaire