Input data to the program from the keyboard.

Another way of inputting data is straight from the keyboard after starting the program. This is convenient for short strings like the keyword ‘HYPNOTIZABLE’. In this case the program uses the python command 'raw_input()', which stops the program running and asks for the keyword. After you’ve typed it and hit the Return key, the program gets going again.

Here's an example that stops the program, prints in the Shell the message ”Enter the key & press Return”. The program then waits while you type the key, and then prints it out in the Shell.

key = input("Type the key & press Return ");
for j in range(len(key)):
    print (key[j],)

It would be a good idea to check for mistakes, such as typing a punctuation mark or a number rather than a key letter, and repeating the input request if a mistake is found.

This step of repeating a section of program is done using the python command ‘while()’ at the outset. So if I have a number ‘x’ and I want to keep adding 1 to it until it reaches 5, my program would be:

x=0;
while(x<5):
    x=x+1
    print x,
print “all done”

The program will keep doing the indented section, incrementing ‘x’ and printing it, until ‘x’ gets to 5 when it will print “all done”. Try it out for yourself.

Now, coming back to our inputting 'HYPNOTIZABLE', we want to ask for the key, check it’s OK and, if it’s not, repeat the request:

    program sets a variable ‘got_key’ = zero
    program asks for keyword
    human inputs keyword
    program puts got_key = 1
    program looks at each character of keyword:
        if the character is lowercase, make it upper case
        if the character is not A to Z make got_key=0
    if got_key=0 go back to ‘program asks for keyword’

These program lines carry out the task:

got_key=0
while got_key==0:
    key = input("Enter the key & press Return ");
    key=key.upper()
    got_key=1
    for j in range(len(key)):
        if(key[j]<'A' or key[j]>'Z'):
            got_key=0
print(key)

PREVIOUS          NEXT