Section two - first app Flashcards

1
Q

How do you show the type of something?

A

print(type(var))

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

Show the amount of characters in something

A

len(variable)

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

add an element to a list
What is this called?

A

list.append(“append with this”)

Method, it’s like a function but it’s attached to a data type (list, variable, etc)

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

Capitalize the first lettter of the string variable

Capitalize the first letter in every word

A

These are the methods you attach

print(todo.capitalize())

todo.title()

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

continuously print “Hello”

A

while True:
print(“Hello”)

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

Create a program to enter a password

A

password = input(“Enter a password”)

while password != “pass123”
password = input(“Enter a password”)

print(“Correct”)

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

Show all methods for objects
For instance, how do I find out how to capitalize a string?
Show more info on the method

A

CMD
python3
dir(str)
Methods are after the underscored stuff
help(str.capitalize)

You’ll notice here that it will output “capitalize()” which shows it takes not arguments.

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

List functions like “print”

A

CMD
python3
import builtins
dir(builtins)
Lowercase are all functions
help(input)

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

Create a case program

A

match user_action:
case “add”:
todo = input(“Enter a todo”)
todos.append(todo)
case “show”:
print(todos)

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

Print list elements per line

A

for item in list:
print(item)

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

If I want remove an ending space, what method would we use?

A

user_action.strip()

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

What is python’s interpreter

A

cpython
python download
It’s an interpreter
interprets python to machine language

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

you have created the below list
list = [‘a’, ‘b’, ‘c’]
you want to find the index of ‘b’
What command do you use?

A

list.index(‘b’)

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

Strings are immutable so you can’t change them with
list[0][1] = “-“
instead, what would you use to change a period to a “-“

A

This will replace the string
list[1] = list.replace(“.”,”-“,1)
one means only change the first occurence of the dot.

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

What is the immutable version of a list

A

tuple = (‘this’, ‘that’, ‘other’)

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

how do you read the below explanation for a list method

pop(self, index=-1, /)
remove and return item at index (default last).

A

You put in an index number as the arguement, it will return the removed item.

It will show you what’s in slot in a list

-1 = default value of the argument
So if you enter nothing, it will be -1, the last item. This means you can actually go backwards through a list like this.

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

Sort a list alphabetically

A

list.sort()
dir(list)
help(list.sort())

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

word = “hello”
Replace the o for a period

A

word.replace(“o”, “.”)

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

Store info from your program in a text file

What is the issue with this and how do we solve it?

A

Create a text file in the same directory as your program.

todos = []
todos.append(“cook”) + \n

Create a file object to write to “r” would be read.

file = open(‘todos.txt’, ‘w’)
file.writelines(todos) < - add the whole list “todos”

You might want to add a “+ \n” after your input to put a space in the file.

THIS WILL CREATE A NEW FILE EVERYTIME SO IT WILL DELETE THE OLD INFO WITH EVERY NEW ITERATION.

Instead add this prior to your “w” command and delete your list altogether

todo = input(‘enter a todo: ‘)
file = open(‘todos.txt’, ‘r’)
todos = file.readlines()

REMEMBER TO CLOSE FILE

file.close()
todos.append(todo)

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

Write a simple string to a file instead of a list

A

file = open(‘text.txt’, ‘w’)
file.write(‘Hey this is your text!’)
file.read() <- instead of read lines if you want list form.

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

What does it mean to exhaust file.read()

A

There is a CURSOR in a file that starts at the first item/object in the text file.
When you file.read(), it goes to the end, so if you try to file.read() again, it will output nothing.

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

When adding an absolute path in windows, why do we need to add the “r” prior to the path?

A

r - raw
The reason for this is because certain symbols, like “" in python call a certain thing to happen. Like “\t” giving you a tab. To make sure it only reads it in text form, we add “r”

\n < - things like this are known as escape sequences

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

We have content in one list, and text files in a another, how do we add the content to each of the text files

contents = [‘one’, ‘two’, ‘three’]

files = [‘one.txt’, ‘two.txt’, ‘three.txt’]

A

for content, files in zip(contents, filenames):
file = open(filename, ‘r’)
file.write()

THIS WON’T PRINT ON IT’S OWN

The structure would look like
[(‘one’, ‘one.txt’),(‘two’, ‘two.txt’),(‘three’, ‘three.txt’)]

If you were doing the below
x = zip(contents, filenames)
you could print this only by listing it’s elements
list(x)

24
Q

Create a multiline string in a variable

A

a = “this is a really” \
“I swear it is”

a = “"”This that
and the other”””

