Notes: view the previous lesson if you still need to install Python through the Miniconda package.
You should create a folder where you will save all your Python programs for this class.
First we will learn how to use Python to work with numbers, strings, and variables. For these exercises, you can enter code in the console (usually on the lower right corner of Spyder) or you can enter several lines of code into the editor where you can run several lines of code at the same time.
For further information review: python.org Lesson 3
Working with variables:
1 equal sign assigns a value. Thus, in the code below, we are assigning the variable x the value of 18.
x=18
test this by entering the following code in your Python console:
x=18
print(x)
type(x)
x+12
x+'abc'
Run the following code. Can you figure out the difference between the following operands (*, **, /, //, %)?
18+4
18*4
18**4
18/4
18//4
18%4
As x is an integer (type ‘int’), note how you can add other integers to it (or perform any mathematical calculation). However, you can not add it to a string (type ‘str’). Now try entering this in your console.
y='fire'
z='fighter'
y+13
y+z
a=y+z
print(a)
len(a)
With strings you can also retrieve substrings. Can you figure out what the following lines of code are doing?
sent=" This is a particularly normal sentence.\n"
sent[0]
sent[0:5]
sent[10:17]
sent[:3]
sent[3:]
sent[-3:]
sent[-6:-3]
Let’s strip out the excess whitespace at the start and end of this sentence (‘’ indicates a line break).
sent.strip()
However, that just showed us the result. To save the new sentence, you need to assign it to a variable:
sent2=sent.strip()
print(sent)
print(sent2)
Now, let us split the sentence into words. We can use the split() function for that.
words=sent2.split()
print(words)
Now, let us retrieve only the first four words:
importantWords=words[0:4]
print(importantWords)
Store the following paragraph in a variable (you can copy and paste it in Python). Alternatively, you may copy a different paragraph from a text of your own choosing:
"Latin America is at peace. Civil wars have ended. Insurgencies have been pushed back. Old border disputes have been resolved. In Colombia, great sacrifices by citizens and security forces have restored a level of security not seen in decades."
Now, write code that extracts only the first 20 characters of the paragraph.
Add a new sentence to the end of this new string.
If, else if (‘elif’ in Python), and else statements allow you to apply particular actions only under specific circumstances that you specify. For example, you can write a program that applies a tax to a product only if it costs more than $20.
For loops allows you to run a program repeatedly over a list or series of data.
These if statements and for loops are called control flows. For documentation on control flows, see: python.org Lesson 4
Read the program below. It takes in an integer and then returns a response given the value of the integer. Notice the use of double equal signs (“==”) in if or else if statements.
x = int(input(“Please enter an integer:”))
if x < 0:
x = 0 ##assigns 0 to variable x
print(‘Negative changed to zero’)
elif x == 0: ## checks if x=0
print(‘Zero’)
elif x == 1:
print(‘Single’)
else:
print(‘More’)
Now try running the program:
Please enter an integer: 42
More
Write a similar program as the one above, but this time identifying all numbers that are odd.
If you want to work with data in Python, you need to learn the different structures Python provides for the storing - and, therefore, analysis - of data. These include:
To learn more about data structures, see Python.org
create the following variables
x="Peru"
y=1532
check types
type(x)
type(y)
combine “Peru” and “1532” into one string:
##try
y+100
x+y ##should receive an error
# convert y to a string
y=str(y)
x+y
For more on Python lists, click here
create a blank list
l=[]
create a populated list:
k=[5,3,22,17,7]
iterate over list:
sum=0
for i in k:
sum+=i
print(sum)
sort list
sorted(k)
sorted(-k)
k=sorted(k)
get length of list
len(k)
add one item to a list
k.append(16)
k=sorted(k)
create new list. Combine lists
j=[77,83,4,62,41,77,77,33,6]
l=j+k
l2=j.extend(k)
if l1==l2:
print(True)
reverse order of list
l=l.reverse()
Complete the following tasks with Python lists. Write this code as a program in the editor. After each task, print the results. An example for numbers one and two are provided.
create a list of your top 5 favorite tv shows (or you can do movies, books, video games, etc.)
tvfavs=['Mork and Mindy','Laverne and Shirley','Murder, She Wrote','The Fresh Prince of Bel-Air','Miami Vice']
print(tvfavs)
Now print the list, one item at a time:
for fav in tvfavs:
print(fav) ##note you need to indent within a for loop
add a 6th tv show to the end of your list. Review the examples above and the link here if you forget how to do any of this.
Rethink your list. Replace one of the items with a show that you may prefer.
Add 4 more shows you enjoyed as a child.
sort the list alphabetically. Use Python’s sorted() function.
create a copy of the list
for the copy list:
remove the last show
remove the third show in the list
Extra Credit: Write a for loop that creates a new list, but this time truncating each show’s name to a maximum of 10 characters.