Python Programming - Chapter 3

60 %
40 %
Information about Python Programming - Chapter 3

Published on April 29, 2008

Author: mariajoslin

Source: slideshare.net

Description

This is the 3rd lecture in a series of lectures for students learning Python programming

Chapter 3 Variables –Names for Values

In most programs, you want to be able to store values for later use and not keep entering them time and time again this is done with variables which is a way for you to tell the computer that every time you mention the name for the value, it will go into memory and retrieve the appropriate value keep in mind that the computer does not really recognize names but rather keep a table of memory addresses and the name given to that address by the programmer (a way to translate a name into its own language) In Python, it is very easy to create variables all you need to do is place the name of the variable on the left side of an equality statement and from that point on (unless the value is altered later), that value will be associated with the name

In most programs, you want to be able to store values for later use and not keep entering them time and time again

this is done with variables which is a way for you to tell the computer that every time you mention the name for the value, it will go into memory and retrieve the appropriate value

keep in mind that the computer does not really recognize names but rather keep a table of memory addresses and the name given to that address by the programmer (a way to translate a name into its own language)

In Python, it is very easy to create variables

all you need to do is place the name of the variable on the left side of an equality statement and from that point on (unless the value is altered later), that value will be associated with the name

Try this: >>> first_string = "This is a string" >>> second_string = "This is another string" >>> first_number = 4 >>> second_number = 5 >>> print "The first variables are %s, %s, %d, %d" % (first_string, second_string, first_number, second_number) Note: the variable name is all one word and is on the left side of the equals sign it is VERY important to give your variable a name which explains what value it will contain (see above) Variables can contain values that are apt to change and that is the true meaning of the word “variable”

Try this:

>>> first_string = "This is a string"

>>> second_string = "This is another string"

>>> first_number = 4

>>> second_number = 5

>>> print "The first variables are %s, %s, %d, %d" % (first_string, second_string, first_number, second_number)

Note: the variable name is all one word and is on the left side of the equals sign

it is VERY important to give your variable a name which explains what value it will contain (see above)

Variables can contain values that are apt to change and that is the true meaning of the word “variable”

Try this: >>> proverb = "A penny saved" >>> proverb = proverb + " is a penny earned" >>> print proverb >>> pennies_saved = 0 >>> pennies_saved = pennies_saved + 1 >>> pennies_saved Notice that a) the variable is always on the left side of the equals, and b) the variable may be on both sides of the equals if a value is being added to whatever is currently in the variable In order to make variable names self-explanatory, you can put two or more words together by separating them with underscores or sometimes by capitalizing the first letter of the second word and so forth

Try this:

>>> proverb = "A penny saved"

>>> proverb = proverb + " is a penny earned"

>>> print proverb

>>> pennies_saved = 0

>>> pennies_saved = pennies_saved + 1

>>> pennies_saved

Notice that a) the variable is always on the left side of the equals, and b) the variable may be on both sides of the equals if a value is being added to whatever is currently in the variable

In order to make variable names self-explanatory, you can put two or more words together by separating them with underscores or sometimes by capitalizing the first letter of the second word and so forth

There are some words that are “reserved” in certain programming languages (and Python is not an exception) these words carry special meaning and may not be used for regular variable names without damaging effects In Python, the following words are reserved: and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if import, in, is, lambda, not, or, pass, print, raise, return, try, while, yield The only other restriction for variable names is that they not begin with numbers or most non-alphabetic characters, with the exception of the underscore character Besides strings and numeric data types, Python has other built-in types such as tuples, lists and dictionaries

There are some words that are “reserved” in certain programming languages (and Python is not an exception)

these words carry special meaning and may not be used for regular variable names without damaging effects

In Python, the following words are reserved:

and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if import, in, is, lambda, not, or, pass, print, raise, return, try, while, yield

The only other restriction for variable names is that they not begin with numbers or most non-alphabetic characters, with the exception of the underscore character

Besides strings and numeric data types, Python has other built-in types such as tuples, lists and dictionaries

Tuples, list , and dictionaries allow you to group more than one item of data together under a single name, making it easier to store large amounts of data The computer knows which data type you will be using by the way you create the variable tuples place all its data inside a pair of “( )” lists place all its data inside a pair of “[ ]” dictionaries must be declared first as an empty dictionary with a pair of “{ }” and only then can you start placing data into the dictionary All these data types act slightly differently and you must decide which one you will be needing for your program

