-2

So I'm making a program that types a number using pynput, then adds 1 to that number, hits enter, and keeps going. However, when it hits 10, the program stops working. Here's my code:

from pynput.keyboard import Key, Controller
import time

keyboard = Controller()

#Example keys:
#keyboard.press('a')
#keyboard.release('a')

#Set the variables for the first number:
number = 8

#Define the press release button, for simple use. 
def press_release_char(char):
    keyboard.press(char)
    keyboard.release(char)

#Set start delay:
time.sleep(3)

while number<100:
    press_release_char(str(number))
    press_release_char(Key.enter)
    time.sleep(1)
    print(number)
    number += 1

Can someone help me with this?

1 Answers1

2

It's because string representation of 10 actually consists of two characters: 1 and then 0, so you must account for that accordingly. Basically you should loop over string representation of your number and send all digits separately, so replace your:

press_release_char(str(number))

with more generic approach:

for c in str(number): press_release_char(c)

and you should be good for any number, no matter how many digits you have. In fact the same loop can be used to send any sequence of characters.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
  • Small gripe - if you don't need the index, just `[press_release_char(c) for c in str(number)]`. Also a list comprehension is not needed here since you are not capturing the output. Just `for c in str(number): press_release_char(c)` would work. – r.ook Apr 28 '20 at 17:51
  • Yep, that's a bit over-engeneering. Corrected. – Marcin Orlowski Apr 28 '20 at 17:54
  • @DuckMan if your problem is solved, please mark answer as accepted: https://stackoverflow.com/help/someone-answers – Marcin Orlowski Apr 28 '20 at 18:37