Input¶

🎨 input¶

In [ ]:
%%file input_demo.py
response = input('What is your name: ')
print(f'You said your name is {response}.')

input_demo.py¶

NOTES

  • demonstrate input in the PyCharm console and in a script.
    • create a file named input_demo.py with a simple prompt-input-print example.

👩🏼‍🎨 number_guess.py¶

Randomly pick a number between 1 and 100.

Prompt the user for a guess.

  • If the guess is correct, print "Correct!", display the number of guesses ('You took 6 guesses.'), and exit
  • If the guess is lower than the number, print "Lower"
  • If the guess is higher than the number, print "Higher"

NOTES

  • Draw it out
    • Flow chart
  • How do you get the target number?
  • How do you structure the input loop?
  • How do you keep track of the number of guesses?
In [ ]:
import random

def main():
    goal = random.randint(1, 100)
    guess_count = 0
    while True:
        response = input("Guess the number: ")
        value = int(response)
        guess_count += 1
        if value == goal:
            print("Correct!")
            print(f'You took {guess_count} guesses.')
            return
        elif value < goal:
            print("Higher")
        else: # value is > goal
            print("Lower")
            
main()  # Use __name__=='__main__' in class

👨🏾‍🎨 clues.py¶

You have a file that contains sets of clues and answers.

Randomly select a set of clues and their associated answer.

Display the clues, one at a time, to the user and prompt a guess. If the guess matches the answer, print "Correct!", otherwise continue.

If the user runs out of clues, print "I'm sorry, you ran out of clues." and exit.

example_clues.txt¶

NOTES

  • Draw it out
    • Flow chart
  • How do you parse the input?
    • Show how to use file.read() to get the whole file as a single string. What do we split on?
    • How do we select a block at random?
    • How do we parse the answer from the clues?
    • How do we turn the block of clues into a list of clues?
In [ ]:
%%file example_clues.txt
Nephi
***
A character in the Book of Mormon
He built a boat
His father's name was Lehi
---
Helaman
***
A character in the Book of Mormon
He was named after his dad
He was a chief judge
Kishkumen tried to kill him
---
Jael
***
A character in the Bible
Her story is in the book of Judges
She was handy with a tent stake
She killed Sisera
In [ ]:
import random

def load_clues(filename):
    with open(filename) as file:
        return file.read().split('---\n')

def parse_block(clue_block):
    answer, clues = clue_block.split('***\n')
    answer = answer.strip()
    clues = clues.split('\n')
    return answer, clues

def play(clue_block):
    answer, clues = parse_block(clue_block)
    
    for clue in clues:
        print(clue)
        response = input("Guess: ")
        if response == answer:
            print('Correct!')
            return
    print("I'm sorry. You ran out of clues.")
    
    
def main(filename):
    clue_blocks = load_clues(filename)
    
    clues = random.choice(clue_blocks)
    
    play(clues)

main('example_clues.txt')  # Use sys.argv[1] in class and __name__=='__main__'    

👩🏾‍🎨 Data Entry¶

You are helping to register people for an event.

Your program should ask whether you want to register a person or quit. The user types 'R' or 'r' to register someone, and 'Q' or 'q' to quit.

If the user opts to register someone, they should enter the particpants first name, last name, and major. Your program will then assign each person randomly to a group (1-6).

When the user opts to quit, write all the information (name, major, group) for each participant into a file, which will be printed and cut up later to create information slips for each person.

Once the data has been written to the file, print "Information written to {file}"

data_entry_output.txt¶

NOTES

  • Draw it out
    • Flow chart
  • Do you gather all the data first, then save it all at once? Or do you save each entry as it comes in?
    • What are the pros and cons to each approach?
    • What happens to your data if the program crashes before writing the information to a file?
    • What if you needed to sort the information by group number before writing to the file?
  • Use .lower() to simplify the response comparisons
  • How to format the output?
    • Single write? Multiple write? Pros and cons?
In [ ]:
%%file data_entry_output.txt
Bean, Gordon
Bioinformatics
Group 4

------------------

Rawlings, Susan
Construction Management
Group 3

------------------

Ballard, William
Vocal Performance
Group 6

------------------
In [ ]:
# This example uses the read-all-then-write-all strategy\

import random

def enter_data():
    first = input("First name: ")
    last = input("Last name: ")
    major = input("Major: ")
    group = random.randint(1,6)
    
    return first, last, major, group


def get_data():
    data = []
    while True:
        response = input('\nWhat do you want to do?\nRegister a person (R/r)\nQuit(Q/q)\n: ')
        if response.lower() == 'q':
            return data
        elif response.lower() == 'r':
            data.append(enter_data())
        else:
            print(f'Unrecognized option: {response}')

            
def write_data(file, data):
    for (first, last, major, group) in data:
        file.write(f'{last}, {first}\n{major}\nGroup {group}\n\n------------------\n\n')

    
def main(output_filename):
    data = get_data()
    with open(output_filename, 'w') as file:
        write_data(file, data)
    print(f'Information written to {output_filename}')
    

main('demo_output.txt')  # Use sys.argv[1] in class and __name__=='__main__'
In [ ]:
# This example uses the write-as-you-go strategy

import random

def enter_data():
    first = input("First name: ")
    last = input("Last name: ")
    major = input("Major: ")
    group = random.randint(1,6)
    
    return first, last, major, group


def data_loop(file):
    while True:
        response = input('\nWhat do you want to do?\nRegister a person (R/r)\nQuit(Q/q)\n: ')
        
        if response.lower() == 'q':
            return 
        
        elif response.lower() == 'r':
            first, last, major, group = enter_data()
            write_data(file, first, last, major, group)
            
        else:
            print(f'Unrecognized option: {response}')

            
def write_data(file, first, last, major, group):
    file.write(f'{last}, {first}\n{major}\nGroup {group}\n\n------------------\n\n')

    
def main(output_filename):
    with open(output_filename, 'w') as file:
        data_loop(file)
    print(f'Information written to {output_filename}')
    

main('demo_output.txt')  # Use sys.argv[1] in class and __name__=='__main__'main('demo_output.txt')

Key Ideas¶

  • input
  • Input loops
    • User interaction
    • Data entry