Introduction
Python is a popular high-level programming language that is widely used for various applications, including web development, data analysis, and automation. In this article, we will discuss how to write a Python program to input a 4-digit number and reverse its first and last digit.
Requirements
To write a Python program to reverse the first and last digit of a 4-digit number, we will need the following:
- Python installed on your system
- A code editor or IDE to write and execute the code
- Basic knowledge of Python programming
Writing the code
Step 1: Input the 4-digit number
To input the 4-digit number, we will use the input() function, which allows the user to enter a value from the keyboard. Here is the code to input the 4-digit number:
num = int(input("Enter a 4-digit number: "))
Step 2: Extract the first and last digit
To extract the first and last digit of the 4-digit number, we can use the modulus operator (%) and integer division (//) operator. The modulus operator returns the remainder when one number is divided by another, while the integer division operator returns the quotient without the remainder. Here is the code to extract the first and last digit:
first_digit = num // 1000
last_digit = num % 10
Step 3: Reverse the first and last digit
To reverse the first and last digit of the 4-digit number, we can use string concatenation to join the last digit, the middle two digits, and the first digit. Here is the code to reverse the first and last digit:
reversed_num = str(last_digit) + str(num % 1000 // 100) + str(num % 100 // 10) + str(first_digit)
Step 4: Print the reversed number
To print the reversed number, we can use the print() function. Here is the code to print the reversed number:
print("The reversed number is:", reversed_num)
Complete Python Code
Here is the complete Python code to input a 4-digit number and reverse its first and last digit:
num = int(input("Enter a 4-digit number: "))
first_digit = num // 1000
last_digit = num % 10
reversed_num = str(last_digit) + str(num % 1000 // 100) + str(num % 100 // 10) + str(first_digit)
print("The reversed number is:", reversed_num)
Output
Enter a 4-digit number: 2347 The reversed number is: 7342
Conclusion
In this article, we discussed how to write a Python program to input a 4-digit number and reverse its first and last digit. We used basic Python programming concepts such as input() function, modulus operator (%), integer division (//) operator, string concatenation, and print() function to accomplish the task. By following this article, you should now be able to write Python programs to reverse the first and last digit of a 4-digit number.
Comments
Post a Comment