Make a program that inverts an integer number with two digits

Asked

Viewed 1,060 times

0

You must print the inverted number followed by a final line. No need to print the 0 further left. For example, if the number typed is 30, just print 3 and not 03.

num=int(input())
if num > 0:
    a = num%10
    b = num//10%10
    d = str("%d%d"%(a, b))
    print(d)
else:
    num_ajus = num_ajus *10 + d
    print(num_ajus)

I want when I type the 40 appears 4 not 04.

  • 2

    ignoring the mistakes, do print(int(d))

  • 1

    @Augustovasques In this particular case, it’s much simpler to do a * 10 + b, in accordance with my answer down below :-)

  • If one of the answers below solved your problem and there was no doubt left, choose the one you liked the most and mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.

2 answers

1

Following your code, just convert the contents of the variable d to integer using the function int, this conversion will already remove the zero left, to effect a line break, we can use the "\n":

num=int(input())

if num > 0:
    a = num%10
    b = num//10%10
    d = int(str("%d%d"%(a, b)))
    print(d, "\n")
else:
    num_ajus = num_ajus *10 + d
    print(num_ajus)

See online: https://repl.it/repls/WorstMellowNetworking


Here’s another example of how to do this, so we can work with much more than two numbers.

Turning number into list, reversing order, using Join to convert the list into string and then convert to integer (removes zero):

#Solicito o número
num = input()

#Transformo o número digitado em uma lista
num = list(num)
#Faço a orndenação inversa da lista, aqui eu já teria um resultado bem próximo
num.reverse()
#Converto a lista para uma string e depois para inteiro, isso removerá o zero a esquerda
num = int("".join(num))

#Exibo o número e a quebra de linha
print(num, "\n")

See online: https://repl.it/repls/SunnyQuerulousDevices

  • Excuse the question I’m new to what would be . Join

  • It is a string method, it allows concatenating the data present in a list for example, separating it with the value present in the string: https://docs.python.org/3/library/stdtypes.html#str.Join

  • Take a look at this example here, it’s very simple: https://repl.it/repls/HumbleDistinctTitle

  • Thank you Daniel, I’m new to this world and I’m having a hard time on some of my college tests

  • Imagine, good studies! :)

1

No need to string numbers

You started well, using math to get the digits of the number separately. Just keep using math to get the final result:

# ATENÇÃO: o código só funciona para números com 2 algarismos (mais sobre isso no final da resposta)
num = int(input())

# assumindo que o número só tem 2 dígitos, não precisa fazer num // 10 % 10
dezena = num // 10
unidade = num % 10
print(unidade * 10 + dezena)

All right, that’s it, end.

Turn the digits into a string, only to turn this string into a string int, although it works, it is an unnecessary turn (as it is new in the area, already learn that "working is different from being right").

You already had the knife and the cheese in hand (the digits), but instead of cutting (making a simple bill), tried to attach the knife on a chainsaw...

Turning into a string would only be justifiable if you needed to format the number (for example, putting zeros on the left or something like that), but since you only had to print the numeric value and nothing else, you don’t have to go all the way around. Don’t complicate what can be solved simply.


The print already includes a line break at the end, and it is unclear if you want to add another line breaking. If this is the case, do:

print(unidade * 10 + dezena, "\n")

Although the print, for default, includes a space between the parameters, then a space will be printed after the number. Visually it won’t make a difference in this case, but in programming any character, including those that we don’t "see", as spaces and TAB’s, can make a difference in many cases. Then you can eliminate this space by changing the tab:

print(unidade * 10 + dezena, '\n', sep='')

But as you are using Python 3, there are other better options like method format and f-string (the latter as of version 3.6):

print('{}\n'.format(unidade * 10 + dezena))

# ou, em Python >= 3.6
print(f'{unidade * 10 + dezena}\n')

Another important detail is that the above code only works for numbers with exactly two digits (which by the title of the question, implies that it is a requirement).

I saw that you used num // 10 % 10 to obtain the digit corresponding to ten, but this is only necessary if the number has three or more digits. If you have exactly two digits, use num // 10 is enough.

Anyway, the program does not validate if the number has exactly two digits. If it has only one, the code above (and also the first code of the another answer) failure - if the number is 3, for example, the result is 30, see.

In that case you could include a check:

if 10 <= num <= 99:
    # usa o código acima
else:
    print('O número deve ter 2 algarismos')

Or, if you want to accept any number of digits, including negative numbers (for example, -123 flipped -321), then use a more general algorithm - also using only good old math:

x = abs(num) # se o número for negativo, troca o sinal
inverso = 0
while x > 0:
    inverso = inverso * 10 + x % 10
    x //= 10
if num < 0: # se o número é negativo, troca o sinal
    inverso *= -1
print(f'{inverso}\n')

If you want to delve into this question of flipping digits and printing them, there’s a little more detailed discussion in this answer.


The solution with list of another answer It would be interesting if you already got a list of the digits. But creating the list, invert and join everything to only at the end convert to number is not a good solution, because if it is not typed a number, will only give error at the end, after you already do all the work. If the program will work with numbers, then continue to do the conversion at the beginning (with int(input())) because if a number is not typed, now gives error right at the start and you don’t have all the reverse work for no reason.

Not to mention that, if the idea is only to invert the string that was typed, nor needed to use list.

Finally, the ideal would be to validate what was typed and only proceed if it is a number (example).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.