25
What's a neat way to iterate items from a list into another one
list = [item.strip('\n') for item in todos]
26
change fhe following to .txt files and dash in their name instead of a . without using a for loop. What is this known as? filename = ['1.doc', 1.report', '1.presentation']
list comprehension - create lists in [with a for loop here] filenames = [filename.replace('.', '-') + '.txt' for filename in filenames]
27
Create a with statement to close your file. Why is this a better way to do things?
with open('todos.txt', 'r') as file: file = todos.readlines() If the program stops because of problems it will always close the file. Otherwise the file will never be closed which can cause problems. Use list comprehension here. This will create a new list and iterate through the items, placing them back in the new list: data = [item.strip() for item in data]
28
If we wanted to know if the word 'add' was in: this = 'add user name' What expression would we use? What expression would we use if add and new were both acceptable What if you needed both What if you wanted to make sure 'and' wasn't in the variable?
if 'add' in this or 'new' in this or 'more' in this: print("True") if 'add' in this and 'new' in this: if 'add' not in this
29
How do you unindent an entire length of code
Copy everything Shift + Tab
30
Take everything after 'add' and print it: variable = 'add clean the bag'
Starts at the 4th spot 'c; print(variable[4:]) If we put 9 at the end, it would mean end at the space before the 9
31
What's the difference between 'if' and 'elif'?
All ifs will be checked Elifs are only checked if ifs aren't true
32
How do I tell if the string is a number or contains a number
This checks if the entire string is a digit Has to be a string hello = "5" hell.isdigit() ========== Check if something CONTAINS a number digit = False for i in password: if i.isdigit() digit = True
33
Check if the below variable is uppercase variable = HELLO
print(variable.isupper())
34
The variable true contains the following booleans: true = [True, True, True] How do we check if they're all true?
if all(true): print('all true') better than if all(true) == True
35
Show via boolean if the variable var contains "add" at the beginning of it
var.startswith("add")
36
You are receiving an error called ValueError in your code, create a good response for it
try: something except ValueError: print("Your command is not valid") continue finally: Continue will take you to the beginning of the loop Break will break you out of the loop
37
What are the two types of errors you can receive?
Syntax and Exception Syntax - you typed something incorrectly Exception - Logical error. Something it not working using the tools you used.
38
Break the program interaction and close it out with the message "an error occurred."
exit("An error occurred)
39
Specify to the function to return absolutely nothing
def greet(): return None
40
Add together all the elements in a list show the biggest number in a list show the lowest number in a list
sum(list) max(list) min(list)
41
what is "var" in: def this(var):
var is a parameter when it is referenced outside of it is an argument, what value you give the argument is the argument value.
42
Separate a variable into two different elements of a list
var = "4 12" list = var.split(" ")
43
What is decoupling and how would you perform it below? def convert(): feet = 3 sentence = f"there are {feet} feet" return sentence
Delete the sentence and only return the data which is needed. In this case it would be "feet".
44
Write a docstring for your function What does this do?
Writes a description for the function def function(): """ Return a string blah blah blah""" print(help(function))
45
Decouple a variable from a function
Decoupling just means you've formatted your function to do something simple and you're not giving back the info super structured. For instance, instead of returning the info in a sentence, just give it back in terms of the hard data
46
What happens when you return more than one object from a function? make it return as a dictionary access it
def parse(): return feet, inches it's given back in the form of a tuple return {"feet": feet, "inches": inches} print(parse()["feet"])
47
How would you create your own python module? Why would you do this? How would you import a module stored in a directory in the same folder as your project?
Move functions over to a separate python document in the same directory. You do this so the code doesn't get too long and complicated. This is really good for organization. from functions import get_todos, write_todos or import functions functions.get_todos() functions.write_todos() IF MODULES WAS THE NAME OF THE DIRECTORY AND FUNCTIONS WAS THE NAME OF THE FILE: from modules import functions
48
What would happen if you added the line print("statement") to a module and imported it What would we do if we only wanted it to print if that module was ran a the main program Why does this work?
It would print put an if statement at the end: if __name__ == "__main__" print("hello") if you print(__name__) it will say __main__
49
What is version control What is github
Lets you track changes between versions download one: git subversion (apache) Bazaar mercurial Cloud based storage for code if you lose access to your code Used for sharing collaboration
50
Use time to show the date and time Is this a standard or local module? Look at time's info
import time time.strftime("%b %d, %Y %H:%M:%S") python.org will have info about this method This is a standard module, it is built into python for you to use. A local module would be in the same directory, something we essentially made. dir(time) you'll find things like CLOCK_MONOTONIC, this and others like it are just variables.
51
Use the glob module Use the csv module
import glob myfiles = glob.glob("files/*.txt") print(myfiles) This will show all text files in list format. You could use this to open multiple files. ======= Create a file that ends with .csv - weather.csv "Station","Temperature" "Kuala Lumpur","45" "New York","25" New python file import csv with open("weather.csv", "r") as file: data = list(csv.reader(file)) date <- this is an iterator object instance now, it's not readable, convert it to a list type outside of with: print(data) This will give you a list of lists, row by row NOW LET'S USE IT city = input("Enter a city: ") for row in data: if row[0] == city: print(row[1]) WE'VE JUST PRINTED OUT THE TEMP FOR NEW YORK
52
Use the shutil module
copy files, create zip files, extract files from zip files shell utility = shutil import shutil shutil.make_archive("output", "zip", "files") This will take the name of the archive we want OUTPUT, we want it compressed ZIP and then the directory that contains all the file we want compressed FILES
53
Use the webbrowser module
import webrowser user_term = input("Enter a search term: ").replace(" ","+") webbrowser.open("https://google.com/search?q=" + user_term)
54
If you were to create a json file that contained questions, options, and answers for a quiz, how would you format it?
[{"question1":"actual question", "options":"all options", "answer":"actual answer" }, {"question2":"actual question", "options":"all options", "answer":"actual answer" } ]
55
You have a json file in your app folder. Import json, open the file, load it's content Print out the first question of the quiz you made in the json file.
import json with open("questions.json", "r") as file: content = file.read() data = json.loads(content) for question in data: print(question["question_text"] for index, alternative in enumerate(question["alternatives"]): print(index, "-", alternative) QUESTION HERE WILL FUNCTION AS THE FIRST ELEMENT OF THE LIST, WHICH IS THE FIRST DICTIONARY. CALLING "QUESTION_TEXT" CALLS FOR THE KEY'S VALUE, WHICH IS THE QUESTION.
56
you have the following dictionary: x = {"a": 6} How would you add the key "b" and give it a value of 7?
x["u"] = 2