gbucks
gbucks

Reputation: 11

Python: swapping digits in a number

This is the program I'm trying to write:

Write a program that always produces the sum of two three-digit numbers, derived from the difference of two other three-digit numbers, as 1089, provided that the originally chosen number’s first and third digits differ by two or more. For this to happen, prompt the user to give you a three-digit number, e.g., 532. Take this number, 532, exchange the first and last digits to get 235. Now subtract 235 (the smaller of the two numbers) from 532 (the larger of the two numbers), and the result is 297. Take the difference, 297, and switch its first and third digits to get 792. Add 297 to 792, and the result is 1089. If the user does not get 1089 as the result, notify him/her that the original entry’s first and last digits differed by less than 2.

This is what I have so far and it's giving me an error. I'm new to python and programming so if you could help me out, it would be much appreciated.

This is what I have so far:

Have user give 3 digit number

threeDigit = str(input("Please enter a 3 digit number without spaces between the numbers.\t"))

#Exchange first and last digits

exchangedNumber = str(threeDigit)[::-1]
print(exchangedNumber)

#Subtract smaller number from greater one

numberOne = exchangedNumber - threeDigit
numberTwo = threeDigit - exchangedNumber

if exchangedNumber>threeDigit: print(numberOne)

if threeDigit>exchangedNumber: print(numberTwo)

Upvotes: 0

Views: 7854

Answers (2)

toubali
toubali

Reputation: 1

Another suggestion :

threeDigit = str(input("Please enter a 3 digit number without spaces between the numbers.\t"))

print(threeDigit)
exchangedNumber = str(threeDigit)[::-1]
print(exchangedNumber)

substractexchangednumber = abs(int(exchangedNumber) - int(threeDigit))

print(substractexchangednumber)
exchangedNumber = str(substractexchangednumber)[::-1]
print(exchangedNumber)
print(substractexchangednumber + int(exchangedNumber))

Upvotes: 0

Chetan_Vasudevan
Chetan_Vasudevan

Reputation: 2414

You may need this to achieve your result

numberOne = int(exchangedNumber) - int(threeDigit)
numberTwo = int(threeDigit) - int(exchangedNumber)

You need to convert them to integer type in order to get your expected results, which initially was string type.Learn more about type conversions

Upvotes: 1

Related Questions