Skip to the content.

Back to Tutorial Index
Updated 9-25-2020

Python Tutorial 2:

Strings, Lists, Loops, and Conditionals

More fun with strings

Strings can be:

Lists

Lists are awesome.

In Python:

Lists can be:

Conditional statements

Conditional statements are very powerful. The most commonly used conditional statement is the ‘if’ statement and its children, the ‘elif’ and ‘else’ statements. Conditional statements use operators (see table below).

Python Operators:

Operator Description
x == y x is equal to y
x != y x is not equal to y
x > y x is greater than y
x < y x is less than y
x >= y x is greater than or equal to y
x <= y x is less than or equal to y
x in y x is a part of y

The basic format for conditional statments is if conditional_stmnt: do something. Some examples:

Loops

Loops are awesome. With conditional statements, they are the backbone of programming

Things to remember when working with loops:

The basic syntax for a loop is for local_variable in iterable: do something

Examples:

#Creating a loop:
sl = ["a", "wonderful", "list", "this", "is"]

for x in sl: #note that 'x' is a local variable and is completely arbitrary
	print(x) #we can call the local variable
#note that the "do something" statement (i.e., print(x)) is indented by a tab (or 4 spaces)
> a
> wonderful
> list
> this
> is
#if statements in loops
for x in sl:
	if "t" in x:
			print(x)
		else:
			continue #continue tells the loop to go to the next item
> list
> this

Exercises

1. Assign the string “This is an awesome sample sentence” to the variable a

2. Split the string into a list of words and assign it to variable b

3. Write a loop that prints each item in b

4. Define a new empty list and assign it to variable c

5. Write a loop that adds each item in b to c if the last letter in the item is “e”