udacity python Flashcards

(32 cards)

1
Q

Print Statements

A

print () - built-in function that displays input values as text in the output

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

Arithmetic Operators

A

Arithmetic operators

+ Addition
- Subtraction
* Multiplication
/ Division
% Mod (the remainder after dividing)
** Exponentiation (note that ^ does not do this operation, as you might have seen in other languages)
// Divides and rounds down to the nearest integer

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

The usual order of mathematical operations holds in Python, often referred to as

A

PEMDAS: Parentheses, Exponents, Multiplication/Division, Addition/Subtraction.

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

NOT THIS

my height = 58
MYLONG = 40
MyLat = 105

A

Although the last two of these would work in Python, they are not pythonic ways to name variables.

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

Assignment Operators

A

Symbol Example Equivalent
= x = 2 x = 2
+= x += 2 x = x + 2
-= x -= 2 x = x - 2

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

is this true : print(.1 + .1 + .1 == .3)

A

False Because the float, or approximation, for 0.1 is actually slightly more than 0.1, when we add several of them together we can see the difference between the mathematically correct answer and the one that Python creates.

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

You should limit each line of code to

A

Good
print(4 + 5)

Bad
print( 4 + 5)

You should limit each line of code to 80 characters, though 99 is okay for certain use cases.

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

What happens if you divide by zero in Python?

A

ZeroDivisionError: division by zero

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

there are two types of errors to look out for

Exceptions
Syntax

A

An Exception is a problem that occurs when the code is running, but a ‘Syntax Error’ is a problem detected when Python checks the code before it runs it.

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

The bool data type holds one of the values

A

True or False, which are often encoded as 1 or 0, respectively.

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

Comparison Operators

A

Symbol Use Case Bool Operation
5 < 3 False Less Than
5 > 3 True Greater Than
3 <= 3 True Less Than or Equal To
3 >= 5 False Greater Than or Equal To
3 == 5 False Equal To
3 != 5 True Not Equal To

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

there are three logical operators you need to be familiar with:

A

Logical Use Bool Operation
5 < 3 and 5 == 5 False and - Evaluates if all provided statements are True
5 < 3 or 5 == 5 True or - Evaluates if at least one of many statements is True
not 5 < 3 True not - Flips the Bool Value

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

Strings

A

You can define a string with either double quotes “ or single quotes ‘. If the string you are creating actually has one of these two values in it, then you need to be careful to ensure your code doesn’t give an error.

> > > my_string = ‘this is a string!’
my_string2 = “this is also a string!!!”
You can also include a \ in your string to be able to include one of these quotes:

> > > this_string = ‘Simon's skateboard is in the garage.’
print(this_string)
Simon’s skateboard is in the garage.
If we don’t use this, notice we get the following error:

> > > this_string = ‘Simon’s skateboard is in the garage.’
File “<ipython-input-20-e80562c2a290>", line 1
this_string = 'Simon's skateboard is in the garage.'
^
SyntaxError: invalid syntax
When you start your string with a single quote ' then it will end at the next single quote ' that does not have the \ escape character in front of it. You can add any number of double quotes in a string starting with a single quote; they will be displayed as characters. It works the other way too.</ipython-input-20-e80562c2a290>

single_quote_string = ‘“This is a quote itself”’
double_quote_string = “Simon’s skateboard is in the garage.”
print(single_quote_string)
print(double_quote_string)
“This is a quote itself”
Simon’s skateboard is in the garage.

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

. There are a number of other operations you can use with strings as well.

A

> > > first_word = ‘Hello’
second_word = ‘There’
print(first_word + second_word)

HelloThere

> > > print(first_word + ‘ ‘ + second_word)

Hello There

> > > print(first_word * 5)

HelloHelloHelloHelloHello

> > > print(len(first_word))

5

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

The len() function

A

len() is a built-in Python function that returns the length of an object, like a string. The length of a string is the number of characters in the string. This will always be an integer.

There is an example above, but here’s another one:

print(len(“ababa”) / len(“ab”))
2.5
You know what the data types are for len(“ababa”) and len(“ab”). Notice the data type of their resulting quotient here.

The data type is float, as it includes a value after the decimal separator.

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

What does the len function return when we give it the integer 835 instead of a string?

A

The error message generated reads: TypeError: object of type ‘int’ has no len(), which alludes to the fact that len only works on a “sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set),”

17
Q

What type does this object have? len(“my_string”)

A

This was a bit trickier. You can tell that “my_string” is itself a string because of the quotation marks. The length of a string is an integer - it is the count of the number of elements in the string.

18
Q

What type does this object have? “hippo” *12

A

This is a string. If you weren’t sure, look at the output of evaluating the expression:

> > > print(“hippo”*12)
hippohippohippohippohippohippohippohippohippohippohippohippo
Multiplying a string by an integer gives a new string made up of that many copies of the original string - and the type is string.

19
Q

functions

A

notice they use parentheses, and accept one or more arguments.
len(“this”)
type(12)
print(“Hello world”)

20
Q

A method in Python

A

behaves similarly to a function. Methods actually are functions that are called using dot notation. For example, lower() is a string method that can be used like this, on a string called “sample string”: sample_string.lower().

