\
to explicitly tell Python this is a continuation of a statement.
E.g., a = '1' \
+ '2' \
+ '3' \
- '4'
Glossary:
Code block: is a grouping of two or more statements. In many cases, it serves as a way to define logical level and limit the scope of variables and functions. It makes more sense when we talk about the scope of variables.
a = "Hello World!"
print(a)
Variable is a reserved memory location to store values which we will refer to later in the code. Python is dynamically-typed language, which means you do not need to claim or predefine the data type of a variable.
The input can be from an end user or an external file (e.g., a txt file). Let's read something from users' input.
a = input("please enter a number:")
print("You just entered {}, correct?".format(a))# this is called string formatting
Syntax: # is a symbol indicating the following phrases are just comments that have nothing to do with code. You can always use #
to annotate your code.
Note: In most cases, we do not use the built-in input or file-reading functions from Python. Instead, we turn to Pandas or other packages. We will learn to use Pandas to read csv files in the third session on Nov. 6.
print("Hello Python!")
a = 5
a
a = "I love python"
a
print(a)
Note: If the last line of a cell is a variable, Jupyter Notebook automatically prints it out using a Ipython output function--display. This is a Ipython trick, which you cannot observe while working with a regular Python IDE.
a = 2
a
b = '2'
b
Question: Does a '2' (enclosed by double quotes) equal b 2?
a = 1
type(a) # type() is a built-in function of Python, which checks the type of the value/varialbe passed in
type(-1) #also an integer
a = 1.3 # a decimal number
type(a)
"Brown University" # a string wrapped by double quotes
'Brown University' # a string wrapped by single quotes.
Note: In most cases, single quotes and double quotes are interchangeable. What if a string happen to have quotation marks inside itself? The rules are:
"I've done it!"
' "this is quoted sentence!" '
""" I have a single quote ' here, also a double quote here " Haha! """
a = """ This sentence has a single quote ' here and also a double quote " here! """
print(a)
string formatting: Let's look at a very powerful method (we will talk about what are methods and their difference from functions), format(), which allows you to do string substitutions. This method allow you to concatenate elements through positional formatting.
x = 'language'
b = "Python is a {}".format(x)
b
What if I want to replace more than 1 elements?
a = 'Python'
b = 'language'
sentence = '{} is a {}'.format(a,b)
sentence
Or you could put indexes inside the curly brackets to explicitly get the values of positional arguments.
a = 'Python'
b = 'language'
sentence = "{1} is a {0}".format(b,a)
sentence
f string: a new syntax since Python 3.6 for string formatting. The code within the {}
are evaluated.
a = 'Rhode Island'
x = f'Where is {a}'
x
a = 4
b = 5
x = f"4+5={a+b}"
x
Boolean Data Type
a = True # a is boolean varialbe. True is a reserved word to represent the logic true value.
print(a)
b = False # False is a reserved word to represent the logic false value.
b
List
[2,4,'t',True] # This is a list. As you can tell, the elements in a list do not need to be of the same type.
(2, 3,True) # This is a tuple.
{'First-name:':'Bill',"Last-name":"Gates"} # this is a dictionary, 'first-name' and 'last-names' are called keys.
{2,3,4} # this is a set
Yes, you can convert a variable from one type to another compatible type. E.g., you have a string variable '4'
. You might want to use its corresponding numeric value 4 to do some arithmetic operations.
a = "4"
b = a + 8
a = "4"
b = int(a)
print (b+8)
a = 4.3
b = int(a)
b
a = 4
b = str(4)
b
a = 4
b = float(4)
b
a = "time"
b = int(a)
a = 1
bool(a)
a = 2
bool(a)
a = 0
bool(a)
a = 'time'
bool(a)
a = ''
bool(a)
Operators are constructs to manipulate the values of operands. Look at this expression, 4 + 5 = 9. 4 and 5 are called operands, and + is called operators. It is noted that the same operator might lead to a different operation when it is applied to different data types.
Operation | Operator | Example |
---|---|---|
Addition | + | a + b |
Subtraction | - | a - b |
Division | / | a / b |
Floored Division | // | a // b |
Multiplication | * | a * b |
Remainder | % | a % b |
Exponentiation | ** | a ** b |
Unary negation | - | -a |
4+3
4-3
4/3
4//3
5%3
4**2 #raise 4 to the power 2 = 16
-(-5) # the negation of -5
'Brown' + ' University' #concatenate two strings
Note: What about square root operation, rounding operation and so on? These operations can be found in math package.
import math
math.sqrt(x)
math.floor(x)
math.ceil(x)
compare values of operands and return either True or False.
Operation | Operator | Example |
---|---|---|
Equal to | == | 4==3 |
Not equal to | != | 3!=4 |
Less than | < | 3 < 4 |
Larger than | > | 4 > 4 |
Less than or equal to | <= | 3 <=4 |
Larger than or equal to | >= | 4 >=3 |
4==3
3!=4
3<4
4>4
3<=4
4>=3
"Tom" == "Jerry"
4 == '4'
1 == True
Assigns the value on the right end to its left variable.
Operation | Operator | Example | Explanation |
---|---|---|---|
Assignment | = | x =5 | x = 5 |
Addition assignment | += | x += y | x = x+y |
Subtraction assignment | -= | x -= y | x = x-y |
Multiplication assignment | *= | x *= y | x = x*y |
Division assignment | /= | x /= y | x = x/y |
Remainder assignment | %= | x %= y | x = x%y |
x = 5 # assing the value of 5 to x.
x
y = 4
y
x += y # x = x + y; we add y to x and save the result to an intermediate memory and then assign it back to X.
x
x = 5
y = 4
x -= y # x = x-y = 5-4 = 1
x
x = 5
y = 4
x *= y # x = x*y = 5*4 = 20
x
x = 5
y = 4
x /= y # x = x/y = 5/4=1.25
x
x = 5
y = 4
x %= y # x = x%y = 5%4 = 1
x
There are three logical operators in Python: and, or, not. They are designed to be applied to boolean values or boolean-compatible values. Mainly used in if-else statement (introduced shortly)
True and False
(5 > 4) and (-1 > 0)
not True
not (4 < 6)
not '2' # '2' is evaluted to be True, so not True leads to a False value.
not 0 # 0 is evaluated to be False, not False leads to a True value.
Checks if an element is part of a collection (e.g., list, string). Returns True if the collection contains that element, otherwise False.
5 in [3,4,5] # list
1 in (2,3,4) #tuple
'B' in 'Brown University'
'rown' in "Brown University"
'T' not in "PSTC"
In the previous tutorials, we've learned how to use Python to do simple arithmetic calculations. In real world, a code script can become way more complicated than that.
This section introduces you three flow-control statements in Python
The if statement is used to check whether a condition is met. If the condition is True, the code block under the if statement will be executed. Otherwise the code block under the else statement is executed. It is noted that the else statement is optional.
The syntax is:
if condition:
do something
if condition:
do something
else:
do something-else
if condition:
do something
elif condition2:
do something else
else:
balabala
a = 'p'
b = 'pstc'
if a in b: # here a in b is logical expression
print("a is part of b!") # pay attention to the intentation here.
a = 4
b = 5
if a == b:
print("a equals b!")
else:
print('a does not equal b!')
a = 4
b = 4
if a > b: #this condition fails
print('a > b')
elif a < b: # this confition fails
print('a < b')
else:
print('Well, then a must equal b!')
The for...in
statement is a looping statement, which iterates over an iterable (e.g., list, str,tuple,dict and file objects).
syntax:
for item in iterable:
do something
Note that the item
variable is a "temporary" variable which is updated on-the-fly to refer to the element during each iteration.
a = [1,2,3,4,5] # list is an iterable.
for item in a:
print(f"the current value is {item}")
Nested for-loop: where you can have all the possible combinations Syntax:
for item_1 in iterable_1:
for item_2 in iterable_2:
do something
cities = ['Providence','Pawtucket','Barrington']
supermarkets = ['Wholefoods', 'Walmart']
for city in cities:
for supermarket in supermarkets:
print(f'{city}-{supermarket}')
The while
statement allows you to repeat an action until the condition specified fails.
The syntax:
while condition:
do something
also change the condition
Note that remember to change the variable(s) involved in the condition during the looping. If not, the code will never stops until your computer memory runs out.
a = 5
while a<10:
print(a)
a += 1 #still remember the addition assignment? a = a+1
print("moving to the next iteration")
Assuming we have a variable with a long list of names. We want to test whether 'Tom' is in this list.
%%time
names_list =['Tom']+['Jerry']*100000 # This is a list of names containing one Tom(the first element) and 100,000 of 'Jerry'
for name in names_list:
if name == 'Tom':
print("I found Tom!")
%%time is a Jupyter magic command that records the running time of a cell.
What is the problem with the code above? This for-loop runs over all the elements in the name list. However, we expected the script to stop as soon as it found "Tom". The rest of searching is a waste of time and computing resources. Let's introduce the new keyword "break" to terminate (jump out of) a loop.
%%time
names_list =['Tom']+['Jerry']*100000
for name in names_list:
if name == 'Tom':
print("I found Tom!")
break
The code with a break statement is 13 times faster than the one without a break on my laptop
Skips over all the lines below the continue keyword within a loop and move directly to the next iteration. It is very helpful when you have multiple conditions inside a loop.
names_list =['Tom']+['Jerry']*100000
for name in names_list:
if name == 'Tom':
continue
print("I found Tom!")
Why is there no output? During a loop, if the script sees continue keyword, it automatically skips over the rest of code and move forward to the next element.