In [1]:
# create a new string to work with
sentence = 'This is CP255!'
In [2]:
sentence
Out[2]:
In [3]:
# what is the length of the string?
len(sentence)
Out[3]:
In [4]:
# extract a substring
sentence[3:9]
Out[4]:
In [5]:
# use the strip method to remove characters from the beginning and end of a string
sentence.strip('!')
Out[5]:
In [6]:
# our string hasn't changed, because we didn't assign a new value to it
sentence
Out[6]:
In [7]:
# create a new string to contain the stripped version of our string
new_sentence = sentence.strip('!')
In [8]:
# the variable new_sentence captured the result of the strip() method
new_sentence
Out[8]:
In [9]:
# you can create a string variable and pass it into the strip method as an argument
to_strip = '255!'
sentence.strip(to_strip)
Out[9]:
In [10]:
# create a for loop to iterate through each character in the string
for character in sentence:
print(character)
In [11]:
# use split() to break a string into tokens
sentence.split()
Out[11]:
In [12]:
# default argument is ' ', but you can pass other substrings to split on
sentence.split('i')
Out[12]:
In [13]:
sentence
Out[13]:
In [14]:
# use the find method to return the index of the first instance of some substring within another string
sentence.find('C')
Out[14]:
In [15]:
to_find = 'is'
sentence.find(to_find)
Out[15]:
In [16]:
# create a new list by splitting the string
list_of_words = sentence.split()
type(list_of_words)
Out[16]:
In [17]:
# the isinstance function tells you if some variable is an instance of some data type
isinstance(list_of_words, list)
Out[17]:
Some functions are already programmed and stored in pre-built classes that are available to us if we just import them. This is the essence of object oriented programming. We can use someone else's classes and the functions within them, which we refer to as methods when they are embedded inside a class.
In [18]:
# import Python's string module so we have access to its existing functions
# see all the string methods here: https://docs.python.org/2/library/stdtypes.html#string-methods
import string
In [19]:
# use the string join method to turn a list into a string
' '.join(list_of_words)
Out[19]:
A boolean expression is one that can be evaluated by Python and interpreted as being True or False. You can think of it as making an assertion, and having Python tell you if you are right or not in making that assertion. It does not pass moral judgments, but will tell you if your assertion is not valid. The == operator is an assertion that what is on the left of it is equivalent to what is on its right. The >= operator is greater than or equal to, and != asserts that two objects are not the same. Don't be confused by the similarity of '=' and '==': one is an assignment of a value to a variable, and the other is a comparison operator. Some examples of boolean expressions:
In [20]:
# use == to evaluate if both sides are equivalent
2 + 2 == 4
Out[20]:
In [21]:
# you can also compare variables
a = 1
b = 1
a == b
Out[21]:
In [22]:
# > and < are greater than and less than
a > 10
Out[22]:
In [23]:
# >= and <= are greater than or equal to, and less than or equal to
a >= 1
Out[23]:
In [24]:
# != means does not equal
a != b
Out[24]:
In [25]:
# use and to return True if multiple conditions are satisfied
c = 5
c > 2 and c < 5
Out[25]:
In [26]:
# use or to return True if either condition is satisfied
c > 2 or c < 5
Out[26]:
In [27]:
c == 5
Out[27]:
In [28]:
# use not to negate some condition
not (c == 5)
Out[28]:
In [29]:
d = True
not d
Out[29]:
The modulus operator (%) tests whether or not we can divide two integers evenly. It gives the remainder from the division. That is, what is left over after dividing the numerator by the largest multiple of the denominator? For example, 10%5 is 0 since 5 goes into 10 twice, with nothing left over. 10%3 is 1, since 3 goes into 10 3 times, with one left over.
In [30]:
10 % 5
Out[30]:
In [31]:
10 % 3
Out[31]:
In [32]:
# use an if statement to execute indented code only if some condition is true
x = 9
if x < 10:
print(str(x) + ' is less than 10')
In [33]:
# you can chain conditions together with and/or
# i like to group conditions with parentheses for readibility
x = 3.5
if (x >= 3) and (x <= 6):
print('x is between 3 and 6')
In [34]:
# if the first if statement evaluates to false, elif executes a code block if its condition is true
# else executes a code block if no preceding if or elif evaluated to true
x = 10
if x < 10:
print('x is less than 10')
elif x == 10:
print('x equals 10')
else:
print('x is greater than 10')
In [35]:
# encapsulation turns a handful of statements into a reusable function
def my_function(value):
if value < 10:
print('the value is less than 10')
elif value == 10:
print('the value equals 10')
else:
print('the value is greater than 10')
# now call the function
my_function(5)
In [36]:
# your function can return results that you can use elsewhere in your code
def greater_than(x, y):
if x > y:
return True
else:
return False
In [37]:
print(greater_than(3, 5))
print(greater_than(5, 3))
Write a function that accepts 2 arguments and uses modulus to return True if the first is evenly divisible by the second, and False if not
In [ ]:
In [38]:
# a while loop repeats as long as some condition is True
x = 5
while x > 0:
print(x)
x = x - 1
print('blast off!')
In [39]:
# add the numbers 0 to 10 to a list
my_list = []
x = 0
while x < 10:
my_list.append(x)
x = x + 1
my_list
Out[39]:
In [40]:
# create a list of even numbers
even_numbers = [2, 4, 6, 8, 10]
even_numbers.append(12)
even_numbers
Out[40]:
In [41]:
# iterate through the list, printing each element multiplied by 2
for even_number in even_numbers:
print(even_number * 2)
In [42]:
# print out only the ints in a list
my_list = [3.3, 19.75, 6, 3.3, 8]
for element in my_list:
if isinstance(element, int):
print(element)
In [43]:
# how many times does the value 3.3 appear in my_list?
def count_occurrences(my_list):
#initialize a counter to keep track
count = 0
for element in my_list:
if element == 3.3:
#add one to the counter each time we find the value
count = count + 1
return count
count_occurrences(my_list)
Out[43]:
In [44]:
# the range function returns a list of numbers from 0 up to (but not including) n
range(10)
Out[44]:
In [45]:
# because range goes up to but does not include the ending number, you can add 1 to capture it
n = 10
range(n + 1)
Out[45]:
In [46]:
# range optionally lets you specify a starting number, an ending number, and a step as arguments
numbers = range(2, 12, 2)
numbers
Out[46]:
In [47]:
# you can do the same thing with variables
start = 2
end = 12
step = 2
range(start, end, step)
Out[47]:
In [48]:
# iterate through the list, printing each element multiplied by 2
for number in numbers:
print(number * 2)
In [49]:
# do the same thing, more concisely
for x in range(2, 12, 2):
print(x * 2)
In [50]:
# list comprehension lets you create a list based on some expression
new_list = [x for x in range(5)]
new_list
Out[50]:
In [51]:
# you can perform operations within a list comprehension
[ x + 1 for x in range(5) ]
Out[51]:
In [52]:
# you can use list comprehension to convert a list of ints to a new list of strings
string_list = [str(x * 2) for x in range(2, 12, 2)]
string_list
Out[52]:
In [ ]: