Unit 10: Advanced topics in Python Flashcards

1
Q

In this unit, you will be learning ____________.

A

In this unit, you will be learning about some of the helpful tools that Python comes with that you can use to create programs that solve all kinds of problems. These functions are available as soon as you load up Python. Unlike modules like the turtle module, you don’t need to import anything first. Our textbook goes over 12 very useful functions. We’re going to discuss some of those that are most important and relevant.

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

What are some of the math functions?

A

The abs() function gives you the absolute value of a number which is the value of the number without the positive or the negative sign.

our next function is the bool function, which is short for Boolean. When we learnt about conditional statements, we learnt about how these statements evaluate to “True” or “False”, and then an if statement or a while loop will run based on that result. The bool function can help you find out if a statement is “True” or “False” without having to put it in an if statement or a while loop. This function takes one parameter, which is the statement that you want to evaluate. The most important use of this function for us is that it returns “True” if a variable has something in it or “False” if a variable does not have anything in it.
being able to see whether you variables have data in them can come in handy.
This use of the bool function allows you the make sure that your user entered something when asked.

The next-built in function we’re going to discuss is the float() function. Along with the float function, we have the int function. Int()—> turn user input into a number to use for calculations and other aspects of our program.
Remember, a floating-point number is a decimal number, whereas an integer is a positive or negative whole number. You can use both the float function and the int function to turn a string into a floating-point number and an integer respectively. You can also use the int function to turn a floating-point number into an integer.

The len() function lets you know the length of a list, dictionary, or a string.

min() and max()

list(), range()

sum()

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

The absolute value of 3 is ______

A

3

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

The absolute value of -3 is _______

A

3

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

The only parameter that the abs function takes is ________________

A

The only parameter that the abs function takes is the number of which you’re trying to find the absolute value.
For e.g.
abs(3)
Output:
3

For e.g.
abs(-3)
3

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

test_variable_1 = “Hello!”
test_variable_2 = “ “
print(bool(test_variable_1))
print(bool(test_variable_2))

What is the output of this?

A

True
False

Since test_variable_1 has the “Hello!” string in it, the function returned “True” (in this case, “True” tells us that there is something in the variable)

Since test_variable_2 did not have anything in it, the function returned “False” (in this case, “False” tells us there is nothing in the variable).

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

Does the bool function work for other data types too other than strings?

A

Yes, this works for other data types, like lists as well.

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

What is the output of this?
empty_list = [ ]
number_list = [1,2,3,4,5]
print(bool(empty_list))
print(bool(number_list))

A

False
True

our empty list has nothing in it, so the bool function returned “False”, whereas our list of numbers does have data in it, so the bool function returned “True”.

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

age = input(“How old are you?”)
while not bool(age):
print(“You need to enter an age. Please try again.”)
age = input(“How old are you?”)
print(“You are “ + str(age) + “ years old!”)

Explain this code

A

The first line asks the user how old he or she is.
Then we get to a while loop that will run whenever “not bool(age)” is True.
The not keyword means take the opposite Boolean value; so , if you had an expression that evaluates to “True”, the “not” of the expression would be “False” (and, likewise, if you had an expression that evaluates to “False”, the “not” of that expression would be “True”).

So
If age is empty, bool(age) will return False and we want our while loop to run (evaluate to “True”) if age is empty, so we take the opposite of that with “not”. Inside our while loop, we give the user an error message and then ask for the input again.

Since it’s a while loop, these two steps will keep occurring until the user correctly enters some kind of input.

Finally, once a correct input is received, the program prints out the age. This use of the bool function allows you the make sure that your user entered something when asked.

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

What is the output of this?

float_string = “3.1”
result_1 = float(float_string) + 1
result_2 = int(result_1)
print(result_1)
print(result_2)

A

4.1
4

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

string = “I love Python!”
length = len(string)
print(length)

What is the output of this and why?

A

The output of this is 14.
As expected, this string contains 14 characters. Remember, spaces are included as a character.

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

