3

So briefly a simple typewriter effect on Python. It works fine when its not inside a'def'. But when it is defined an error line is not defined occurs... any reason why?

import time

def typing():
    global line
    for letter in line:
        time.sleep(0.03)
        print(letter, end='')

def loop():        
    line ='I am gay'
    typing()
    print('')
    line ='Are you also gay?'
    typing()
    print('')
    loop()
loop()
wonea
  • 4,783
  • 17
  • 86
  • 139
Yo LEE
  • 55
  • 1
  • 5

3 Answers3

3

I would simplify it to pass line is as an argument to make it a little cleaner. Also, the reason it isn't working is because the output actually doesn't print until the function finishes running! see How to flush output of Python print?

Here is a working version of your program:

import sys
import time

def typing(l):
    for letter in l:
        print(letter, end='')
        sys.stdout.flush()
        time.sleep(.14)

def loop():
    line ='I am gay'
    typing(line)
    print('')
    line ='Are you also gay?'
    typing(line)
    print('')

loop()

if you're using python 3.3+, you could set the flush argument on print.

print(letter, end='', flush=True) to avoid using sys.

def typing(l):
    for letter in l:
        print(letter, end='', flush=True)
        time.sleep(.03)

fun question!

Community
  • 1
  • 1
Nick Brady
  • 6,084
  • 1
  • 46
  • 71
1

That is because when you use global line then your code should have the line variable globally defined.

import time

line = ''

def typing():
    global line
    for letter in line:
        time.sleep(0.03)
        print(letter, end='')

def loop():        
    line ='I am gay'
    typing()
    print('')
    line ='Are you also gay?'
    typing()
    print('')
    loop()
loop()
Varad
  • 920
  • 10
  • 25
  • Then you would also need `global line` inside `loop()`. It's better to pass it as an argument to `typing()` as suggested above. – berna1111 Mar 22 '17 at 01:10
  • 1
    @berna1111 You're right. But I answered his question since he wanted to know why that error is happening. However there are better solutions than that. My solution was to just make him understand when he has a global inside a function the variable should be globally set otherwise he is likely to get the issue :) – Varad Mar 22 '17 at 01:13
1

This is because you're declaring global line at wrong place;

Try declaring it in loop() as it's your main function (or initially called function) here:

import time

def typing():
    for letter in line:
        time.sleep(0.03)
        print(letter, end='')

def loop():  
    global line      
    line ='I am gay'
    typing()
    print('')
    line ='Are you also gay?'
    typing()
    print('')
    loop()
loop()

DEMO https://repl.it/G7Zw

Nishanth Matha
  • 5,993
  • 2
  • 19
  • 28