Tuples, list , and dictionaries allow you to group more than one item of data together under a single name, making it easier to store large amounts of data

The computer knows which data type you will be using by the way you create the variable

tuples place all its data inside a pair of “( )”

lists place all its data inside a pair of “[ ]”

dictionaries must be declared first as an empty dictionary with a pair of “{ }” and only then can you start placing data into the dictionary

All these data types act slightly differently and you must decide which one you will be needing for your program

Tuples are used when you want to assign values to match more than one format specifier in a string they contain references to data such as strings and numbers Try this: >>> filler = ("string", "filled", "by a", "tuple") >>> print "A %s %s %s %s" % filler You can also access a single value inside of a tuple by placing square brackets after the name of the tuple Be careful! Python, like most other languages, starts counting at zero and will always be one off of what you would normally think about the location of the element

Tuples are used when you want to assign values to match more than one format specifier in a string

they contain references to data such as strings and numbers

Try this:

>>> filler = ("string", "filled", "by a", "tuple")

>>> print "A %s %s %s %s" % filler

You can also access a single value inside of a tuple by placing square brackets after the name of the tuple

Be careful! Python, like most other languages, starts counting at zero and will always be one off of what you would normally think about the location of the element

If you’re not too sure how many elements a tuple has, you can always use the function “ len ” to tell you how many items there are for example: >>> len(filler) will return the value “4”, but the indeces into the elements of filler will range from 0 to 3 Be aware that elements of a tuple can be another tuple and that makes it multidimensional in order to access an element of a tuple which is in itself another tuple , you need to add another pair of square brackets

If you’re not too sure how many elements a tuple has, you can always use the function “ len ” to tell you how many items there are

for example: >>> len(filler)

will return the value “4”, but the indeces into the elements of filler will range from 0 to 3

Be aware that elements of a tuple can be another tuple and that makes it multidimensional

in order to access an element of a tuple which is in itself another tuple , you need to add another pair of square brackets

Try this: >>> a = ("first", "second", "third") >>> b = (a, "b's second element") >>> print "%s" % b[1] >>> print "%s" % b[0][0] >>> print "%s" % b[0][1] >>> print "%s" % b[0][2] Although there isn’t a limit on the number of dimensions a tuple can have, after a while the number of dimensions will confuse the programmer so no more than three dimensions are recommended The only oddity with tuples is that if there is only one element in a tuple , it needs to be followed with a “,” before closing the parentheses

Try this:

>>> a = ("first", "second", "third")

>>> b = (a, "b's second element")

>>> print "%s" % b[1]

>>> print "%s" % b[0][0]

>>> print "%s" % b[0][1]

>>> print "%s" % b[0][2]

Although there isn’t a limit on the number of dimensions a tuple can have, after a while the number of dimensions will confuse the programmer so no more than three dimensions are recommended

The only oddity with tuples is that if there is only one element in a tuple , it needs to be followed with a “,” before closing the parentheses

The biggest draw back to a tuple is that once it is created, it cannot be changed this is called “immutability” and this is true for strings and most other languages have this same drawback Lists , on the other hand, are changeable sequences of data Lists contain its elements in a pair of square brackets and its elements are accessed the same way as with tuples

The biggest draw back to a tuple is that once it is created, it cannot be changed

this is called “immutability” and this is true for strings and most other languages have this same drawback

Lists , on the other hand, are changeable sequences of data

Lists contain its elements in a pair of square brackets and its elements are accessed the same way as with tuples

Try this: >>> count = 0 >>> breakfast = ["coffee", "tea", "toast", "egg"] >>> print "Today's breakfast is %s" % breakfast[count] >>> count = 1 >>> print "Today's breakfast is %s" % breakfast[count] >>> print "Today's breakfast is %s" % breakfast[count] >>> count = 2 >>> print "Today's breakfast is %s" % breakfast[count] >>> count = 3 >>> print "Today's breakfast is %s" % breakfast[count] Remember that the contents of a list can be changed at any time and have no restrictions on them

Try this:

>>> count = 0

>>> breakfast = ["coffee", "tea", "toast", "egg"]