We can use a for loop to print out each of the characters in a string. You can refer to a string like it’s a list for this.

string = “I love Python!”
length = len(string)
for count in range(0, length):
print(length)

A

I

l
o
v
e

p
y
t
h
o
n

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

What is the output of this?
numbers = [2,9,4]
print(min(numbers))
print(max(numbers))

A

2
9

you can also put the numbers right into the min and the max functions like this
print(min(2,9,4))
print(max(2,9,4))
You will still get the same output. This is a good time saving trick if you do not need to keep your list of numbers around for something else

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

list()
range() functions
What are the meaning of each of the above functions?
How can list() and range() be used together?

A

The list function creates a list from information given to it.
What the range function actually returns is a special thing called an iterator. you can also add a third parameter, called the step. This lets you count “by” the number. You don’t need to add 1, since Python assumes that is the way to count unless stated otherwise by your code.
You can use the list function to store this information in it.

print(list(range(0,7)))
Output:
[0,1,2,3,4,5,6]

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

Can you count using a negative number?

A

Yes.
You can also count the other way by using a negative number as the step and reversing the two numbers so that you are starting at a higher number and going to a lower number, like this: print(list(range(7,0,-2)))

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

What does the sum() function do?

A

This lets you add up the contents of your list.

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

Replace some parts of the code with sum() for this code:

def calculate_average(scores):
total = 0
number_of_scores = len(scores)
for count in range(0, number_of_scores):
total = total + scores[count]
average = total/number_of-scores
return average

A

def calculate_average(scores):
number_of_scores = len(scores)
total = sum(scores)
average = total/number_of-scores
return average

scores = [93,87,98,82]
print(calculate_average(scores))

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

How do you go into the builtins catalog and help menu?

A

Open up IDLE and type in the following. Note the two underscores “_” before and after builtins.

> > > dir(__builtins__)

When you press ENTER, you should see a list of all of the built-in functions available to you:

[‘ArithmeticError’, ‘AssertionError’, ‘AttributeError’, ‘BaseException’,…
…‘str’, ‘sum’, ‘super’, ‘tuple’, ‘type’, ‘vars’, ‘zip’]
Now you can use the “help()” function to figure out how to use any of the built-in functions listed. For example, lets look at the min function:

> > > help()
Welcome to Python 3.9’s help utility!
…..
help> min
Press ENTER again and you should see a description of the min() function, including any parameters that you’ll need to include when you call it in your code.

Help on built-in function min in module builtins:

min(…)
min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value

With a single iterable argument, return its smallest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the smallest argument. Basically, this is telling you that you need to include something iterable, like a list, when you call the function min(), and it will return its smallest item. For example:

> > > min([5,18,3,109,1,64,2])
1
When you’re done exploring the built-ins, type “quit” to exit the help menu and return to IDLE.

help> quit
You are now leaving help and returning to the Python interpreter.

»>

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

What is the built-in function for returning the value of a number without the positive or negative sign?

A

abs(my_variable)

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

What is the built-in function for taking a string and returning a decimal for arithmetic?

A

float(my_variable)

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

What is the built-in function for taking a string and returning a whole number for arithmetic?

A

int(my_variable)

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

What is the built-in function that returns True if a variable has something in it or False otherwise?

A

bool(my_variable)

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

What is the built-in function for this: keyword that evaluates the opposite of a boolean value (either True or False)?

A

not bool(my_variable)

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

What is the built-in function for returning the number of items in a list?

A

len(my_list)

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

What is the built-in function for creating a new list?

A

list(item1,item2,item3)

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

What is the built-in function to return a special iterator to step through a list?

A

range()

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

Create a list of integer values, then sort and reverse the list using built in functions.

A

Create the reversed list

Your code should look like this
#Create a list
my_list = [22,31,3,5,66,32,9,11]
#Create the sorted list
my_sorted_list = sorted(my_list)

my_reversed_list = sorted(my_list, reverse=True)

