0

I want user to enter random numbers. I run a while loop until the user enters 0.

while input()!=0:
    print "Your number is:...??"

My question is: Are there any special variables (like $_ in Perl) using which I can access the user input? For example (in the above case) I want to print what the user has entered.

2 Answers 2

2

You need to assign the result to a variable:

s = None
while s != 0:
  s = int(input("Enter number: "))
  print("Your number is: {}".format(s))

This is a python3 example. For python 2.x you should be using raw_input instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Hmm.. It seems we can not run this loop without creating a variable. Thank you.
1

An alternative method is to use iter and provide a callable:

for num in iter(lambda: int(raw_input('Your number is: ')), 0):
    print 'You entered', num

4 Comments

This is nice. According to the docs, the value of the callable will be returned unless it is the sentinel which will raise StopIteration.
@Jon This is nice method. Thank you. But I never clearly understand what lambda exactly does. Any help is appreciated.
@Holmes lambda creates a callable... You can think of it as a less flexible def... So the above could define def somefunc(): raw_input('Your number is: ') and instead of the lambda, use somefunc.... - see docs.python.org/2/reference/expressions.html#lambda
@Holmes In fairness, I should point out although I prefer this method - it's not an oft-used syntax of the language, so not all Python programmers will immediately grok it - while everyone will grok the while and break system...

Your Answer

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.