Writing a program that takes a two-digit number # that breaks it

I am currently using Python to create a program that accepts user input for a two-digit number and prints the numbers on one line.

For example: My program will receive a number from a user, just use 27

I want my program to be able to print “The first digit is 2” and “The second digit is 7” I know that I will have to use modules (%), but I'm new to this and got a little confused!

+5
source share
4 answers

Try the following:

val = raw_input("Type your number please: ")
for i, x in enumerate(val, 1):
    print "#{0} digit is {1}".format(i, x)
+2
source

It is not clear from your question whether you want to use %to replace strings or %for remainder.

, mathsy, ints, :

>>> val = None
>>> while val is None:
...   try:
...     val = int(raw_input("Type your number please: "))
...   except ValueError:
...     pass
... 
Type your number please: potato
Type your number please: 27
>>> print 'The first digit is {}'.format(val // 10)
The first digit is 2
>>> print 'The second digit is {}'.format(val % 10)
The second digit is 7
+1

Think of a two-digit number as if it is a string. It’s easier to take every number. Using str () will change the integer per line. Modules allow you to place these lines in the text.

Assuming the user enters 27 into the num variable, the code:

print 'The first digit is %s and the second digit is %s' % (str(num)[0], str(num)[1])
0
source

Another way of coding Python:

val = raw_input("Type your number please: ")
for i in list(val):
    print i

Note: valread as a string. For whole manipulations use list(str(integer-value))instead

0
source

All Articles