>>> print "Today's breakfast is %s" % breakfast[count]

>>> count = 1

>>> print "Today's breakfast is %s" % breakfast[count]

>>> print "Today's breakfast is %s" % breakfast[count]

>>> count = 2

>>> print "Today's breakfast is %s" % breakfast[count]

>>> count = 3

>>> print "Today's breakfast is %s" % breakfast[count]

Remember that the contents of a list can be changed at any time and have no restrictions on them

You can not only change the values that are stored in the list , but you can add information to the end of the list the “ append” method allows you to add one item to the end of a list for example: breakfast.append(“waffle”) the “extend” method allows you to add more than item, or items in a tuple to the end of a list for example: breakfast.extend([“juice”, “oatmeal”]) The length of a list can also be accessed through the “len” function, the same ways as with a tuple

You can not only change the values that are stored in the list , but you can add information to the end of the list

the “ append” method allows you to add one item to the end of a list

for example: breakfast.append(“waffle”)

the “extend” method allows you to add more than item, or items in a tuple to the end of a list

for example: breakfast.extend([“juice”, “oatmeal”])

The length of a list can also be accessed through the “len” function, the same ways as with a tuple

Dictionaries are different from tuples and lists mainly because they are accessed with names as opposed to numeric indeces In addition, dictionaries need to be declared before you start to add information in them and this is done with an empty pair of curly brackets Individual items of a dictionary are added one at a time by placing the string index in a pair of square brackets and then the value associated with that index on the right side of an equals sign This is perhaps the biggest drawback to using a dictionary – the creation of a dictionary is a two-step process

Dictionaries are different from tuples and lists mainly because they are accessed with names as opposed to numeric indeces

In addition, dictionaries need to be declared before you start to add information in them and this is done with an empty pair of curly brackets

Individual items of a dictionary are added one at a time by placing the string index in a pair of square brackets and then the value associated with that index on the right side of an equals sign

This is perhaps the biggest drawback to using a dictionary – the creation of a dictionary is a two-step process

Try this: >>> menus_special = {} >>> menus_special["breakfast"] = "canadian ham" >>> menus_special["lunch"] = "tuna surprise" >>> menus_special["dinner"] = "Cheeseburger deluxe“ The name given to the indeces of a dictionary are called “keys” and the data are called “values” You can see what information is stored in a dictionary by placing it on a line by itself in the shell and it will display the key followed by a colon and the associated value for every item Try this: >>> menus_special {'lunch': 'tuna surprise', 'breakfast': 'canadian ham', 'dinner': 'Cheeseburger deluxe'}

Try this:

>>> menus_special = {}

>>> menus_special["breakfast"] = "canadian ham"

>>> menus_special["lunch"] = "tuna surprise"

>>> menus_special["dinner"] = "Cheeseburger deluxe“

The name given to the indeces of a dictionary are called “keys” and the data are called “values”

You can see what information is stored in a dictionary by placing it on a line by itself in the shell and it will display the key followed by a colon and the associated value for every item

Try this:

>>> menus_special

{'lunch': 'tuna surprise', 'breakfast': 'canadian ham', 'dinner': 'Cheeseburger deluxe'}

The other difference with dictionaries is that you can access the individual elements by placing a string (instead of a number) inside the square brackets Try this: >>> print "%s" % menus_special["breakfast"] >>> print "%s" % menus_special["lunch"] >>> print "%s" % menus_special["dinner"] If you want to know all the keys for your dictionary or all the values stored in the dictionary, you can used the built-in function keys() and values() for example: menus_special.keys() -or- menus_special.values() The return values can be stored into a list for use later on

The other difference with dictionaries is that you can access the individual elements by placing a string (instead of a number) inside the square brackets

Try this:

>>> print "%s" % menus_special["breakfast"]

>>> print "%s" % menus_special["lunch"]

>>> print "%s" % menus_special["dinner"]

If you want to know all the keys for your dictionary or all the values stored in the dictionary, you can used the built-in function keys() and values()

for example: menus_special.keys() -or- menus_special.values()

The return values can be stored into a list for use later on

