Python IO

CSCI 1913 – Introduction to Algorithms, Data Structures, and Program Development
Adriana Picoral

input function

  • text-input and text-output to user are important for testing and debugging
  • You rarely use them when writing “real code”
  • both operations are done with functions in python
  • Both show off something weird about python function

input function

  • input()will wait for user input and return as a string
  • input("prompt")will print a prompt and then wait for user input return as a string
  • Often combined with type-changing functions to type cast.
user_input = input("Enter a number: ")
number = int(user_input)

Input validation

Remember that type casting fuctions like int() and float() will throw errors if a string argument has non-numeric characters

When do we use input and print?

  • very rarely
  • print sends data to end-user, can’t be used elsewhere.
  • input reads data from end-user, can’t be from elsewhere.

This function is useless and I hate it:

def isEven (x):
  if x % 2 == 0:
    print("even")
  else :
    print("odd")

Exercise

Write a basic number guessing game. Here’s some code to get you started:

import random

MIN = 1
MAX = 100
SECRET = random.randint(MIN, MAX)
  • The program should repeatedly ask the user to guess a number
  • if the user guesses too large report “smaller”
  • if the user guesses too small report “larger”
  • if the user guesses right, report “correct” and exit.

A possible solution

How do we add input validation to this solution? (to ensure int() won’t throw an error)

import random

def guess(user_input, secret):
    user_input = int(user_input)
    if user_input == secret:
        print("correct")
        return True
    if user_input > secret:
        print("smaller")
        return False
    if user_input < secret:
        print("larger")
        return False

def play_game(secret):
    user_input = input("Guess the number: ")
    while not guess(user_input, secret):
        user_input = input("Guess the number: ")


if __name__ == "__main__":
    MIN = 1
    MAX = 100
    SECRET = random.randint(MIN, MAX)
    play_game(SECRET)

Quiz 02

You have 10 minutes to complete the quiz

  • No need for comments or doc strings, no need to include the tests in your solution, no need for if __name__. Just write your function and what’s inside the function
  • Raise your hand when you’re done, a TA will come and grab your completed quiz

HINTS:

  • use the keyword def to define a function
  • you can use % to determine if a number is odd (the remainder of the division by two is not zero)