Methods are specific to the data type for a particular variable. So there are some built-in methods that are available for all strings, different methods that are available for all integers, etc.

21
Q

An important string method: format()

A

Example 1 python print(“Mohammed has {} balloons”.format(27))

Example 1 Output bash Mohammed has 27 balloons

Example 2 python animal = “dog” action = “bite” print(“Does your {} {}?”.format(animal, action))

Example 2 Output py Does your dog bite?

Example 3 python maria_string = “Maria loves {} and {}” print(maria_string.format(“math”, “statistics”))

Example 3 Output bash Maria loves math and statistics

Notice how in each example, the number of pairs of curly braces {} you use inside the string is the same as the number of replacements you want to make using the values inside format().

22
Q

F-String Formatting

A

F-string, or “Formatted String Literals” is a method of string formatting introduced in Python 3.6. It optimizes and simplifies the process of including variables within a string.

Unlike the traditional methods (as shown above) where you need to use placeholders like %s and %d or the format() function, F-strings provide a concise and convenient way to embed expressions inside string literals, using curly brackets {}. The expressions will be replaced with their values when the string is evaluated.

Here are a couple of examples:

Example 1 - Using a Single Variable

name = “John”
print(f”Hello, {name}”)
Example 1 Output bash Hello, John

Example 2 - Using Expressions within the f-string You can use complex expressions within the {}. Python will evaluate the expressions and replace them with their results.

a = 5
b = 3
print(f”The sum of {a} and {b} is {a+b}”)
Example 2 Output py The sum of 5 and 3 is 8

23
Q

What happens when you call a string method like islower() on a float object? For example, 13.37.islower().

A

an error occurs. The islower() method is an attribute of string methods, but not floats. Different types of object have methods specific to their type. For example, floats have the is_integer() method which strings don’t have.

24
Q

Another important string method: split()

A

This function or method returns a data container called a list that contains the words from the input string

The split method has two arguments (sep and maxsplit). The sep argument stands for “separator”. It can be used to identify how the string should be split up (e.g., whitespace characters like space, tab, return, newline; specific punctuation (e.g., comma, dashes)). If the sep argument is not provided, the default separator is whitespace.

True to its name, the maxsplit argument provides the maximum number of splits. The argument gives maxsplit + 1 number of elements in the new list, with the remaining string being returned as the last element in the list. You can read more about these methods in the Python documentation too.

The syntax for the split method is: string.split(sep, maxsplit)

Here are some examples for the .split() method.

A basic split method
new_str = “The cow jumped over the moon.”
new_str.split()
Output is:

[‘The’, ‘cow’, ‘jumped’, ‘over’, ‘the’, ‘moon.’]
The separator is space, and the maxsplit argument is set to 3
new_str.split(‘ ‘, 3)
Output is:

[‘The’, ‘cow’, ‘jumped’, ‘over the moon.’]
Using ‘.’ or period as a separator
new_str.split(‘.’)
Output is:

[‘The cow jumped over the moon’, ‘’]
Using no separators but having a maxsplit argument of 3
new_str.split(None, 3)
Output is:

[‘The’, ‘cow’, ‘jumped’, ‘over the moon.’]

25
What is the length of the string variable verse?
print(len(verse))
26
What is the index of the first occurrence of the word 'and' in verse?
print(verse.find("and"))
27
What is the index of the last occurrence of the word 'you' in verse?
word = "you" index = verse.rfind(word)
28
What is the count of occurrences of the word 'you' in verse?
word = "you" count = verse.count(word)
29
ome tips on successful debugging
Understand common error messages you might receive and what to do about them. Search for your error message, using the Web community. Use print statements.
30
Understanding Common Error Messages
There are many different error messages that you can receive in Python, and learning how to interpret what they're telling you can be very helpful. Here are some common ones for starters: "ZeroDivisionError: division by zero." This is an error message that you saw earlier in this lesson. What did this error message indicate to us? You can look back in the Quiz: Arithmetic Operators section to review it if needed. "SyntaxError: unexpected EOF while parsing" Take a look at the two lines of code below. Executing these lines produces this syntax error message - do you see why? greeting = "hello" print(greeting.upper This message is often produced when you have accidentally left out something, like a parenthesis. The message is saying it has unexpectedly reached the end of file ("EOF") and it still didn't find that right parenthesis. This can easily happen with code syntax involving pairs, like beginning and ending quotes also. "TypeError: len() takes exactly one argument (0 given)" This kind of message could be given for many functions, like len in this case, if I accidentally do not include the required number of arguments when I'm calling a function, as below. This message tells me how many arguments the function requires (one in this case), compared with how many I gave it (0). I meant to use len(chars) to count the number of characters in this long word, but I forgot the argument. chars = "supercalifragilisticexpialidocious" len()
31
Search for Your Error Message
Software developers like to share their problems and solutions with each other on the web, so using Google search, or searching in StackOverflow, or searching in Udacity's Knowledge forum are all good ways to get ideas on how to address a particular error message you're getting. Copy and paste the error message into your web browser search tab, or in Knowledge, and see what others suggest about what might be causing it. You can copy and paste the whole error message, with or without quotes around it. Or you can search using just key words from the error message or situation you're facing, along with some other helpful words that describe your context, like Python and Mac.
32