Another feature of a dictionary is that you can find out whether you’ve already used a key this is done with the has_key() function which will return a True or False value Try this: >>> menus_special.has_key("junk") >>> menus_special.has_key("breakfast") >>> menus_special.has_key("canadian ham") True and False are built-in values which really represent 1 and 0, but is more intuitive to a programmer Strings are interesting in that they can be treated as list of individual characters, but please remember that they are immutable

Another feature of a dictionary is that you can find out whether you’ve already used a key

this is done with the has_key() function which will return a True or False value

Try this:

>>> menus_special.has_key("junk")

>>> menus_special.has_key("breakfast")

>>> menus_special.has_key("canadian ham")

True and False are built-in values which really represent 1 and 0, but is more intuitive to a programmer

Strings are interesting in that they can be treated as list of individual characters, but please remember that they are immutable

Certain elements of a string can be removed and this is a technique called “slicing” these new slices are actually brand new strings that are being created, regardless of their new length Additional Features of Python Another special built-in value, besides True and False , is None this is used with functions that have nothing to return to the calling program Python allows you to access elements of a tuple , list or string from the end by placing a negative value in the square brackets for example: [-1] will access the last elements, [-2] will access the next-to-last element, etc.

Certain elements of a string can be removed and this is a technique called “slicing”

these new slices are actually brand new strings that are being created, regardless of their new length

Additional Features of Python

Another special built-in value, besides True and False , is None

this is used with functions that have nothing to return to the calling program

Python allows you to access elements of a tuple , list or string from the end by placing a negative value in the square brackets

for example: [-1] will access the last elements, [-2] will access the next-to-last element, etc.

Another feature to remember is that whenever a slice is created from a list or a tuple , the result is another list or tuple , depending on what you sliced from Try this: >>> slice_this_tuple = ("The", "next", "time", "we", "meet", "drinks", "are", "on", "me") >>> sliced_tuple = slice_this_tuple[5:9] >>> sliced_tuple >>> slice_this_list = ["The", "next", "time", "we", "meet", "drinks", "are", "on", "me"] >>> sliced_list = slice_this_list[5:9] >>> sliced_list >>> slice_this_string = "The next time we meet, drinks are on me" >>> sliced_string = slice_this_string[5:9] >>> sliced_string

Another feature to remember is that whenever a slice is created from a list or a tuple , the result is another list or tuple , depending on what you sliced from

Try this:

>>> slice_this_tuple = ("The", "next", "time", "we", "meet", "drinks", "are", "on", "me")

>>> sliced_tuple = slice_this_tuple[5:9]

>>> sliced_tuple

>>> slice_this_list = ["The", "next", "time", "we", "meet", "drinks", "are", "on", "me"]

>>> sliced_list = slice_this_list[5:9]

>>> sliced_list

>>> slice_this_string = "The next time we meet, drinks are on me"

>>> sliced_string = slice_this_string[5:9]

>>> sliced_string

Keep in mind that if you use a colon to specify which elements to slice from, a new sequence of that same type is created and contains just those elements Another way to expand lists is by appending sequences, but be aware that a single elements of the list will now be a sequence by itself, thereby making it multidimensional Lists can also have values deleted from them by using the “pop” function and you can even specify which element you want removed by placing it in the parentheses

Keep in mind that if you use a colon to specify which elements to slice from, a new sequence of that same type is created and contains just those elements

Another way to expand lists is by appending sequences, but be aware that a single elements of the list will now be a sequence by itself, thereby making it multidimensional

Lists can also have values deleted from them by using the “pop” function and you can even specify which element you want removed by placing it in the parentheses

