0

I am trying to learn python, I was trying write C/C++ code i used before in python, can anyone help me find whats wrong in this code....

#print 1st for 1 -> st or 2nd for 2 -> nd , etc
x = int(input('Enter a number :'))
temp = x
while temp>0:
 temp = temp % 10
if temp == 1:
 print (x, "st")
elif temp == 2:
 print (x, "nd")
elif temp == 3:
 print (x, "rd") 
else:
 print (x, "th")

and can you suggest few goods books to learn python, for now i was reading the documentation and its not for beginners...and i know C/C++

Fred Foo
365k80 gold badges765 silver badges852 bronze badges
asked Feb 12, 2012 at 15:48
1
  • print (3, "rd") outputs 3 rd. Use e.g. print(x, "rd", sep='') to avoid that space. Commented Feb 12, 2012 at 16:04

2 Answers 2

7

Let's see how this:

temp = x
while temp>0:
 temp = temp % 10

works, using an example (x=12345).

temp = 12345
12345>0
temp = 12345%10 = 5
5>0
temp = 5%10 = 5
5>0
temp = 5%10 = 5
...

So it's an endless loop!

To get the last digit (which is probably what you want) just do this:

temp = x%10
answered Feb 12, 2012 at 15:55
Sign up to request clarification or add additional context in comments.

Comments

0

Regarding good books to learn Python, I would recommend Head First Python. It is very easy to understand and make use of your knowledge in C/C++.

answered Feb 12, 2012 at 16:07

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.