Fun with Python: raw_input()

Introduction

This is the first post in the Fun with Python series. It approaches Python not with a view to learning what a variable is or what a function is but rather assumes that you have some background in these things from JavaScript, Java, C, etc. and simply want to do fun stuff with Python without trailing through all this detail all over again.

User input

The aim of this post is to show how we take and use input from the user. The example is hacked together at speed with web searches and educated guesswork while keeping an eye on the documentation. It is tested in version 2.7.5 on the Mac OS X.

The following code does a few things:

  1. creates a file that can be run from Terminal using python filename.py
  2. demonstrates the use of comments
  3. prompts and accepts user input
  4. demonstrates the creation and use of a function
  5. tests equality in combination with a if/elif/else group of statements
  6. concatenates strings
  7. shows how an input string is converted to its int value
  8. adds two int values and converts them to a string
  9. demonstrates the Print command

#!/usr/bin/env python

# the first line is a path to the Python install for the benefit of BSD'ish Unix systems
# see https://docs.python.org/2.7/tutorial/interpreter.html#executable-python-scripts

name = raw_input('Name please-->')    # a raw_input prompt to obtain user input

def greet():
# this is a function
    gender = raw_input('(M)ale or (F)emale?')    # obtains the user's gender as raw_input
    if gender=='F' or gender=='f':    # if a woman then doesn't ask her age
        print 'I\'d never ask a lady her age, but I must say you look fabulous today '+name
    elif gender =='M' or gender =='m':
        age = raw_input('Age please-->')    # asks the man's age
        print 'Hello '+name+', did you know that '+age+' is really young! My best friend is '+str(int(age)+20)+' this year.'    # flatters him
    else:
        print 'Try again'    # unexpected input try again
        greet()    # call this function again

greet()    # first call to function

Note: Each line that continues the one above it is indented four spaces, as is the convention with Python.

Run

To run the code:
  1. Open a text editor
  2. Copy and paste the above code into a new file
  3. Save the file to a location using a .py file extension
  4. Open Terminal
  5. Type python
  6. Leave a space after python and drag the file from Finder to the Terminal window
  7. Press Enter 

follow us in feedly
Endorse on Coderwall

Comments