Python Basics Flashcards
Set a variable to your name
var = “Aman”
Print “Hello, Treehouse”
print(“Hello, Treehouse”)
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”)
c. def my_function() :
print(“Hello”)
How would you name a variable that has two words like hello there?
Hello_there
What is print()?
Function
TF: Syntax is what we call the rules for writing in a programming language.
True
How many equal signs do you need to create a variable?
One
variable = value
TF: Using help() is cheating
False
To look up the documentation about the str class’s upper method, I’d use help()
help(str.upper)
TF: The Python shell is a great place to write the final version of your code.
False
To leave the Python shell, run the ____ () function.
exit()
I have a script named hello_treehouse.py. How would I run that?
python hello_treehouse.py
TF: Before we can run a Python script, we have to run a separate, distinct compilation step.
False
TF: When we’re writing a Python script, we have to include»_space;> in front of every line.
False
What keyword is used to delete a variable?
Del
What are whole numbers in Python called?
Integers or ints
What are numbers with decimals called?
Floats
What are the rules regarding adding, subtracting, multiplying, and dividing when using ints and floats?
When you add, subtract or multiply, you always get ints, unless you are using a float.
When you divide, you always get a float.
What happens when you divide by 0?
You receive a Zero Division Error.
What do you use when you need to convert a value to an integer or a float?
int()
float()
Can you use += or -= in python?
Yes
What are the 4 ways to make strings?
Single quotes, double quotes, triple quotes, str function
Can you multiply a string and a number?
Yes
How would use .format to add a number to a string? “There are {} people here”
Message = “There are {} people here”.format(6)
What’s unique about python lists?
They are kind of like arrays but can hold different types in them like strings, numbers, lists.
Lists are mutable
What are 2 great methods to add to lists?
append() → only for one item
my_list.append(6)
extend() → for more than one item
my_list.extend([4, 5, 6])
What method do you use for removing something from a list?
remove() → only for one item
my_list.remove(7)
Why can’t you run list(5)?
Because it is one item. A list must be iterable.
What is the purpose of the split method?
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”].
What is the purpose of the join method?
.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)
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.
sundaes = available.split(‘;’)
menu = “Our available flavors are: {}.”
menu = “Our available flavors are: {}.”.format(‘, ‘.join(sundaes))
What are the index rules?
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.
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?
2 Ways to remove it
alpha_list.remove(‘c’)
del alpha_list[2]
What are the numerical values for true and false?
False = 0 True = 1
What are the boolean values for true things vs false things?
Full things are true
Empty things are false
What are the symbols for equal to and not equal to?
==
!=
What are the symbols for lesser, greater or equal etc.?
> <
<=
=
What does ‘is’ do?
It checks whether or not the two values are in the same place in memory.
If I want to make sure that age is exactly equal to 25, which comparator should I use?
==
Which comparison means “not equal to”?
!=
Give a comparison that would be True for the following: 5 2
!=
All comparators, things like >=,
False
TF: <= means “greater than or equal to”.
False
How do you write an if statement?
If a < b:
print(“ok”)
How do you write else if?
elif a == b:
print(ok)
Make an if condition that sets admitted to True if age is 13 or more.
Admitted = None
if age >= 13:
admitted = True
Add an else statement that turn admitted into false if you are younger than 13.
else:
admitted = False
What does in check for?
Containment or inclusion
Checks whether a value is in a value or list
What does not in check for?
Checks whether a value is not in a value or list
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.
if time in store_hours:
store_open = True
else:
store_open = False
What do for loops do?
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)
What do while loops do?
while loops, on the other hand, run until their condition, like an if has, turns False. Start = 10 While start: print(start) Start -= 1
What does break do?
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
What does ‘continue’ do?
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.
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”.
for hello in hellos:
print(“{} world”.format(hello))
What does the input function do?
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? ”))
I need age to be an integer. What do I need to add?
age = ___________ (input(“What is your age? “))
Int
When writing a function? What does the keyword def do?
Def stands for define. Then you put the name of the function.
In a function, what are the contents inside the parentheses called? hows_the_parrot()
Arguments
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.
Def printer(count): print(“Hi” * count)
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.
def product(x, y): return(x * y)
What is the purpose of try and except?
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))
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.
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))
How do you leave comments?
#
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!
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)
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
def loopy(items): # Code goes here for item in items: if item[0] == 'a': continue else: print(item)
How do you import libraries?
Use import keyword.
import random
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….
def even_odd(number): if number % 2 == 0: return True else: return False
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.
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
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.
def squared(num): try: return int(num) * int(num) except ValueError: return num * len(num)
What do the keywords and & or do?
and - lets us define two conditions that must be True
or - lets us define two conditions, one of which must be True
What does str.isalpha() do?
Returns whether or not all of the characters in a string are alphabetical
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.
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]
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.
import sys
answer = input(‘Do you want to start a movie?’).lower()
if answer != ‘n’:
print(“Enjoy the show”)
else:
sys.exit()
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!
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
The _________ keyword makes a function send data back to wherever the function was called.
return
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?
-1
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
Else
Which kind of loop runs a set number of times?
For
Blocks start with a colon but what groups all of the lines of a particular block together?
Indentation
The symbol for “less than or equal to” is
<=
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.
True
The keyword for checking membership (checking to see if one thing belongs to another thing) is ________
In