udacity python Flashcards
(32 cards)
Print Statements
print () - built-in function that displays input values as text in the output
Arithmetic Operators
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
The usual order of mathematical operations holds in Python, often referred to as
PEMDAS: Parentheses, Exponents, Multiplication/Division, Addition/Subtraction.
NOT THIS
my height = 58
MYLONG = 40
MyLat = 105
Although the last two of these would work in Python, they are not pythonic ways to name variables.
Assignment Operators
Symbol Example Equivalent
= x = 2 x = 2
+= x += 2 x = x + 2
-= x -= 2 x = x - 2
is this true : print(.1 + .1 + .1 == .3)
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.
You should limit each line of code to
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.
What happens if you divide by zero in Python?
ZeroDivisionError: division by zero
there are two types of errors to look out for
Exceptions
Syntax
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.
The bool data type holds one of the values
True or False, which are often encoded as 1 or 0, respectively.
Comparison Operators
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
there are three logical operators you need to be familiar with:
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
Strings
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.
. There are a number of other operations you can use with strings as well.
> > > 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
The len() function
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.
What does the len function return when we give it the integer 835 instead of a string?
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),”
What type does this object have? len(“my_string”)
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.
What type does this object have? “hippo” *12
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.
functions
notice they use parentheses, and accept one or more arguments.
len(“this”)
type(12)
print(“Hello world”)
A method in Python
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.
An important string method: format()
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().
F-String Formatting
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
What happens when you call a string method like islower() on a float object? For example, 13.37.islower().
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.
Another important string method: split()
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.’]