4
while int(input("choose a number")) != 5 :

Say I wanted to see what number was input. Is there an indirect way to get at that?

EDIT Im probably not being very clear lol. . I know that in the debugger, you can step through and see what number gets input. Is there maybe a memory hack or something like it that lets you get at 'old' data after the fact?

jason
  • 4,721
  • 8
  • 37
  • 45
  • 1
    If you didn't assign it to anything, there's no way to refer to it. – Mike Christensen Jul 19 '13 at 17:03
  • 5
    Its definitely not `5`. ;) –  Jul 19 '13 at 17:03
  • 1
    So If i understand your question, you want to reference `input` after the while loop? –  Jul 19 '13 at 17:04
  • yeah, just currious if its possible. Not worried about it being correct or a good way, just if its even possible. – jason Jul 19 '13 at 17:12
  • @jason Both of the answers provided are correct and do work, but Jon Clements answer is more efficient and less code. But Stephens answer is easier to read. –  Jul 19 '13 at 17:25

5 Answers5

7

Nope - you have to assign it... Your example could be written using the two-argument style iter though:

for number in iter(lambda: int(input('Choose a number: ')), 5):
    print number # prints it if it wasn't 5...
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
2

Do something like this. You don't have to assign, but just make up an additional function and use it every time you need to do this. Hope this helps.

def printAndReturn(x): print(x); return(x)

while printAndReturn(int(input("choose a number"))) != 5 :
      # do your stuff
rnbguy
  • 1,369
  • 1
  • 10
  • 28
1

No, there is no way to access that input the way you did it, you would have had to store it. Here's a "hello world" level example

val = int(input("choose a number"))
while val != 5 :
  val = int(input("choose a number"))
Stephan
  • 16,509
  • 7
  • 35
  • 61
1

Semi-related hacky solution that technically answers your question but not really:

If you run this in the interactive python environment (the thing with the >>>), you can do this

>>>while int(input("choose a number: ")) != 5 :
...  print _
...
choose a number: 2
2
choose a number: 5
>>>

Note that this only works in the interactive environment.

Community
  • 1
  • 1
Stephan
  • 16,509
  • 7
  • 35
  • 61
0

Not simply. If you attempt to read past values from stdin it'll give you an UnsupportedOperation exception. You could wrap stdin with a custom file buffer object that reads stdin when you want it and lets you seek.

import sys
from io import StringIO


class InputHistoryBuffer(StringIO):
    def __init__(self):
        super().__init__()
        self._stdin = sys.stdin
        sys.stdin = self

    def readline(self) -> str:
        value = self._stdin.readline()
        self.writelines([value])
        return value


input_history = InputHistoryBuffer()
x = input(":")

sys.stdin.seek(0)
print(sys.stdin.read(len(x))) 
Subham
  • 397
  • 1
  • 6
  • 14