print(my_list)

print(my_sorted_list)

print(my_reversed_list)

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

What are modules?

A

Modules are a collection of functions, variables, and other things together that you can use to build programs.

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

What is this module “sys” ,object “stdin”, and the function “readline()” for?

A

It gives us another way to read in information from our user. (get input from the user)

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

What is the output of this?

import sys
def say_hi():
print(“What’s your name?”)
user_name = sys.stdin.readline()
print(“Hello, {}”.format(user_name))

say_hi()

A

What’s your name?
John
Hello, John

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

What is the module datetime for?

A

to find out the exact time and date now

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

What is the output of this?
import datetime
print(datetime.datetime.now())

A

It depends on when you are coding this. The date and time will be reflected accordingly.

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

Which of the following correctly uses a Python module to get input from the user?

system.userinput()

sys.stdin.getline()

system.input()

sys.stdin.readline()

A

sys.stdin.readline()

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

Which of the following correctly uses Python’s datetime module to get the current date and time?

datetime.now()

datetime.gettime(now)

datetime.datetime.now()

import datetime.now()

A

datetime.datetime.now()

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

How can you create our own module?

A

You can create a module by simply writing Python objects (functions, lists, variables, etc.) inside a program file with .py extension and then save the file in a directory or folder where another Python program can access the module file. It could be in the same folder where the caller program resides or a folder in PYTHONPATH (an environment variable which you can be set to add additional directories where Python will look for modules and packages). PYTHONPATH is out of the scope of this tutorial, so we will only discuss the first option.

36
Q

Imagine that you would like to create a module called my_calculator to do multiplication, division, addition, and subtraction using two numbers. First, let’s write the following 4 functions in a program called my_calculator.py and save that file into a folder.

def add(num1, num2):
print(“{} + {} = {}”.format(num1,num2, (num1+num2)))
def sub(num1, num2):
print(“{} - {} = {}”.format(num1,num2, (num1-num2)))
def mult(num1, num2):
print(“{} x {} = {}”.format(num1, num2, (num1*num2)))
def div(num1, num2):
print(“{} / {} = {}”.format(num1, num2, (num1/num2)))
my_calculator is now a module that you can use to do mathematical arithmetic operations in another program that imports the my_calculator module.

Now, say you would like to use my_calculator module inside a program file called test_module.py. You would need to write the following Python program and save that file into the same folder where you’ve already saved the my_calculator.py file : ____________________________

A

import my_calculator
my_calculator.add(4, 5)
my_calculator.sub(10, 2)
my_calculator.div(18, 3)
my_calculator.mult(5, 6)
Using the import statement, you made the module objects or contents available in your program. However, you can’t directly access the functions like

add(4, 5)
sub(10, 2)
div(18, 3)
mult(5, 6)
This is because a module creates a separate namespace (an area where a name is unique and can be used without any ambiguity). By pre-fixing the module name, you can get the access to that module namespace.

If you don’t want to use the module name as prefix using the “.” operator, you will need to import the objects inside the module into your program like this example:

from my_calculator import *
Now you can use those function with any prefix.

add(4, 5)
sub(10, 2)
div(18, 3)
mult(5, 6)
Note that asterisk ‘*’ in the import statement means to import all objects inside the module. This isn’t, however, a recommended approach in a large program because you are importing all those variables and function names into your own program namespace. This could cause a naming conflict unless you know them all well and can be confident there won’t be a conflict. Otherwise, you have a decent chance of overwriting an existing name inadvertently.

A better alternative would be to bring in a few functions that you would like to use from the module. For example: say you would like to use the mult function only. You could import the mult function from the module like the example below and then use that function directly.

from my_calculator import mult
mult(5, 6)
Some of the advantages of creating and using modules in Python are: they enable you to organize your code into smaller pieces that are easier to manage and the code in the modules can be reloaded and rerun as many times as needed, which enables code reuse.

37
Q

This is one of the way in which you can import module

import module_name

