Creation and use of dictionaries in Python #22

--Originally published at Learning With Python LWP

Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.

Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Accessing Values in Dictionary:

To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example −

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']

When the above code is executed, it produces the following result −

dict['Name']:  Zara
dict['Age']:  7

If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows −

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

print "dict['Alice']: ", dict['Alice']

When the above code is executed, it produces the following result


Validated user input (ensure correct/expected data entry) #20 #TC1014

--Originally published at Learning With Python LWP

Reading and Writing Files in Python

Overview

When you’re working with Python, you don’t need to import a library in order to read and write files. It’s handled natively in the language, albeit in a unique manner.

The first thing you’ll need to do is use Python’s built-in open function to get a file object.

The open function opens a file. It’s simple.

When you use the open function, it returns something called a file object. File objects contain methods and attributes that can be used to collect information about the file you opened. They can also be used to manipulate said file.

For example, the mode attribute of a file object tells you which mode a file was opened in. And the name attribute tells you the name of the file that the file object has opened.

You must understand that a file and file object are two wholly separate – yet related – things.


Creation and use of ranges in Python

--Originally published at Learning With Python LWP

What is Python’s range() Function?

As an experienced Python developer, or even a beginner, you’ve likely heard of the Python range() function. But what does it do? In a nutshell, it generates a list of numbers, which is generally used to iterate over with for loops. There’s many use cases. Often you will want to use this when you want to perform an action X number of times, where you may or may not care about the index. Other times you may want to iterate over a list (or another iterable object), while being able to have the index available.

The range() function works a little bit differently between Python 2.x and 3.x under the hood, however the concept is the same. We’ll get to that a bit later, however.

Python’s range() Parameters

The range() function has two sets of parameters, as follows:

range(stop)

  • stop: Number of integers (whole numbers) to generate, starting from zero. eg. range(3) == [0, 1, 2].

range([start], stop[, step])

  • start: Starting number of the sequence.
  • stop: Generate numbers up to, but not including this number.
  • step: Difference between each number in the sequence.

Reading and writing of text files

--Originally published at Learning With Python LWP

Reading and Writing Files in Python

Overview

When you’re working with Python, you don’t need to import a library in order to read and write files. It’s handled natively in the language, albeit in a unique manner.

The first thing you’ll need to do is use Python’s built-in open function to get a file object.

The open function opens a file. It’s simple.

When you use the open function, it returns something called a file object. File objects contain methods and attributes that can be used to collect information about the file you opened. They can also be used to manipulate said file.

For example, the mode attribute of a file object tells you which mode a file was opened in. And the name attribute tells you the name of the file that the file object has opened.

You must understand that a file and file object are two wholly separate – yet related – things.

 


Validated user input (ensure correct/expected data entry)

--Originally published at Learning With Python LWP

MOST OF THE TIMES THAT YOU CREATE A PROGRAM YOU EXPECT IT TO INTERACT WITH THE USER, AND BY DOING SO THEY MAY BE DOING THINGS THAT THEY AREN’T SUPPOSED TO, LIKE WRITING WORD WHERE THEY SHOULD WRITE NUMBERS OR USE SPECIAL CHARACTERS IN STRINGS, IN THIS CASES THE COMPUTER WILL DROP AN ERROR AND WILL STOP THE PROGRAM BUT HOW TO PREVENT IT FROM STOPING AND JUST LET THE USER KNOW HE IS DOING SOMETHING WRONG? THAT IS EXACTLY WHAT THIS TOPIC IS ABOUT.

As in many things in programing how you do it depends on the programer and there are plenty of ways to do so, so I will be explaining just the basic concept and to do so I will use an example.

def get_int(prompt):
    try:
        value = int(input(prompt))
    except ValueError:
        print("Sorry, I didn't understand that.")
        return get_int(prompt)

    if value < 0:
        print("Sorry, your response must not be negative.")
        return get_int(prompt)
    else:
        return value

Creation and use of strings #TC1014

--Originally published at Learning With Python LWP

Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. For example −

var1 = 'Hello World!'
var2 = "Python Programming"

Accessing Values in Strings

Python does not support a character type; these are treated as strings of length one, thus also considered a substring.

To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example −

#!/usr/bin/python

var1 = 'Hello World!'
var2 = "Python Programming"

print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]

Creation and use of Lists/Tuples in Python

--Originally published at Learning With Python LWP

Overview of Python Lists and Tuples

Two of the most commonly used built-in data types in Python are the list and the tuple.

Lists and tuples are part of the group of sequence data types—in other words, lists and tuples store one or more objects or values in a specific order. The objects stored in a list or tuple can be of any type, including the nothing type defined by the None keyword.

The big difference between lists and tuples is that lists are mutable, however tuples are immutable. Meaning once tuples are created, objects can’t be added or removed, and the order cannot be changed. However, certain objects in tuples can be changed, as we’ll see later.


When to use what type of repetition in a program #TC1014

--Originally published at Learning With Python LWP

A for loop repeats the execution of a block of statements a fixed number of times. A list of values, or a string, is used to determine the number of times the block of code will be repeated. The block of code is executed once for each item in the list, or each character in the string.

Programmers have a number of jargon words that refer to loops; repetition is also called iteration and the for loop is sometimes called a definite loop because we can work how many repetitions there will be from the program (the while loop, which we will deal with later, is ‘indefinite’, i.e. we don’t know how many times it will iterate until the program is run).

Open the following program loopThroughName.py in IDLE and run it.

# loopThroughName.py
# this program loops through a users first name
# displaying each letter of their name on a separate line
# D.H. January 5th 2005

firstName = raw_input("Please enter your first name: ")
print
print "Each letter of your name follows "
print

for letter in firstName:
     print letter

Use of recursion for repetitive algorithms #TC1014

--Originally published at Learning With Python LWP

Recursion means “defining something in terms of itself” usually at some smaller scale, perhaps multiple times, to achieve your objective. For example, we might say “A human being is someone whose mother is a human being”, or “a directory is a structure that holds files and (smaller) directories”, or “a family tree starts with a couple who have children, each with their own family sub-trees”.

Programming languages generally support recursion, which means that, in order to solve a problem, functions can call themselves to solve smaller subproblems.


Use of loops with “for” #TC1014

--Originally published at Learning With Python LWP

It has the ability to iterate over the items of any sequence, such as a list or a string.

Syntax

for iterating_var in sequence:
   statements(s)

If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted.