Python 練習實例29
python 練習實例29
題目:給一個不多于5位的正整數,要求:一、求它是幾位數,二、逆序打印出各位數字。
程序分析:學會分解出每一位數。
程序源代碼:
實例(python2.x):
#!/usr/bin/python # -*- coding: utf-8 -*- x = int(raw_input("請輸入一個數:\n")) a = x / 10000 b = x % 10000 / 1000 c = x % 1000 / 100 d = x % 100 / 10 e = x % 10 if a != 0: print "5 位數:",e,d,c,b,a elif b != 0: print "4 位數:",e,d,c,b, elif c != 0: print "3 位數:",e,d,c elif d != 0: print "2 位數:",e,d else: print "1 位數:",e
實例(python3.x):
#!/usr/bin/python x = int(input("請輸入一個數:\n")) a = x // 10000 b = x % 10000 // 1000 c = x % 1000 // 100 d = x % 100 // 10 e = x % 10 if a != 0: print ("5 位數:",e,d,c,b,a) elif b != 0: print ("4 位數:",e,d,c,b) elif c != 0: print ("3 位數:",e,d,c) elif d != 0: print ("2 位數:",e,d) else: print ("1 位數:",e)
以上實例輸出結果為:
請輸入一個數: 23459 5 位數: 9 5 4 3 2
請輸入一個數: 3472 4 位數: 2 7 4 3