What happens?
Why use it?
Give an example.

A

What happens?

The whole module is imported, and you can use all its functions and variables.
To call a function, you need to prefix it with the module name (e.g., module_name.function_name()).
Why use it?

Keeps things organized because every function you call is clearly linked to the module.
No risk of naming conflicts since you’re using the module name to differentiate functions.
Example:

python
Copy code
import my_calculator

my_calculator.add(4, 5) # Clear where ‘add’ comes from
my_calculator.sub(10, 2)

38
Q

This is one of the ways in which you can import module.

from module_name import specific_function

What happens?
Why use it?
Give an example.

A

What happens?

You import only specific functions or variables that you want from the module.
You don’t need the module name prefix to use the functions.
Why use it?

Makes your code shorter and more readable if you’re only using a few specific functions.
Saves memory if the module is large but you only need some parts of it.
Example:

python
Copy code
from my_calculator import add, sub

add(4, 5) # No need for my_calculator.
sub(10, 2)

39
Q

This is one of the ways in which you can import module.
from module_name import *

A

What happens?

Everything in the module is imported into your program’s namespace (as if you wrote it directly in your program).
You can call any function in the module without a prefix.
Why use it?

Rarely recommended because it imports everything, which can cause conflicts if two modules have functions with the same name.
You lose track of where the functions came from, making your code harder to debug.
Use only for small programs or quick experiments.
Example:

python
Copy code
from my_calculator import *

add(4, 5) # No module prefix needed
sub(10, 2)

40
Q

how do you know which import module methods you should use?

A

Key Differences Summarized:
Method What You Get Function Call Recommended?
import module_name Full module module_name.func() Yes, for clarity.
from module_name import func Specific function(s) only func() Yes, for small needs.
from module_name import * Everything from the module func() No, risky in large programs.
Your Summary Was Great!
Here’s how it aligns:

  1. You’re importing everything and calling functions with the module name.
  2. You’re importing specific functions and calling them directly, making code shorter.
  3. You’re importing everything but calling only the functions you need (risky in bigger projects).
41
Q

What is object oriented programming (OOP)?

A

Object oriented programming is a way of modelling objects (any other kind of object you can think of) in the real-world for us in computer programs.

Chatgpt’s answer: OOP is a programming style that models real-world objects using attributes (data) and behaviours (methods. Object combine data and functions to make code easier to manage.

42
Q

In OOP, we define an object by some of its ___________ and _______________.

A

In OOP, we define an object by some of its attributes and associated behaviours.

For example.g., a pet has some attributes such as name, age, breed, or colour.

It also has certain behaviours—> it can walk, eat, sleep, or speak (bark sound)

43
Q

There are lots of attributes and behaviours of an object so we should define all those attributes and behaviours. Is this true?

A

No. We should only define those attributes and behaviours that we want to use to solve the problem we are working on.

44
Q

What is the meaning of object oriented analysis (OOA)?

A

The process of brainstorming to identify attributes and behaviours of an object.

45
Q

After we finish our OOA, we ______________.

A

After we finish our OOA, we write the data or attributes names and the names of the object’s behaviours. This part of the process is called Object Oriented Design (OOD).

46
Q

What are the steps to Object oriented programming?

A

1.Figure out which attributes and associated behaviours we want to focus on (OOA)
2. We write the data or attributes names and the names of the object’s behaviours (OOD)
3. We write a program to model that object using those attributes and behaviours we decided on OOP)

47
Q

Everything in Python is an object. Is this true?

A

Yes. A string, integer, float, Boolean, list and map— all of these are objects in Python.Those objects are given to us to use by the Python language developers. Using OOP, we can create our own custom data types and use them.

48
Q

In Object Oriented Programming (OOP), the goal is to define an object using which of the following?

attributes and behaviors
analysis and design
type and variables
models and namespace

A

Attributes and behaviours

49
Q

A value passed when calling a function is ___

A

argument

50
Q

