Python How To : Examples

Python How ToI’ve received a bunch of email’s requesting that I provide more sample Python code. Some people learn better by seeing somebody work through examples. So, here I’ll work through some simple to understand examples that should teach you a bunch about Python.

Note: They will start out simple and work up to file I/O (Reading and Writing to files)


Customer Information Input with Python

Let’s say a client wants to greet a customer, get their name and respond using the customers name. I’ll provide the simple code below. Just note that a # signifies a comment. Python ignores everything that proceeds it. I’ll use the comment section of the code to explain what I’m doing.

print(“Hi”)
# Prints the word Hi on the screen

name = input(“What is your name: “)
# Displays the words in quotes on screen and stores the name entered in a variable named name

print(“Hi”, name)
# Displays the word Hi followed by the name given by the customer

Your customer now wants to except the customers name and age. He wants to tell the customer how their age relates to his own as well. (He’s 35)

print(“Hi”)
name = input(“What is your name: “)
print(“Hi”, name)
age = input(“How old are you: “)

print(type(age))
“””This is not needed for this problem, but is here to make a point. This line would output to the screen. This is a string and can’t be compared to an integer, which 35 is. If I tried to below, it would always return the value false. That’s why I perform the type conversion below. You write multiple line quotes using triple quotes by the way“””

yourAge = int(age)
# I use the function int, to convert the string into an integer

if yourAge == 35:
”’If the variable named yourAge is equal to 35 the next line is executed, if not you skip to the code that proceeds the word else”’

print(“Your the same as me”)
else: print(“Your a different age from me”)
# The code that proceeds else is only reached if yourAge doesn’t equal 35

print(type(yourAge))
# Would print this to the screen

You start messing around with some built in functions in Python to pass the time. Here is what you discover:

print(“Hi”)
name = input(“What is your name: “)
print(“Hi”, name)
age = input(“How old are you: “)

print(id(age))
”’Everything in Python is an object. This means that all of your variables have built in variables and functions you can use to manipulate them. More on this later. You also learned that most variables a immutable in Python. This means that each time you change a variable, a whole new object is created. When an object is created, it’s stored in memory and given a new id. This line will print out that id. This id is 21865856. If I changed the value of age it would print out a new id”’

yourAge = int(age)

if yourAge == 35:
print(“Your the same as me\n”)
”’ \n is used in strings to represent a newline. This forces a new blank line to be printed to the screen”’

else: print(“Your a different age” +
” from me\n”)
”’ Here I show you how to print a multi-lined string in Python. You could also do this with triple quotes”’

print(type(yourAge))

print(bool(yourAge))
print(float(yourAge))
print(chr(yourAge))
”’ You can change the type of variable using the functions above. A bool (Boolean) is a value that is either True or False. A float is a value with a decimal. A chr (character) will turn a number into the character code for 35 in this example. That character is the double quote “. The full output for these 3 functions would be
True
34.0
“”’

The client wants a more descriptive response on how their ages relate. This is super easy to fix. So, You heard you can store all of the customer data in just one variable. That means you could keep the name, age and whatever else the client needs in one place. You think this might be useful so you try out tuples at the same time:

print(“Hi”)
name = input(“What is your name: “)
print(“Hi”, name)
age = input(“How old are you: “)
yourAge = int(age)

if yourAge == 35:
print(“Your the same as me\n”)
elif yourAge > 35:
print(“Your older than me\n”)
else: print(“Your younger than me\n”)
”’Here I introduce the term elif. It’s used when you need to check for more than just one condition. It is short for else if.”’

tupleTest = (name, yourAge)
”’ I’m assigning name and age to a tuple. A tuple can hold integers, strings, etc. all in the same file.”’

print(tupleTest)
# If you executed this you’d see (‘Derek’, 34)

for i in tupleTest:
print(i)
”’ A for statement is used to perform an action, as long as a condition is met. The condition here is to print out the contents of the tuple, until their are none left. The variable i temporarily holds the value of the tuple. ”’

print(tupleTest[0])
”’ The variables are stored in the tuple in an ordered list that begins with the key value 0. This code will print out the value of the first variable saved in the tuple. In this case, the name entered.”’

print(type(tupleTest))
”’ This code will print out , which proves that it really is a tuple”’

The customer says they need more information off of their customers. They like tuples, but need to be able to add new customer information to the list. Tuples can’t do this because they are immutable. (See Above) He asks if their are immutable (Editable) tuples. Yes, but they are called lists. Here is the code:

print(“Hi”)
name = input(“What is your name: “)
print(“Hi”, name)
age = input(“How old are you: “)
yourAge = int(age)
state = input(“What state do you live in:”)
country = input(“What country do you live in:”)
# Getting the state and country now

