my python teacher ask to me to write a program that adds the digits in a 2 digit number. e.g. if the input was 35, then the output should be 3 5 = 8. So, a made it on this way:
two_digit_number = input("Type a two digit number: ")
print(int(two_digit_number [0] ) int(two_digit_number [1]))
Is it wrong?
CodePudding user response:
Your answer is correct but I feel like this is a better way:
number = int(input())
print(number // 10 number % 10)
CodePudding user response:
Your code is working fine and nothing wrong with it, but if you wanted to you could simplify it a little using builtins like sum and map. For instance, what map does is apply the first callable argument to an iterable passed in as the second argument (a string of characters in this case).
Here's an example using both those builtins. I also use assert to confirm once that it's a valid two digit number, because otherwise it'll work for any length number, like a five digit number.
two_digit_number = input("Type a two digit number: ")
assert len(two_digit_number) == 2, 'Enter a valid two digit number!'
print(sum(map(int, two_digit_number)))
If you wanted to, you could also rewrite it like this, using map and an assignment using implicit iterable unpacking:
two_digit_number = input("Type a two digit number: ")
first_dig, second_dig = map(int, two_digit_number)
print(first_dig second_dig)