Solve problems by calling functions and passing data into the function if needed: ________

A

functional approach

51
Q

An instance of something in object oriented programming: _______

A

object

52
Q

Solve problems by modelling objects using attributes and behaviours: ___________

A

object oriented approach

53
Q

Data or characteristic of an object: _______

A

attribute

54
Q

An action or method of an object: ____

A

Behaviour

55
Q

Used on an object to access an attribute or call a method: ______

A

Dot operator

56
Q

What is encapsulation?

A

Encapsulation is the concept of keeping an object’s data and the methods that modify it together, so the object manages its own state and reduces the need for external variables.

57
Q

What are the benefits of OOP? Name three advantages of Object-oriented programming (OOP).

A
  1. Encapsulation reduces the need for external data management .
  2. Reusability allows objects to be reused in multiple programs.
  3. Real-world modelling makes it easier to understand and code real-world scenario.
58
Q

How do you create an object in OOP?

A

Use a class to define the object type, then create the object with
object_name = ClassName()

59
Q

What is the dot(.) operator used for in OOP?

A

The dot operator is used to call an object’s methods (functions) or access its attributes (data).

60
Q

How does the functional approach differ from OOP?

A

Functional programming uses standalone functions and requires external variables for data. OOP organises data and functions into objects, reducing external data management.

61
Q

Why does OOP have fewer bugs compared to functional programming?

A

OOP encapsulates data inside objects, reducing the risk of accidentally modifying or corrupting the data externally.

62
Q

What are methods in OOP?

A

Methods are functions defined inside a class that define an object’s behaviour, like deposit_money() or withdraw_monet() in a BankAccount object.

63
Q

What is an example of OOP in PyBank? In PyBank, how would you deposit $100 into your bank account using OOP?

A

my_bank_account = BankAccount()
my_bank_account.deposit_money(100.00)

64
Q

What is the difference between the first and second OOP approaches in PyBank?

A
  1. First approach use set_deposit_amount() and deposit_money() to handle deposits.
  2. Second approach: Pass the amount directly into deposit_money(100.00)
65
Q

What will the following code print out?

print(int("5.125")) Question 1Select one:

a.
5.125

b.
It displays an error message.

c.
5

d.
6

A

b It displays an error message is the correct answer

Explanation:
The int() function cannot convert a string containing a decimal (like “5.125”) to an integer. It will raise a ValueError.

You cannot convert a string containing a float immediately into an integer in one step. You have to convert it into float first and then into an integer

66
Q

You want to model a real-life MacBook computer using Object Oriented Analysis. Which of the following would be ideal candidates for the behaviors of your MacBook computer object?

*Choose all that apply.

Question 2Select one or more:

a.
screen_size

b.
price

c.
turn_on

d.
run_program

A

Answer:
c. turn_on
d. run_program

Explanation:
Behaviors represent actions that an object can perform. turn_on and run_program are actions a MacBook can perform, while screen_size and price are attributes (properties of the object).

67
Q

What will the following code print out?

empty_string = ''
print(bool(empty_string)) Question 3Select one:

a.
False

b.
True

c.
None

d.
It displays an error message.

A

a
Explanation:
An empty string in Python evaluates to False when converted to a boolean.

68
Q

True or false? When completing Object Oriented Analysis (OOA) and Object Oriented Design (OOD), the primary goal is to define as many attributes and behaviors as we can for the real-world object.

Question 4Select one:
True
False

A

Answer:
False

Explanation:
The primary goal of OOA and OOD is to define the relevant attributes and behaviors for the object, focusing on what is necessary for modeling the system.

69
Q

You want to model a real-life camera using Object Oriented Analysis. Which of the following would be ideal candidates for the attributes of your camera object?

*Choose all that apply.

Question 5Select one or more:

a.
take_picture

b.
brand

c.
charge_camera

d.
battery_level

A

Answer:
b. brand
d. battery_level

Explanation:
Attributes represent properties of an object. brand and battery_level describe a camera, while take_picture and charge_camera are behaviors.