if yourAge == 35:
ageCompare = “Same as me”
elif yourAge > 35:
ageCompare = “Older than me”
else: ageCompare = “Younger than me”

visitorInfo = [name, yourAge, state]
”’ Adding the name, age and state to a List variable. Very similar to a tuple, but it’s mutable. Also values are surrounded by ( ), instead of brackets [ ].”’

print(visitorInfo)
# Outputs [‘Derek’, 34, ‘pa’] to the screen

visitorInfo.append(country)
visitorInfo.append(ageCompare)
”’ The function append is used to add additional values to the List named visitorInfo”’

print(visitorInfo)
”’ The new output [‘Derek’, 34, ‘pa’, ‘us’, ‘Younger than me’] We where able to easily add new values ”’

visitorInfo.remove(visitorInfo[4])
”’ The customer decided to not save the value of the variable named ageCompare. So I just removed it from the List with the remove function. Remember a ZERO is the first item in the list. ”’

print(visitorInfo)
”’ The output from this line is [‘Derek’, 34, ‘pa’, ‘us’] ”’

After your done with this problem, you start to wonder if a Dictionary variable would have been better than a list? A Dictionary, while immutable, allows you to store data in key value pairs.

This just means, you could have the word Name associated with each customers name. The same would be true for all of the other variables as well. That sounds much better than having a single number as a key like Lists and Tuples. You decide to try out Dictionary’s.

print(“Hi”)
name = input(“What is your name: “)
print(“Hi”, name)
age = input(“How old are you: “)
yourAge = int(age)
state = input(“What state do you live in:”)
country = input(“What country do you live in:”)
if yourAge == 35:
ageCompare = “Same as me”
elif yourAge > 35:
ageCompare = “Older than me”
else: ageCompare = “Younger than me”

visitorInfo = ({“Name”:name, “Age”:yourAge, “State”:state})
”’ You create a Dictionary by inclosing everything between ({ }). Then you provide the key you wish to use in quotes and the value to store in it after a colon : ”’

print(visitorInfo)
”’ This is the output {‘Age’: 32, ‘Name’: ‘Derek’, ‘State’: ‘pa’} ”’

print(visitorInfo.get(“Name”))
”’ You can retrieve the value, by using a key. Here is that output Derek ”’

print(visitorInfo.items())
”’ The items function will print out all of the information stored in the Dictionary. Here it is dict_items([(‘Age’, 32), (‘Name’, ‘Derek’), (‘State’, ‘pa’)]) ”’

print(visitorInfo.values())
”’ The values function, just prints the values stored dict_values([32, ‘Derek’, ‘pa’]) ”’
visitorInfo.pop(“State”)
”’ You can delete items in the Dictionary with the pop function, but there is no append function like their is for lists ”’

print(visitorInfo.items())
”’ Here is proof that the variable state is gone dict_items([(‘Age’, 32), (‘Name’, ‘Derek’)]) ”’

I hope these code samples help you better understand Python? One other question that came up in emails was how to create large strings and disregard the new lines that are inserted automatically.

Here is an example. If I have this giant multi-line string variable.

badVariables = “””and, continue, except, global, lambda, pass, while,
as, def, False, if, None, raise, with, assert, del, finally, import,
nonlocal, return, yield, break, elif, for, in, not, True, class, else,
from, is, or, try”””

And I print it out with print(badVariables), I receive the following output:

and, continue, except, global, lambda, pass, while,
as, def, False, if, None, raise, with, assert, del, finally, import,
nonlocal, return, yield, break, elif, for, in, not, True, class, else,
from, is, or, try

The reason why, is because Python is automatically entering newline characters into the string. To remove them, just save the string with backslashes between the lines. For example:

badVariables = “””and, continue, except, global, lambda, pass, while, \
as, def, False, if, None, raise, with, assert, del, finally, import, \
nonlocal, return, yield, break, elif, for, in, not, True, class, else, \
from, is, or, try”””

That’s All Folks

If you have any questions, leave them in the comment section below.

Till Next Time

Think Tank

2 Responses to “Python How To : Examples”

  1. Sue says:

    I cannot run any of your input function.

    If i use

    >>> name = input(“What is your name: “)

    then it shows

    Traceback (most recent call last):
    File “/Users/suejlee/Desktop/Python/start.py”, line 4, in
    name = input(“What is your name: “)
    File “”, line 1, in
    NameError: name ‘lala’ is not defined

    Any help please?

Leave a Reply

Your email address will not be published.

Google+