Write A Python Script To Create A List Where Each Element Of The List Is A Digit Of A Given Number

Given a number as input in a Python program, you have to write a python logic where each and every digit of the number is taken and stored in the form of a list.

The list should contain the digits of the number in the same order.

 

Write A Python Script To Create A List Where Each Element Of The List Is A Digit Of A Given Number

 

Write A Python Script To Create A List Where Each Element Of The List Is A Digit Of A Given Number

Let me take a variable name as a number and ask a user to enter a number using the input function call and convert it into an integer. Let's take another variable named as digits and initialize it to an empty list this variable will be used to store all the digits of a number

number = int(input("Enter a Number : "))
digits = []





Now let's make a copy of the given number by taking a variable named as temp and copying the value of the number to temp.

Use the while loop to perform the modulus and division until the temp value becomes zero.

Take the temp variable and perform the modulus by 10 to get the last digit of the number. Once you get the last digit of a number use the list inbuilt function insert to to add the last_digit variable to the start of the list.  Once the the last digit is added to the start of the list use division by 10 to trim the last digit of the number

temp = number
while temp != 0:
  last_digit = temp % 10
  digits.insert(0, last_digit)
  temp = temp // 10




Once the while loop completes,  the list variable named as digits will store all the digits of a given number. The list variable digit will Store all the digits present in a given number in the same order of the number,  once you execute this Python program you will understand. Using the print function call print the list variable digits.

print(f"Digits of Given Number {number} is {digits}")





Complete Python Working Code
====================================

number = int(input("Enter a Number : "))
digits = []

temp = number
while temp != 0:
  last_digit = temp % 10
  digits.insert(0, last_digit)
  temp = temp // 10


print(f"Digits of Given Number {number} is {digits}")






Output
===================
Enter a Number : 345678
Digits of Given Number 345678 is [3, 4, 5, 6, 7, 8]




Output
===================
Enter a Number : 987654
Digits of Given Number 987654 is [9, 8, 7, 6, 5, 4]




Output
=============
Enter a Number : 980234
Digits of Given Number 980234 is [9, 8, 0, 2, 3, 4]




Conclusion
================
Execute the above Python program by yourself  by providing the integer number as an input,  note down the result.


Comment down below if you have any suggestions to improve the above Python program




Post a Comment

0 Comments