70
Q

The following loop will run __________ times.

my_list = [5,7,3,2,8,9,1,6,9,8]
for i in range(1, len(my_list), 3):
    print(i) Question 6Select one:

a.
4

b.
3

c.
2

d.
The loop will throw an index error.

A

b
Explanation:
range(1, len(my_list), 3):

The range function generates numbers starting from 1, up to (but not including) the length of my_list (len(my_list) = 10), with a step of 3.
The sequence generated will be:

Start at 1.
Add 3 → 4.
Add 3 → 7.
Add 3 → 10 (but this is excluded because the range stops before 10).
So, the values for i will be: 1, 4, 7.

Iteration Count:

The loop runs once for each value in the sequence: 1, 4, 7.
This means the loop runs 3 times.
Output of print(i):
plaintext
Copy code
1
4
7
Correct Answer:
The loop will run 3 times, so the correct answer is:

b. 3.

71
Q

What will the following code print out?

print(min(1, -6, 3, 1, 1, 1)) Question 7Select one:

a.
It will display an error about having too many 1s.

b.
1

c.
3

d.
-6

A

d
Explanation:
The min() function returns the smallest value among the arguments, which is -6.

72
Q

What will the following code print out?

single_space = ' '
print(bool(single_space)) Question 8Select one:

a.
False

b.
True

c.
None

d.
It displays an error message.

A

Answer:
b. True

Explanation:
A single space is a non-empty string, and non-empty strings in Python evaluate to True when converted to a boolean.

73
Q

To read information from the user using sys.stdin.readline() statement, we need to import which module?

Question 9Select one:

a.
io

b.
system

c.
stdin

d.
sys

A

Answer:
d. sys

Explanation:
The sys.stdin.readline() method belongs to the sys module, so it needs to be imported.

74
Q

What is the output of the following statement?

print(len(["Hello! Python is fun"])) Question 10Select one:

a.
1

b.
4

c.
7

d.
20

A

Answer:
a. 1

Explanation:
The argument to len() is a list containing a single string. The length of the list is 1, regardless of the content of the string.

75
Q

If you use a Windows computer, _________________________ to create a file to use with Python.

So how does it work?

A
  1. If you use a Windows computer, we’re going to use a built-in program called Notepad to create a file to use with Python.

You might open it a little differently based on the version of windows that you’re using.
2. In order to open up Notepad, go to your windows menu, scroll to the Windows Accessories and open the dropdown.–> from there you will select Notepad

  1. Once you have opened the Notepad program, type the code you want into the empty file it displays:
  2. Once you’ve typed those two lines into the file, click on File and then save.
  3. This will bring up a dialog box that allows you to save your file on your computer.
  4. In order to make it easier to find it later, we are going to choose a specific location to save the file, the C drive.
    On this computer, we’ll click on this PC and then the C drive.
    Double-click on the Users folder and then the folder with your username. Make sure you know what this username is, because you’ll need it later on to be able to get to your file.
  5. Enter myfile.txt as the file name at the bottom of the box and click on the Save button. Now you will have a file called myfile.txt to use as we learn about Python.
76
Q

If you use Mac OS X computer, we’re going to use _________________________to create a file to use with Python.

A
  1. If you use Mac OS X computer, we’re going to use a built-in program called TextEdit to create a file to use with Python.
  2. In order to open up TextEdit, on this computer we’ll click the Finder, then Applications, then we’ll scroll down to TextEdit.
    Double click the icon to open up the program.
  3. Type the code you want in to the empty file it displays.
  4. Once you have typed those two lines into the file, click on Format and then on Make Plain Text. Then, click on File and then Save. This will bring up a dialog box that allows you to save your file on your computer.
  5. In order to make it easier to find later, click on your username in the dropdown.
    You may need to click the expand button to see this option.
    Make sure you know what this username is, because you’ll need it later on to be able to get to your file.
  6. Enter myfile.txt as the file name in the box.
    Click on the Save button. Now, you will have a file called myfile.txt to use as we learn about Python.
