Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Problem 1. Tuple Input a) Write a function called input_tuple (in a new file p1.

ID: 3795214 • Letter: P

Question

Problem 1. Tuple Input
a) Write a function called input_tuple (in a new file p1.py) that reads from the terminal a sequence of
objects with types provided by a tuple given as parameter and that returns the sequence of objects read
as a tuple.
The function will iterate through the types tuple and will try to parse the input string based on the types.
The function takes the following parameters:
prompt: a string to be displayed as input prompt
types: a tuple of type objects that must match the types of the data entered by the user and
returned by the function. The only types supported are int, float, str, bool
sep: a string that separates the input objects, with default value “,”.
The function returns one of:
if parsing the data from the user according to the types tuple succeeds, then it returns the tuple
with the converted data to Python objects,
if parsing the data from the user according to the types tuple fails, then it returns the empty
tuple ( ).
Error handling: the function must not raise/throw errors related to parsing or input/read operations.
Use proper error handling with try/except. In case of any error, print an error message to the terminal
and return the empty tuple ().
Here is a successful example on how the function can be used:
student_tup = input_tuple(“Enter first name, last name, age (float), ID (int), fulltime (bool): “,
(str, str, float, int, bool), # this is the tuple with expected types
“,”) # , is the separator character on the input line
The function displays the prompt:
“Enter first name, last name, age (float), ID (int), fulltime (bool): “
The user enters the string: “Spongebob,Squarepants,23.5,1,True”. Then, the tuple returned will be equal
to (“Spongebob”, “Squarepants”, 23.5, 1, True).
Here is an example when parsing based on the types tuple fails:
The function call is the same as above, but the user enters: “Spongebob Squarepants,23.5,1,True”.
Notice that the token count is less than required – a separator is missing. The function returns ().
Another example of failure is if the user types: “Keith,Rupert,Murdoch,20,10010,False”. The function
expects a float for the 3rd object, but gets instead a string that can’t be converted to float. The function
returns (), too.
Function input_tuple should NOT use list comprehensions.
Hint: Python types (like int, str) can be used as constructors to ‘construct’ an object of a corresponding
type from a string. For example, int(“30”) returns object of type int with number 30 inside.
b) Write a function called input_tuple_lc that is identical to input_tuple except that it uses list
comprehension(s).
c) Write a function read_tuple that works similarly to input_tuple, but instead of reading input from the
terminal, it reads text from a file object passed as argument. If this function uses correctly a list
comprehension you get 2 extra points.
The function read_tuple takes the following parameters:
file_obj: an object representing an open text file; e.g. opened with open(“filename”,”r”).
types: a tuple of type objects that must match the types of the data entered by the user and
returned by the function. The only types supported are int, float, str, bool
sep: a string that separates the input objects, with default value “,”.
The function returns one of:
if parsing the data from the user according to the types tuple succeeds, then it returns the tuple
with the converted data
if parsing the data from the user according to the types tuple fails, then it returns the empty
tuple ( ).
Error handling: the function must not raise/throw errors related to parsing or input/read operations.
Use proper error handling with try/except. In case of any error, print an error message to the terminal
and return the empty tuple ().
A usage scenario (omitting error handling for brevity) would be:
f = open(“cars.csv”, “r”)
(make, model, mpg_float, modelYr_int, newcar_bool) = read_tuple(f, (str, str, float, int, bool), “,”)
# use these variables ….
f.close()
This code will work fine if the file cars.csv looks like this:
Lada,Niva,19.5,1987,False
Porsche,911 Turbo S,17.5,1989,False
Function read_tuple() should return in this case the tuple (‘Lada’,’Niva’,19.5,1987,False) for the first
time it’s called.
If the input format does not comply with types argument (str, str, float, int, bool) then the function
should return ().
c) In the main program (p1.py) write code that tests both functions.
Using the testif function from the Unit 2 module for writing your tests gives you 2 extra credit points.
Hints:
• notice that MS Word uses a special type of the double quote “ characters, in case you want to
paste to a Python editor
• you can iterate with a for loop through the types tuple
• if a variable t holds a type object (from iterating through the types tuple, for instance), then you
can convert a string s to an object of type t by calling t(s). If the conversion fails, it will
throw/raise a ValueError.
• bool(x) will succeed in most cases for different types of data. If x==0 or “”, bool(x) will return
False.
• a tuple is immutable, but a list is not. Grow a list first, then convert to a tuple.

Explanation / Answer

Last chapter we introduced Python’s built-in types int, float, and str, and we stumbled upon tuple.

Integers and floats are numeric types, which means they hold numbers. We can use the numeric operators we saw last chapter with them to form numeric expressions. The Python interpreter can then evaluate these expressions to produce numeric values, making Python a very powerful calculator.

Strings, lists, and tuples are all sequence types, so called because they behave like a sequence - an ordered collection of objects.

Squence types are qualitatively different from numeric types because they are compound data types - meaning they are made up of smaller pieces. In the case of strings, they’re made up of smaller strings, each containing one character. There is also the empty string, containing no characters at all.

In the case of lists or tuples, they are made up of elements, which are values of any Python datatype, including other lists and tuples.

Lists are enclosed in square brackets ([ and ]) and tuples in parentheses (( and )).

A list containing no elements is called an empty list, and a tuple with no elements is an empty tuple.

The first example is a list of five integers, and the next is a list of three strings. The third is a tuple containing four integers, followed by a tuple containing four strings. The last is a list containing three tuples, each of which contains a pair of strings.

Depending on what we are doing, we may want to treat a compound data type as a single thing, or we may want to access its parts. This ambiguity is useful.

Note

It is possible to drop the parentheses when specifiying a tuple, and only use a comma seperated list of values:

Also, it is required to include a comma when specifying a tuple with only one element:

Except for the case of the empty tuple, it is really the commas, not the parentheses, that tell Python it is a tuple.

3.2. Working with the parts of a sequence

The sequence types share a common set of operations.

3.2.1. Indexing

The indexing operator ([ ]) selects a single element from a sequence. The expression inside brackets is called the index, and must be an integer value. The index indicates which element to select, hence its name.

The expression fruit[1] selects the character with index 1 from fruit, and creates a new string containing just this one character, which you may be surprised to see is 'a'.

You probably expected to see 'b', but computer scientists typically start counting from zero, not one. Think of the index as the numbers on a ruler measuring how many elements you have moved into the sequence from the beginning. Both rulers and indices start at 0.

3.2.2. Length

Last chapter you saw the len function used to get the number of characters in a string:

With lists and tuples, len returns the number of elements in the sequence:

3.2.3. Accessing elements at the end of a sequence

It is common in computer programming to need to access elements at the end of a sequence. Now that you have seen the len function, you might be tempted to try something like this:

That won’t work. It causes the runtime error IndexError: list index out of range. The reason is that len(seq) returns the number of elements in the list, 16, but there is no element at index position 16 in seq.

Since we started counting at zero, the sixteen indices are numbered 0 to 15. To get the last element, we have to subtract 1 from the length:

This is such a common in pattern that Python provides a short hand notation for it, negative indexing, which counts backward from the end of the sequence.

The expression seq[-1] yields the last element, seq[-2] yields the second to last, and so on.

3.2.4. Traversal and the for loop

A lot of computations involve processing a sequence one element at a time. The most common pattern is to start at the beginning, select each element in turn, do something to it, and continue until the end. This pattern of processing is called a traversal.

Python’s for loop makes traversal easy to express:

Note

We will discuss looping in greater detail in the next chapter. For now just note that the colon (:) at the end of the first line and the indentation on the second line are both required for this statement to be syntactically correct.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote