Session 3 - Part 1 Flashcards

1
Q

```

~~~

How can you convert a string to uppercase in Python?

A

You can utilize the upper() method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How can you convert a given string to lowercase in Python?

A

You can utilize the lower() method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How can you convert a given string to title case in Python?

A

You can utilize the title() method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How can you remove leading and trailing whitespace characters from a string in Python?

A

You can achieve this by using the strip() method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the output of this code?

my_string = ‘ the cat Sat on The Mat. ‘

print(my_string.upper())

A

(spaces before) THE CAT SAT ON THE MAT.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the output of this code?

my_string = ‘ the cat Sat on The Mat. ‘

print(my_string.lower())

A

(spaces before) the cat sat on the mat.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the output of this code?

my_string = ‘ the cat Sat on The Mat. ‘

print(my_string.title())

A

(spaces before) The Cat Sat On The Mat

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the output of this code?

my_string = ‘ the cat Sat on The Mat. ‘

print(my_string.strip())

A

the cat Sat on The Mat.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the output of this code?

my_string = ‘ the cat Sat on The Mat. ‘

print(my_string.strip().lower())

A

the cat sat on the mat.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Explain the following Python code:

my_string = ‘ the cat Sat on The Mat. ‘

print(my_string.upper()) - (3)

A

This code defines a string variable my_string containing the text “the cat Sat on The Mat.” with leading and trailing whitespace characters.

The upper() string method is then applied to my_string, converting all characters in the string to uppercase.

Finally, the result, which is the string in uppercase, is printed to the output console.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Explain the following Python code - (2)

my_string = ‘ the cat Sat on The Mat. ‘

print(my_string.title())

A

This code takes the string stored in the variable my_string and prints it out in title case.

In title case, the first character of each word is capitalized, and the rest of the characters are in lowercase.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Explain the following Python code - (2)

my_string = ‘ the cat Sat on The Mat. ‘

print(my_string.strip())

A

This code removes leading and trailing whitespace characters (such as spaces, tabs, and newline characters) from the string stored in the variable my_string.

The strip() method is used to perform this operation, and the resulting string with whitespace removed is printed to the console.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

You can combine these string methods (upper, lower, title, strip) like this:

A

my_string.strip().lower()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Explain the following Python code and how it combines string methods - (4)

my_string = ‘ the cat Sat on The Mat. ‘

print(my_string.strip().lower())

A

This code demonstrates the combination of string methods in Python.

First, the strip() method is applied to my_string to remove leading and trailing whitespace characters.

Then, the lower() method is applied to the resulting string, converting all characters to lowercase.

The combined effect of these methods is that the string is stripped of whitespace and converted to lowercase before being printed to the console.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Explain the meaning of the following string assignment (i.e., (i.e., “string assignment” refers to the process of assigning a string value to a variable) - (3)

my_string=”\n hello world \t”

A

In the given string assignment, my_string, the escape sequences \n and \t are used.

\n represents a newline character, causing the text “hello world” to start on a new line.

\t represents a tab character, adding tab spaces (equivalent to multiple spaces) before the text “hello world”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Exercise
Change the following code so that it prints the string ‘All In Title Case’ and without the leading and trailing spaces.

Bonus points. Use an f-string to center the modified string in some asterisks like this ** Hello World! **

Code:

my_string=”\n hello world \t”
print(my_string)

A

my_string=”\n hello world \t”
print(f”{my_string.title().strip()}”)

Output:
* Hello World*

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What are string member functions in Python - (3)

A

String member functions” refer to methods that are specific to strings and are accessed using dot notation.

These methods include functions to change the case of strings (e.g., lower(), upper(), title(), strip(), join strings (join()), split strings (split()), and others.

They are essential for string manipulation tasks in Python

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Describe the importance of string member functions in Python - (2)

A

String member functions are essential for cleaning up and altering the case of strings.

This is not only useful for printing and other output purposes but also in cases where we need to compare strings ‘case-insensitively’ (in other words without caring whether something is upper- or lower-case).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Let’s imagine we have a password system for school district

Each time someone wants to get in they have to type the password (‘pencil’). But, to make things easier, we don’t want it to fail if they have the CAPS LOCK key on, or if they are German And Need To Capitalize Lots Of Words. Or if they have accidentally added a space or tab at the start of the string (YNiC screensaver unlock box - I’m looking at you!).

How might we do this? - Two ways - (2)

A

Using if statements

Turning any user input to lower case and check against ‘pencil’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Let’s imagine we have a password system for school district

Each time someone wants to get in they have to type the password (‘pencil’). But, to make things easier, we don’t want it to fail if they have the CAPS LOCK key on, or if they are German And Need To Capitalize Lots Of Words. Or if they have accidentally added a space or tab at the start of the string (YNiC screensaver unlock box - I’m looking at you!).

First way if statements:

A

if (inputWord==’pencil’) or (inputWord==’PENCIL’) or (inputWord==’Pencil’) or (inputWord=…..

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Why might using a series of if statements to check for variations in capitalization or leading whitespace be considered clunky? - (2)

e.g.,

if (inputWord==’pencil’) or (inputWord==’PENCIL’) or (inputWord==’Pencil’) or (inputWord=…..

A

Using a series of if statements to check for variations in capitalization or leading whitespace can be considered clunky because it requires writing repetitive code and becomes cumbersome to maintain, especially if the password changes.

Also you may not think of all the variations people can type pencil

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Let’s imagine we have a password system for school district

Each time someone wants to get in they have to type the password (‘pencil’). But, to make things easier, we don’t want it to fail if they have the CAPS LOCK key on, or if they are German And Need To Capitalize Lots Of Words. Or if they have accidentally added a space or tab at the start of the string (YNiC screensaver unlock box - I’m looking at you!).

Second way -Turning any user input to lower case and check against ‘pencil’ - produce this code - target string is ‘pencil’

A

target_string = ‘pencil’

user_input = input(‘Login with user password: ‘)

user_input = user_input.lower()

if user_input == target_string:
print(“Welcome to the Seattle Public School District DATANET”)
else:
print(“Password denied”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is the following outputs given these inputs? - (5)

code:

target_string = ‘pencil’

user_input = input(‘Login with user password: ‘)

user_input = user_input.lower() # We could also ‘strip’ it to remove whitespace

if user_input == target_string:
print(“Welcome to the Seattle Public School District DATANET”)
else:
print(“Password denied”)

	inputs:
	pencil
	PENCIL
	PeNCIL
	pen
A

Login with user password: pencil Welcome to the Seattle Public School District DATANET

Login with user password: Pencil Welcome to the Seattle Public School District DATANET

Login with user password: pencil Welcome to the Seattle Public School District DATANET

Login with user password: PeNCIL Welcome to the Seattle Public School District DATANET

Login with user password: pen Password denied

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is the advantage of converting the input to lowercase before comparing it to the password?

e.g.,

target_string = ‘pencil’

user_input = input(‘Login with user password: ‘)

user_input = user_input.lower()

A

Converting the input to lowercase before comparison ensures case insensitivity, simplifying code and making it more robust by ignoring variations in capitalization or leading whitespace.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Explain the following Python code - (6)

target_string = ‘pencil’

user_input = input(‘Login with user password: ‘)

user_input = user_input.lower()

if user_input == target_string:
print(“Welcome to the Seattle Public School District DATANET”)
else:
print(“Password denied”)

A

This code prompts the user to enter a password and compares it with a target password stored in lower case.

Firstly, the target password ‘pencil’ is stored as all lower-case characters in variable ‘target_string’

Then, the user is prompted to input their password.

The user_input.lower() function converts the user’s input to lower case, ensuring that the comparison is not case-sensitive.

If the user’s input matches the target password, ‘Welcome to the Seattle Public School District DATANET’ is printed; otherwise, ‘Password denied’ is printed.

This approach ensures that the password comparison ignores variations in capitalization and provides a robust password validation mechanism.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is the output of this code?

target_string = ‘pencil’

user_input input(‘Login with user password’

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

might you use a while loop to keep going until someone gets the password right? BONUS POINTS: Why might this be a bad idea?

A

We will just keep trying lots of passwords

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Quick Exercise
Modify the code from the example above so that it does the comparison in upper case.

target_string = ‘pencil’

user_input = input(‘Login with user password: ‘)

user_input = user_input.lower() # We could also ‘strip’ it to remove whitespace

if user_input == target_string:
print(“Welcome to the Seattle Public School District DATANET”)
else:
print(“Password denied”)

A

tgt_string = ‘PENCIL’

user_input = input(‘Enter a string: ‘)

user_input = user_input.upper()

if user_input == tgt_string:
print(“Welcome to the Seattle Public School District DATANET”)
else:
print(“Password denied”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Explain the functionality of the split string member function .spilt() in Python.

A

The split string member function is designed to take a string and split it into a list of strings

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What is the default behaviour of .spilt() string member function?

A

By default, it splits the string on any whitespace characters (such as spaces, tabs, or newlines/carriage-return characters),

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Explain the functionality of the provided Python code - (10)

dat = ‘The cat sat on the mat’

res = dat.split()

print(type(res))

print(res)

print(len(res))

A

The provided code utilizes the split() method to split the string “The cat sat on the mat” into individual words.

It initializes a string variable dat with the value ‘The cat sat on the mat’.

The split() method is applied to dat, splitting the string into individual words based on whitespace characters.

The resulting list is stored in the variable res.

It prints the type of res (which confirms it’s a list), the contents of res (the individual words), and the length of res (the number of words in the original string).

Output:

<class ‘list’>
[‘The’, ‘cat’, ‘sat’, ‘on’, ‘the’, ‘mat’]
6

You can see that it takes the string “The cat sat on the mat” and breaks it apart into 6 strings - one for each part of the string between each space character.

The length of the resulting list is 6, corresponding to the number of words in the original string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Explain how to change the character on which the split method splits a string in Python,

A

To change the character on which the split method splits a string, you can pass a desired ‘separator’ character as an argument to the method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Example of change the character on which spilt spilts the string by passing our desired ‘seprator; character as an arguement - (2)

if we have a string which is separated by commas:

dat = ‘Person,Condition,RT’
res = dat.split(‘,’)
print(res)

Explain:

A

In this example, the string dat is split into individual parts at each comma character, and the resulting list is printed:

Output:
[‘Person’, ‘Condition’, ‘RT’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

Why is this formulation particularly useful e.g., spilting string based on comma character ‘,’:

dat = ‘Person,Condition,RT’

res = dat.split(‘,’)

print(res)

A

This formulation is particularly useful because a common way to store data in scientific studies is as a Comma-Separated Values file (often known as a CSV file).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

Modify this code below to spilt on a different character like ‘o’:

dat = ‘Person,Condition,RT’

res = dat.split(‘,’)

print(res)

A

dat = ‘Person,Condition,RT’

res = dat.split(‘o’)

print(res)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What is output of this code:
dat = ‘Person,Condition,RT’

res = dat.split(‘o’)

print(res)

A

[‘Pers’, ‘n,C’, ‘nditi’, ‘n,RT’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Explain this code - (5)

dat = ‘Person,Condition,RT’

res = dat.split(‘o’)

print(res)

A

The string ‘Person,Condition,RT’ is stored in the variable dat.

The split(‘o’) method is applied to dat, splitting the string at each occurrence of the letter ‘o’.

The resulting list is stored in the variable res.

It prints the content of res, which contains the parts of the string split at each occurrence of ‘o’.

So output would be: [‘Pers’, ‘n,C’, ‘nditi’, ‘n,RT’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Explain the concept of “white-space” in Python and what it refers to - (2)

A

In Python, “white-space” refers to characters such as tabs, spaces, and newline/carriage-return characters.

These characters are used to format code or data files and are typically invisible when displayed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What does “carriage return” mean in the context of datafiles? - (2)

A

n data files, “carriage return” indicates the end of a line in a datafile.

In Python, it is represented by the special symbol \n, which is interpreted as a “newline” character.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

Example of using \n

What i the output of this code?

print(“Hello\nWorld”)

A

Hello
World

40
Q

Explain this code and its output - (3)

print(“Hello\nWorld”)

A

The string “Hello\nWorld” is passed to the print() function.

You have inserted a newline in between the two words, so they get printed on different lines such as:

Output
Hello
World

41
Q

What is a tab character in Python? - (2)

A

A tab character in Python, represented as \t, is a special type of whitespace character used to align text by moving the cursor to the next tab stop at a fixed interval.

It is commonly used for indentation and formatting purposes in documents, code, or data files.

42
Q

Explain useage of \t in this Python code:

print(“Name:\tJohn Doe”)
print(“Age:\t25”)
print(“City:\tNew York”)

A

When executed, this code will print information about a person with each attribute (name, age, city) followed by a tab character (\t) to align the text neatly in columns.

43
Q

What is output of this code?

print(“Name:\tJohn Doe”)
print(“Age:\t25”)
print(“City:\tNew York”)

A

Name: John Doe
Age: 25
City: New York

44
Q

Explain the functionality of the provided Python code: print(“This\tis\tindented”). - (2)

A

Specifically, it prints the string “This”, followed by a tab character (\t), then “is”, another tab character, and finally “indented”.

When executed, the output will display “This”, followed by several spaces, then “is”, followed by several spaces, and finally “indented”.

45
Q

What is output of code going to be?

print(“This\tis\tindented”)

A

This is indented

46
Q

Explain the functionality of the provided Python code - (6)

my_string = ‘Country\t,GDP\t,Happiness\t,Authoritarianism\t\n\r’
string_list = my_string.split(“,”)

for thisString in string_list:
cleanString = thisString.strip()
print(cleanString)

A

This code initializes a string my_string containing tab-separated values (with commas as delimiters) and newline/carriage return characters.

The string is then split into a list of strings using the split() method with a comma delimiter.

Each element in the resulting list retains the tab characters (\t).

The for loop iterates over each element in string_list, and the strip() method is applied to remove any leading or trailing whitespace, including the tab characters, from each element.

Finally, it prints each cleaned string:

Country
GDP
Happiness
Authoritarianism

47
Q

What is output of this code?

my_string = ‘Country\t,GDP\t,Happiness\t,Authoritarianism\t\n\r’
string_list = my_string.split(“,”)

for thisString in string_list:
cleanString = thisString.strip()
print(cleanString)

A

Country
GDP
Happiness
Authoritarianism

48
Q

Explain the functionality of the provided Python code - (5)

my_string = ‘Country\t,GDP\t,Happiness\t,Authoritarianism\t\n\r’
string_list = my_string.split(“,”)
print(string_list)

A

This code initializes a string my_string containing tab-separated values (with commas as delimiters) and newline/carriage return characters.

Then, it splits the string into a list of strings using the split() method with a comma delimiter

However, the \t and \n\r characters are retained within the string elements in the list, rather than being interpreted as tabs and newline/carriage returns. .

Finally, it prints the resulting list.

Output: [‘Country\t’, ‘GDP\t’, ‘Happiness\t’, ‘Authoritarianism\t\n\r’]

49
Q

A full pathname for a file on a computer consists of a.. together these elements uniquelty identifiy - (2)

A

directory (or folder) and a filename, which must be unique within the directory.

Together, these elements uniquely identify the location of the file within the file system.

50
Q

For example, on a Linux system, the full path to a file in a user’s home directory might be:

A

/home/alex/Documents/PiN_Handout.pdf

51
Q

/home/alex/Documents/PiN_Handout.pdf

The directory which is the file… and filename within directory is… - (2)

A

In this case, the directory which the file is in is /home/alex/Documents and the filename within the directory is PiN_Handout.pdf.

each of home, alex and Documents is a directory. alex is nested within home and Documents is nested within alex.

52
Q

top level directory on Linux systems is known as / -

A

top of the tree /root of file system

53
Q

Explain the concepts of absolute and relative paths in computing

A

An absolute path provides the complete address of a file or directory starting from the root directory, whereas a relative path specifies the location of a file relative to the current working directory.

54
Q

Provide an example of an absolute path in computing - (2)

A

An example of an absolute path in computing is

/home/user/documents/my_file.txt.

This path specifies the complete address of the file my_file.txt, starting from the root directory (/) and including all intermediate directories (home, user, documents).

55
Q

Give an example of a relative path in computing - (3)

A

An example of a relative path in computing is data/my_data.csv.

This path specifies the location of the file my_data.csv relative to the current working directory.

It indicates that the file is located within a directory named data within the current working directory.

56
Q

If a filename does not have a full directory component (i.e. it does not start with / or C: on Windows), it is said to be

A

relative.

57
Q

Why is understanding absolute and relative paths important? - (2)

A

so that you understand where your program will look for files (when you are reading data in) and write files out (when you save data, figures etc out).

Understanding absolute and relative paths is important for determining where files will be located or saved when working with programs.

58
Q

Example of relative path

my_filename = ‘my_file.txt’

If we use this filename when opening or saving a file, it wil be - (2)

A

the file will be searched for or placed in the current working directory

This is the directory which the script “thinks” that it is inside of.

59
Q

What does the %pwd command do in Colab and how is it useful? - (3)

A

The %pwd command in Colab prints the current working directory on the command line interface.

It is a magic command that displays the directory location within the file system where the script or notebook is currently executing.

This information is useful for understanding the file system context and specifying file paths in the script or notebook.

60
Q

Explain the behavior of a Python script in relation to determining its current directory during execution as compared to Colab -(3)

A

When running a Python program, it may need to determine its current directory during execution.

This directory can change independently of the current directory of the Colab interpreter.

The Python script has the ability to manipulate its own execution environment, including changing directories, without affecting the directory of the Colab interpreter

61
Q

Explain the rationale behind using os.getcwd() in Python scripts. than %cwd? - (2)

A

os.getcwd() is preferred in Python scripts for retrieving the current working directory due to its portability and consistency across different environments.

Unlike %cwd, which is specific to Colab and may not work in other environments, os.getcwd() is a standard Python library function that works reliably across various platforms

62
Q

What function can you use within a Python script to find the current working directory? - (2)

A

Within a Python script, you can use the os.getcwd() function to find the current working directory.

This function returns a string representing the current directory path.

63
Q

How can you change the current working directory within a Python script? - (2)

A

You can change the current working directory within a Python script using the os.chdir(dirname) function, where dirname is a string containing the directory path to which you wish to change.

64
Q

Before using os.getcwd() or os.chdir(dirname) and os.listdir(), we have to import module called

A

os

65
Q

What does module os provide?

A

provides functions for interacting with the operating system.

66
Q

Explain this code:

import os

print(os.getcwd()) - (3)

A

The code snippet imports the os module in Python, which provides functions for interacting with the operating system.

It then uses the os.getcwd() function to retrieve the current working directory.

The output of os.getcwd() will be the current directory in which the Python script is being executed.

67
Q

Explain the functionality of os.listdir().

A

os.listdir() is a function in Python’s os module that returns contents , by default, of the current working directory

68
Q

Explain the purpose of the provided code snippet. - (3)

import os
os.chdir(‘/content/sample_data’)
print(os.listdir())
print(os.getcwd())

A

The code snippet changes the current working directory to /content/sample_data using the os.chdir() function, specifying an absolute path (‘it starts with a / meaning the ‘root’ of the tree’)

Then, it prints the contents of the directory using os.listdir(), which lists all the files and directories within the specified directory.

Finally, it prints the current working directory using os.getcwd(), which returns the path of the current working directory.

69
Q

It is usually best to avoid changing the directory that your program is working in and use

A

absolute paths instead

70
Q

Why is it good to use abolsute file path names?

A

One reason is that if your programme crashes while you are in a different directory you might not be in the place you expect when you restart it.

71
Q

If, when you are reading data, you are getting errors such as “No such file or directory”, it is probably because you are using a - (2)

A

relative file path and are not in the correct directory.

Or you have just typed the filename wrong.

72
Q

What is the function used for joining parts of a file path together?

A

The function used for joining parts of a file path together is os.path.join.

73
Q

Why is joining parts of a file together using os.path.join() useful?

A

This is particularly useful if we want to open many files from the same directory

74
Q

In os.path.join () we can simply

A

pass it as many components of the path as we have, and it will join them in the correct manner.

75
Q

Explain what does code does - (4)

from os.path import join

my_dir = ‘/content/sample_data/’

my_file = ‘mnist_test.csv’

my_filename = join(my_dir, my_file)

print(my_filename)

A

The code snippet demonstrates the usage of the join function from the os.path module which joins together directory and file names, creating full file paths (with separators appropriate to the file system you are on).

then defines a directory path (my_dir) and a file name (my_file).

Using os.path.join, it joins the directory path and file name to create a full file path to store in variable (my_filename).

It then prints my_filename which will be: /content/sample_data/mnist_test.csv

76
Q

os.path.join() can also take a

A

string instead of a variable

77
Q

What does the provided code snippet do? - (2)

my_filename2 = join(my_dir, ‘california_housing_test.csv’)

print(my_filename2)

A

The code snippet combines a directory path (my_dir) with a filename (‘california_housing_test.csv’) to create a full file path (my_filename2).

The resulting file path is then printed.

78
Q

What is the output of this code?

my_filename2 = join(my_dir, ‘california_housing_test.csv’)

print(my_filename2)

A

/content/sample_data/california_housing_test.csv

79
Q

You can also pass multiple individual dictionaries to to the join function e.g,

A

print(join(‘/home’,my_dir, ‘ynic’, ‘presentations’, ‘teaching’, ‘pin’,’file.txt’))

80
Q

What does this code do? - (3)

from os.path import join

my_dir = ‘alex’

print(join(‘/home’,my_dir, ‘ynic’, ‘presentations’, ‘teaching’, ‘pin’,’file.txt’))

A

The code snippet showcases the usage of the join function from the os.path module to create a full directory path by joining together multiple individual directory names.

Starting from the root directory /home, it sequentially adds each directory name (‘alex’, ‘ynic’, ‘presentations’, ‘teaching’, ‘pin’) along with the filename ‘file.txt’.

The resulting full directory path is then printe

81
Q

What is output of this code?

from os.path import join

my_dir = ‘alex’

print(join(‘/home’,my_dir, ‘ynic’, ‘presentations’, ‘teaching’, ‘pin’,’file.txt’))

A

/home/alex/ynic/presentations/teaching/pin/file.txt

82
Q

Write a script which creates and prints out filenames for the output files S01.txt to S10.txt in the directory /home/pin/my_data. Obviously these files do not really exist, but you can still create variables containing these paths. You will need to review loops, string formatting and path joining.

A

from os.path import join
base_path=’/home/pin/my_data/’

nSubjects=10 # Because what if we collect more subjects? All we have to do is change this

b=10
a=f’My favourite number is {b} ‘
print(a)

for thisSub in range(1,nSubjects+1): # The +1 is to make sure we go from 1 to 10 inclusive
fileName = f”S{thisSub:02}.txt”

print(join(base_path,fileName))

83
Q

What is the output of this code?

from os.path import join
base_path=’/home/pin/my_data/’

nSubjects=10 # Because what if we collect more subjects? All we have to do is change this

b=10
a=f’My favourite number is {b} ‘
print(a)

for thisSub in range(1,nSubjects+1): # The +1 is to make sure we go from 1 to 10 inclusive
fileName = f”S{thisSub:02}.txt”

print(join(base_path,fileName))

A

/home/pin/my_data/S01.txt
/home/pin/my_data/S02.txt
/home/pin/my_data/S03.txt
/home/pin/my_data/S04.txt
/home/pin/my_data/S05.txt
/home/pin/my_data/S06.txt
/home/pin/my_data/S07.txt
/home/pin/my_data/S08.txt
/home/pin/my_data/S09.txt
/home/pin/my_data/S10.txt

84
Q

R

Reminder, what does :02 do in formatted string - (4)

e.g., b= 1
a = f’Fav number is {b:02}’
print(a)

A

:02 means that the formatted value should be displayed in at least two characters wide, and if the value is less than two digits, it will be zero-padded on the left side to reach the specified width.

For example:

If b is 1, then f’Fav number is {b:02}’ will result in ‘Fav number is 01’.

If b is 10, then f’Fav number is {b:02}’ will result in ‘Fav number is 10’.

85
Q

Comma-separated value (CSV) files are - (2)

A

plain-text files (meaning you can open them in a normal text editor and look at the data) where data items are separated by commas and where new sets of fields are placed on different lines (by means of a new-line character).

They are easy to understand.

86
Q

Example of CSV files

A

Wade,Alex,49

Smith,Joe,21

Doe,Jane, 23

West,Mae,29

87
Q

CSV files are common and can be

A

exported from spreadsheet software and are easy to read and write in just about all programming languages.

88
Q

What does the CSV module in Python facilitate? - (2)

A

The CSV module in Python facilitates the reading and writing of data from and to CSV (Comma-Separated Value) files.

It provides functions specifically designed to handle CSV file operations efficiently.

89
Q

How to import CSV module in python?

A

Type:
import csv

90
Q

What are the 3 modules that have in built CSV readers?

A
  1. Pandas
  2. Numpy
  3. Python CSV module
91
Q

Explain this code - (6) that opens the entire CSV file

A

import csv: Imports the CSV module, allowing us to work with CSV files.

  • ## with open('/content/sample_data/california_housing_test.csv', 'r') as csvfile:: Opens the CSV file in read mode (‘r’). The file path is provided in absolute format.
  • reader = csv.reader(csvfile, delimiter=','): Creates a CSV reader object named reader.
  • The delimiter=',' argument specifies that fields in the CSV file are separated by commas.
  • for row in reader:: Iterates through each row in the CSV file
  • print(', '.join(row)): Joins the items in the current row with commas and prints them
92
Q

What is PANDAS?

A

a Python module designed for reading in and processing data tables, it introduces a new data type called DataFrame

93
Q

Pandas is the most common and easiest way to

A

load in and process .CSV files

94
Q

Example of reading in csv folder in pandas:

A
95
Q

How about the average?

Explain this code - (3):

import pandas as pd
housingTable=pd.read_csv(‘/content/sample_data/california_housing_test.csv’)
housingTable.latitude

averageLatitude=housingTable.latitude.mean()
print(f’Mean latitude={averageLatitude:3.3f}’)

A

This Python code imports the Pandas library as ‘pd’ and reads a CSV file named ‘california_housing_test.csv’ located in the ‘/content/sample_data/’ directory.

The data from the CSV file is loaded into a Pandas DataFrame named ‘housingTable’.

Then, it calculates the mean latitude from the ‘latitude’ column of the DataFrame using the mean() function and prints it with 3 minium width (of entire string) and to 3 DP

96
Q

You can also convert dataframe (pandas) to something you are comfortable with like - (3)

A

a list

e.g., import pandas as pd
housingTable=pd.read_csv(‘/content/sample_data/california_housing_test.csv’)

housingList = housingTable.values.tolist()

97
Q

How about the average?

Explain what this code does - (6)

import pandas as pd
housingTable=pd.read_csv(‘/content/sample_data/california_housing_test.csv’)
housingTable.latitude

print(f’Mean lat: {housingTable.latitude.mean():3.3f}’)

housingList = housingTable.values.tolist()

latitude=housingTable[‘latitude’].tolist()

A

The code imports the Pandas library under the alias pd.

It reads a CSV file named california_housing_test.csv located in the specified path /content/sample_data/ into a Pandas DataFrame named housingTable.

It accesses the latitude column of the housingTable DataFrame.

It calculates the mean of the latitude column using the mean() method and prints it with prints it with 3 minium width (entire string) and to three decimal places.

It converts the DataFrame housingTable into a list of lists using the values.tolist() method and stores it in housingList.

It extracts all values from the latitude column of the housingTable DataFrame and converts them into a list stored in the variable latitude.