Try this: >>> todays_temperatures = [23, 32, 33, 31] >>> todays_temperatures.append(29) >>> todays_temperatures >>> morning = todays_temperatures.pop(0) >>> print "This mornings temperature was %.02f" % morning >>> late_morning = todays_temperatures.pop(0) >>> print "Todays late morning temperature was %.02f" % late_morning >>> noon = todays_temperatures.pop(0) >>> print "Todays noon temperature was %.02f" % noon >>> todays_temperatures Note: you can “pop” an element from a list and never use it (it will be automatically discarded from memory

Try this:

>>> todays_temperatures = [23, 32, 33, 31]

>>> todays_temperatures.append(29)

>>> todays_temperatures

>>> morning = todays_temperatures.pop(0)

>>> print "This mornings temperature was %.02f" % morning

>>> late_morning = todays_temperatures.pop(0)

>>> print "Todays late morning temperature was %.02f" % late_morning

>>> noon = todays_temperatures.pop(0)

>>> print "Todays noon temperature was %.02f" % noon

>>> todays_temperatures

Note: you can “pop” an element from a list and never use it (it will be automatically discarded from memory

Exercises Create a list called dairy_section with four elements from the dairy section of a supermarket. Print a string with the first and last elements of the dairy_section list. Create a tuple called milk-expiration with three elements: the month, day and year of the expiration date on the nearest carton of milk

Create a list called dairy_section with four elements from the dairy section of a supermarket.

Print a string with the first and last elements of the dairy_section list.

Create a tuple called milk-expiration with three elements: the month, day and year of the expiration date on the nearest carton of milk

Print the values in the milk_expiration tuple in a string that reads “This milk will expire on 12/10/2005”. Create an empty dictionary called milk_carton. Add the following key/value pairs. You can make up the values or use a real milk carton: expiration_date : set it to the milk_expiration tuple fl_oz : set it to the size of the milk carton on which you are basing this cost : set this to the cost of a carton of milk brand_name : set this to the brand name of milk you drink

Print the values in the milk_expiration tuple in a string that reads “This milk will expire on 12/10/2005”.

Create an empty dictionary called milk_carton. Add the following key/value pairs. You can make up the values or use a real milk carton:

expiration_date : set it to the milk_expiration tuple

fl_oz : set it to the size of the milk carton on which you are basing this

cost : set this to the cost of a carton of milk

brand_name : set this to the brand name of milk you drink

Print out the values of all of the elements of the milk_carton using the values in the dictionary , and not, for instance, using the data in the milk_expiration tuple Show how to calculate the cost of six cartons of milk based on the cost of milk_carton. Create a list called cheeses. List all of the cheeses you can think of. Append this list to the dairy_section list, and look at the contents of dairy_section. Then remove the list of cheeses from the array.

Print out the values of all of the elements of the milk_carton using the values in the dictionary , and not, for instance, using the data in the milk_expiration tuple

Show how to calculate the cost of six cartons of milk based on the cost of milk_carton.

Create a list called cheeses. List all of the cheeses you can think of. Append this list to the dairy_section list, and look at the contents of dairy_section. Then remove the list of cheeses from the array.

How do you count the number of cheeses in the cheese list? Print out the first five letters of the name of your first cheese.

How do you count the number of cheeses in the cheese list?

Print out the first five letters of the name of your first cheese.

Add a comment

Related presentations

Related pages

Search › python programming chapter 3 | Quizlet

Search results for: python programming chapter 3. 500 Study Sets 500 Sets 500 Classes 500 Users; Advertisement
Read more

Welcome to Python.org

The official home of the Python Programming Language
Read more

Python Programming Chapter 3 Text Version

CC0002N Python Programming. Chapter 3 Using numbers. In Chapter 2, we looked at programs that input two types of data. Programs with numeric input made ...
Read more

Python Programming - John Zelle: Chapter 3 ex. 13 - 3six3

Python Programming - John Zelle / Chapter 3 Exercise 13 ... Run = This program adds series of numbers entered by the user How many numbers do you want to ...
Read more

Search › programming chapter 3 python | Quizlet

If you're having trouble, want to report a bug, provide a suggestion, or just want to say hello — please fill out the form below.
Read more

Python Programming - John Zelle: Chapter 3 ex. 14 - 3six3

Python Programming - John Zelle / Chapter 3 Exercise 14
Read more

Programming in Python 3 (Second Edition) - Qtrac

Programming in Python 3 book, Compare PDFs, DiffPDF, diffpdfc, Python. ... Functional-Style Programming; Chapter 9. Debugging, Testing, and Profiling;
Read more

Python by Kids Chapter 3 - YouTube

Python by Kids Chapter 3 Prismatic Pythons. Subscribe Subscribed Unsubscribe 9 9. ... Python 3 Programming for Morons 1 of 7 - Duration: 5:34.
Read more

Overview — Python 3.5.2 documentation

Python 3.5.2 documentation. Welcome! This is the documentation for Python 3.5.2, last updated Aug 29, 2016. Parts of the documentation:
Read more