Home > Net >  Reverse number in Python
Reverse number in Python

Time:03-26

I have a homework to make a program that can reverse an input number, but have a requirement to return a sentence with no error when the input is not a number (i.e. words or sentence). For example, when I input abc the program will return Error, please input a number! How can I make it return a sentence when input a str This is the code I've done so far.

def reverse_num(x):
    x = num
    x = str(x)
    
    if x[0] == '-':
        a = x[::-1]
        return f"{x[0]}{a[:-1]}"
    else:
        return x[::-1]

num = input("Enter an integer (positive or negative): ")
print (reverse_num(num))

Noted that the requirement is to reverse both positive and negative number with cannot be return str, but my code return all of them in reversed.

CodePudding user response:

Let's Break Your Problem in 2 Function:

A function to reverse and a loop to read until you get a number or user cancels:



    def reverse_input(num):
        if num[0] == "-":
            temp = num[:0:-1]
            return (-int(temp))
        return int(num[::-1])
    
    while True:
        num = input("Enter Number")
        if num[0] == "-":
            flag = num[1:].strip().isdigit()
        else:
            flag = num[:].strip().isdigit()
        if flag:
            print("User input is Number")
            print(reverse_input(num))
            break
        else:
            print("User input is string")
            resp = input("Would You like to try Again? Enter Y to try and N to Cancel")
            if resp == 'n' or resp == 'N':
                print("Sorry Execute Again")


What does it do ?

  • It reads input from user. Input returns string always.
  • First, we check if Entered String had negation sign or not. If it is there we'll test string skipping negation sign. Otherwise, we will use whole string.
  • We will check if entered string is number using built-in isdigit() function. And Call function to get reversed string.
  • Function will reverse string and typecast to integer with sign.

CodePudding user response:

You may use try-except statements

try:
    x = int(num)
    x = str(x)
    #rest
except ValueError:
     #error message 
  • Related