77
Q

Manipulating files in Python allows you to _____________.

A

Manipulating files in Python allows you to save data into a file for later reference and then to read that data back into Python at a later time.

78
Q

What is the function: open() for?

A

This function takes one parameter, which is the location of the file that we want to open.

79
Q

What is the code for opening files on a windows computer?
Explain the code too.

A

my_file = open(‘C:\Users\ \myfile.txt’)

It tells Python that your file (named myfile.txt in this case) can be found on your main hard drive (the C:\) drive. Then, it tell it that it needs to look in the Users folder. Inside the Users folder, it tells it that it needs to look inside the USERNAME folder.
You’ll replace the USERNAME with the username of your personal computer.

80
Q

What is the code for opening files on a Mac OS X computer?
Explain the code too.

A

my_file = open(‘/Users/ctyuser/myfile.txt’)

This tells Python to go in the Users folder first and then inside the USERNAME folder.

Just like with a Windows computer, you’ll replace the USERNAME with the username of your own personal computer.
Inside the USERNAME folder, Python will look for your file (named myfile.txt)

81
Q

What do you do after having your file opened in Python with this code:
my_file = open(‘C:\Users\ \myfile.txt’)?

A

Our variable my_file is actually an object and it has certain functions that we can use on it.
then you use the read() function and finally print out what’s in the contents variable so that we can see our file.

82
Q

What is the read() function for?

A

It will put the contents of the file into a new variable called contents.

We can also put our data into a list.

83
Q

What is the readlines() function for?

A

The readlines() function will put each line of the file into a separate element of the list.

For e.g.
data = my_file.readlines()
print(data)

Output:
[‘I love Python!\n’,’Python is super useful!’]

the slash “\n” at the end of the first line is the return character.
It’s what told our text editor that we wanted to type our second sentence on a new line.

Since the data is now in a list, we can use all of the techniques we learnt in the unit on lists to look at the data.
Let’s try using a for loop to print out each line.

data_count = len(data)–> this line of code finds out how big our list is so that we know how many times to un the for loop.

The line below will look at each item in the list.
for count in range(0, data_count):
print(“Line” + str(count) + “:” + data[count])

The last line prints out the contents where we are in the list including a number to tell us where we are.

We added a count to see what was on each line of our text file.
This is the output:
Line 0: I love Python!
Line 1: Python is super useful!

84
Q

What is one of the most useful things that you can do with files?

A

Keeping information in them until you need it.

85
Q

Code a program that stores the test scores in a separate notepad and then use it in IDLE to read in the file and put all of the scores inside of a list before calculating the average.

What happens if you need to change the scores?

A

scores_file = open(‘C:\Users\aryan24\scores.txt’)

test_scores = scores_file.readlines()
print(test_scores)

scores_count = len(test_scores)
for count in range(0, scores_count):
test_scores[count] = int(test_scores[count])

def calculate_average(scores):
number_of_scores = len(scores)
total = sum(scores)
average = total/number_of_scores

print(calculate_average(test_scores))

The first line opens up the test scores file so that we can use it to get the data out.

the second line actually gets the data out and puts it in list form inside the test_scores list

the third line prints out the contents of the test_scores list so that we can make sure that we did it all correctly.

the fourth line counts the number of test scores we have so that we can change each of them into an integer.

the fifth line runs the for loop from 0 to the number of scores we calculated before. this makes sure that we change each score to an integer.

Finally, we have to take each test score, change it into the integer version, and then put it back inside the list where it was to start.

Now, we can use our function that we wrote with the sum built-in function to calculate the average of our scores.

If you need to change the test scores, we will open up the scores.txt file, delete what we wrote before, and put in ten different test scores, for e.g.

86
Q

Will Python ignore those \n?

A

Yes

Python actually ignores that information when going through it; they are a special type of “word” to Python that it doesn’t really see.