Python Basics Flashcards

1
Q

Set a variable to your name

A

var = “Aman”

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

Print “Hello, Treehouse”

A

print(“Hello, Treehouse”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
Which of these Python blocks is correctly formatted?
      a. def my_function() : {
	print(“Hello”)
       }
      b. def my_function() 
	print(“Hello”)
  c. def my_function() :
print(“Hello”)
A

c. def my_function() :

print(“Hello”)

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

How would you name a variable that has two words like hello there?

A

Hello_there

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

What is print()?

A

Function

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

TF: Syntax is what we call the rules for writing in a programming language.

A

True

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

How many equal signs do you need to create a variable?

A

One

variable = value

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

TF: Using help() is cheating

A

False

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

To look up the documentation about the str class’s upper method, I’d use help()

A

help(str.upper)

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

TF: The Python shell is a great place to write the final version of your code.

A

False

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

To leave the Python shell, run the ____ () function.

A

exit()

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

I have a script named hello_treehouse.py. How would I run that?

A

python hello_treehouse.py

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

TF: Before we can run a Python script, we have to run a separate, distinct compilation step.

A

False

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

TF: When we’re writing a Python script, we have to include&raquo_space;> in front of every line.

A

False

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

What keyword is used to delete a variable?

A

Del

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

What are whole numbers in Python called?

A

Integers or ints

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

What are numbers with decimals called?

A

Floats

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

What are the rules regarding adding, subtracting, multiplying, and dividing when using ints and floats?

A

When you add, subtract or multiply, you always get ints, unless you are using a float.
When you divide, you always get a float.

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

What happens when you divide by 0?

A

You receive a Zero Division Error.

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

What do you use when you need to convert a value to an integer or a float?

A

int()

float()

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

Can you use += or -= in python?

A

Yes

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

What are the 4 ways to make strings?

A

Single quotes, double quotes, triple quotes, str function

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

Can you multiply a string and a number?

A

Yes

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

How would use .format to add a number to a string? “There are {} people here”

A

Message = “There are {} people here”.format(6)

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

What’s unique about python lists?

A

They are kind of like arrays but can hold different types in them like strings, numbers, lists.
Lists are mutable

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

What are 2 great methods to add to lists?

A

append() → only for one item
my_list.append(6)

extend() → for more than one item
my_list.extend([4, 5, 6])

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

What method do you use for removing something from a list?

A

remove() → only for one item

my_list.remove(7)

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

Why can’t you run list(5)?

A

Because it is one item. A list must be iterable.

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

What is the purpose of the split method?

A

When we want to break a string into a list based on something that repeats in the string, we use the .split() method. It separates by whitespace (i.e. spaces, tabs, newlines, etc). Or you have to explicitly say by what.
“Hello there”.split() produces [“Hello”, “there”].
“name;age;address”.split(“;”) produces [“name”, “age”, “address”].

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

What is the purpose of the join method?

A

.join() method lets us combine all of the items in a list into a string (and only string items).
my_favorite_colors = [“green”, “black”, “silver”]
my_string = “My favorite colors are “
my_string + “, “.join(my_favorite_colors)

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

PROBLEM
available = “banana split;hot fudge;cherry;malted;black and white”

Use .split() to break the available string apart on the semi-colons (;). Assign this to a new variable sundaes.

Make a new variable named menu that’s set to “Our available flavors are: {}.”.

Then reassign the menu variable to use the existing variable and .format() to replace the placeholder with the new string in display_menu.

A

sundaes = available.split(‘;’)

menu = “Our available flavors are: {}.”

menu = “Our available flavors are: {}.”.format(‘, ‘.join(sundaes))

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

What are the index rules?

A

0 is the first index and then it goes by 1.

If you want the last index, use -1. If you want second to last, use -2. Etc etc.

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

If you have a list called alpha_list which has the follow [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] and you want to remove c, what can you do?

A

2 Ways to remove it

alpha_list.remove(‘c’)
del alpha_list[2]

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

What are the numerical values for true and false?

A
False = 0
True = 1
35
Q

What are the boolean values for true things vs false things?

A

Full things are true

Empty things are false

36
Q

What are the symbols for equal to and not equal to?

A

==

!=

37
Q

What are the symbols for lesser, greater or equal etc.?

A

> <
<=
=

38
Q

What does ‘is’ do?

A

It checks whether or not the two values are in the same place in memory.

39
Q

If I want to make sure that age is exactly equal to 25, which comparator should I use?

A

==

40
Q

Which comparison means “not equal to”?

A

!=

41
Q

Give a comparison that would be True for the following: 5 2

A

!=

42
Q

All comparators, things like >=,

A

False

43
Q

TF: <= means “greater than or equal to”.

A

False

44
Q

How do you write an if statement?

A

If a < b:

print(“ok”)

45
Q

How do you write else if?

A

elif a == b:

print(ok)

46
Q

Make an if condition that sets admitted to True if age is 13 or more.

A

Admitted = None
if age >= 13:
admitted = True

47
Q

Add an else statement that turn admitted into false if you are younger than 13.

A

else:

admitted = False

48
Q

What does in check for?

A

Containment or inclusion

Checks whether a value is in a value or list

49
Q

What does not in check for?

A

Checks whether a value is not in a value or list

50
Q

time = 15

store_open = None
store_hours = [9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

I need you to make an if condition that sets store_open to True if time is in the store_hours list. Otherwise, if time isn’t in store_hours, set store_open to False. You’ll probably have to use if, else, and in to solve this one.

A

if time in store_hours:
store_open = True
else:
store_open = False

51
Q

What do for loops do?

A
for loops run a certain number of times and then end themselves
numbers = [1, 2, 3, 4]
doubles = []
for number in numbers:
    doubles.append(number*2)
52
Q

What do while loops do?

A
while loops, on the other hand, run until their condition, like an if has, turns False. 
Start = 10
While start:
	print(start)
	Start -= 1
53
Q

What does break do?

A
Break lets us break a loop early and not do anymore looping
for letter in "abcdef":
    if letter == "c":
        break
    print(letter)
This will stop printing after c
54
Q

What does ‘continue’ do?

A
Let’s you continue and skip over whatever condition you want. 
for letter in "abcdef":
    if letter == "c":
        continue
    print(letter)

This will skip c but print everything else out.

55
Q
hellos = [
    "Hello",
    "Tungjatjeta",
    "Grüßgott",
    "Вiтаю",
    "dobrý den",
    "hyvää päivää",
    "你好",
    "早上好"
]

I need you to write a for loop that goes through each of the words in hellos and prints each word plus the word “World”. So, for example, the first iteration would print “Hello World”.

A

for hello in hellos:

print(“{} world”.format(hello))

56
Q

What does the input function do?

A
the input() function is used to get information from a user.
input(“what’s your age?”)
Inputs are saved as strings. 
We can save inputs as strings like this 
Age = int(input(“What’s your age? ”))
57
Q

I need age to be an integer. What do I need to add?

age = ___________ (input(“What is your age? “))

A

Int

58
Q

When writing a function? What does the keyword def do?

A

Def stands for define. Then you put the name of the function.

59
Q

In a function, what are the contents inside the parentheses called? hows_the_parrot()

A

Arguments

60
Q

Write a function named printer. The function should take a single argument, count, and should print “Hi “ as many times as the count argument. Remember, you can multiply a string by an integer.

A
Def printer(count):
	print(“Hi” * count)
61
Q

I need you to write a function named product. It should take two arguments, you can call them whatever you want, and then multiply them together and return the result.

A
def product(x, y):
    return(x * y)
62
Q

What is the purpose of try and except?

A

The try block is just that, the word try followed by a colon. Inside of the block, indented, is the code that you think might ‘cause an issue.
You want to create an except block for every type of exception your try block might cause. - this is like catch in Swift

try:
speed = int(input(“What is the airspeed velocity of an unladen swallow? “))
except ValueError:
print(“What? I don’t kno-oooooooooooooooo!”)
else:
print(“I think a swallow could go faster than {}.”.format(speed))

63
Q

I need you to make a new function, add.
add should take two arguments, add them together, and return the total.

Let’s make sure we’re always working with floats. Convert your arguments to floats before you add them together. You can do this with the float() function.

Add a try block before where you turn your arguments into floats.
Then add an except to catch the possible ValueError. Inside the except block, return None.
If you’re following the structure from the videos, add an else: for your final return of the added floats.

A
def add(num1, num2):
    return(num1 + num2)
def add(num1, num2):
    return(float(num1) + float(num2))
def add(num1, num2):
    try: 
        (float(num1) + float(num2))
    except ValueError:
        return None
    else:
        return (float(num1) + float(num2))
64
Q

How do you leave comments?

A

#

65
Q

I need you to help me finish my loopy function. Inside of the function, I need a for loop that prints each thing in items.

def loopy(items):
    # Code goes here

Oops, I forgot that I need to break out of the loop when the current item is the string “STOP”. Help me add that code!

A
def loopy(items):
    # Code goes here
    for item in items:
        print(item)
def loopy(items):
    # Code goes here
    for item in items:
        if item == "STOP":
            break
        else: 
            print(item)
66
Q

Same idea as the last one. My loopy function needs to skip an item this time, though.
Loop through each item in items again. If the character at index 0 of the current item is the letter “a”, continue to the next one. Otherwise, print out the current member.
Example: [“abc”, “xyz”] will just print “xyz”.

def loopy(items):
    # Code goes here
A
def loopy(items):
    # Code goes here
    for item in items:
        if item[0] == 'a':
            continue
        else:
            print(item)
67
Q

How do you import libraries?

A

Use import keyword.

import random

68
Q

Write a function named even_odd that takes a single argument, a number.
return True if the number is even, or False if the number is odd.
You can use % 2 to find out the remainder when dividing a number by 2. Even numbers won’t have a remainder….

A
def even_odd(number):
    if number % 2 == 0:
        return True
    else:
        return False
69
Q

Create a new function named just_right that takes a single argument, a string.
If the length of the string is less than five characters, return “Your string is too short”.
If the string is longer than five characters, return “Your string is too long”.
Otherwise, just return True.

A
def just_right(string):
    if len(string) < 5:
        return "Your string is too short"
    elif len(string) > 5: 
        return "Your string is too long"
    else:
        return True
70
Q

This challenge is similar to an earlier one. Remember, though, I want you to practice! You’ll probably want to use try and except on this one. You might have to not use the else block, though.

Write a function named squared that takes a single argument.

If the argument can be converted into an integer, convert it and return the square of the number (num ** 2 or num * num).

If the argument cannot be turned into an integer (maybe it’s a string of non-numbers?), return the argument multiplied by its length. Look in the file for examples.

A
def squared(num):
    try:
        return int(num) * int(num)
    except ValueError:
        return num * len(num)
71
Q

What do the keywords and & or do?

A

and - lets us define two conditions that must be True

or - lets us define two conditions, one of which must be True

72
Q

What does str.isalpha() do?

A

Returns whether or not all of the characters in a string are alphabetical

73
Q

You’ve seen how random.choice() works. It gets a random member from an iterable (like a list or a string).
I want you to try and reproduce it yourself.
First, import the random library.
Then create a function named random_item that takes a single argument, an iterable. Then use random.randint() to get a random number between 0 and the length of the iterable, minus one. Return the iterable member that’s at your random number’s index.
Check the file for an example.

A
import random
# EXAMPLE
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"
def random_item(word):
    int = random.randint(0, len(word)-1)
    return word[int]
74
Q
Use input() to ask the user if they want to start the movie.
If they answer anything other than "n" or "N", print "Enjoy the show!". Otherwise, call sys.exit(). You'll need to import the sys library.
A

import sys

answer = input(‘Do you want to start a movie?’).lower()

if answer != ‘n’:
print(“Enjoy the show”)
else:
sys.exit()

75
Q

Make a while loop that runs until start is falsey.

Inside the loop, use random.randint(1, 99) to get a random number between 1 and 99.
If that random number is even (use even_odd to find out), print “{} is even”, putting the random number in the hole. Otherwise, print “{} is odd”, again using the random number.
Finally, decrement start by 1.
I know it’s a lot, but I know you can do it!

A

import random

start = 5
def even_odd(num):
    # If % 2 is 0, the number is even.
    # Since 0 is falsey, we have to invert it with not.
    return not num % 2
76
Q

The _________ keyword makes a function send data back to wherever the function was called.

A

return

77
Q

If I have the string “apple” and I want to get the “e” using a negative index, starting from the end, what would the index be?

A

-1

78
Q

Finish this so the return happens if the try block doesn’t have any exceptions:

try:
    count = int(input("Give me a number: "))
except ValueError:
    count = 0
\_\_\_\_\_\_\_\_\_ :
    return count * 15
A

Else

79
Q

Which kind of loop runs a set number of times?

A

For

80
Q

Blocks start with a colon but what groups all of the lines of a particular block together?

A

Indentation

81
Q

The symbol for “less than or equal to” is

A

<=

82
Q

TF: Variable names can be any combination of numbers, letters, and underscores but cannot start with a number. They also cannot contain symbols, spaces, or hyphens.

A

True

83
Q

The keyword for checking membership (checking to see if one thing belongs to another thing) is ________

A

In