First of all, comments. In Python, the pound sign (#
) is used for comments in your codes.
# This is a comment.
# Use them to write short notes and descriptions in your code.
If you need to comment multiple lines out, you may be able to do this by using triple quotes ('''
). But this is not recommended, since it treats the expressions inside '''
as a regular multi-line string varible, so the expressions are not ignored by the interpreter in the same way that # commented expression
is.
c = 10
'''
Multi-line comments can be done like this, but not recommended.
a = 10
b = 30
c = a + b
'''
print(c)
10
In Jupyter notebook
environment, the last item in the cell is printed.
1+2 # this won't be printed
3*4 # this will be printed
12
You can use print()
, to print multiple things out.
print(1+2)
print(3*4)
3 12
To supress the output of a cell, add a semicolon.
1+2;
3*4;
Throughout the class, we will mostly work with the following four variable types. We will frequently use the arrays (with numpy
module) to handle vectors and matrices. These four types are the building bits for the arrays.
flag = True # boolean variable
clid = 370 # integer variable
temp = 25.1 # float variable
dept = 'EE' # string variable
You can check which type a specific variable is, by
type(flag), type(clid), type(temp), type(dept)
(bool, int, float, str)
or explicitly print them as follows.
print(flag)
print(clid)
print(temp)
print(dept)
True 370 25.1 EE
In Python, there are different types of operators (special symbols) that operate on different values. Some of the basic operators include:
+
(addition)-
(subtraction)*
(multiplication)/
(division)**
(exponent)=
(assign a value)+=
(add and re-assign; increment)-=
(subtract and re-assign; decrement)*=
(multiply and re-assign)True
or False
)==
(equal to)!=
(not equal to)<
(less than)<=
(less than or equal to)>
(greater than)>=
(greater than or equal to)For integer variables, you will see a couple more complicated division-related operations.
/
(true division)//
(floor division)%
(modulo operation)For example you can say something like
( 2 * clid + 10 ) % 4
2
Integer division (floor division) and float division (true division) are different, so
print(7/2) # true division
print(7//2) # floor division
3.5 3
For floating point numbers, you can say something like
temp_in_f = 1.8 * temp + 32
print(temp_in_f)
77.18
which is pretty intuitive.
You can put j
or J
after a number to make it imaginary, so you can write complex literals easily. More to come when we will talk about python modules, including numpy
or cmath
.
1j*1j
(-1+0j)
a = 3+4j
print (a.real)
print (a.imag)
print (a.conjugate())
print (abs(a))
3.0 4.0 (3-4j) 5.0
Assignment operators including increment/decrement operators can be used just like other programming languages.
num1 = temp_in_f
print(num1)
num1 += 10 # add and reassign
print(num1)
num1 -= 10 # subtract and reassign
print(num1)
num1 *= 2 # multiply and reassign
print(num1)
num1 /= 2 # divide and reassign
print(num1)
77.18 87.18 77.18 154.36 77.18
Now the comparison operators:
num2 = 77
print(num1 == num2) # should be False
print(num1 != num2) # should be True
print(num1 < num2) # should be False
print(num1 >= num2) # should be True
False True False True
This looks a bit awkward but also works.
5 > 3 > 4
False
or,
5 > 3 < 4 == 1 + 3
True
Python implements all of the usual operators for Boolean logic.
t, f = True, False
type(t)
bool
print(t and f) # Logical AND;
print(t or f) # Logical OR;
print(not t) # Logical NOT;
print(t != f) # Logical XOR;
False True False True
The followings also work.
print(t & f) # Logical AND;
print(t | f) # Logical OR;
print(not(t)) # Logical NOT;
False True False
Some similar operations can be intuitively done on string variables.
2*dept
'EEEE'
dept + ' stands for Electronic Engineering'
'EE stands for Electronic Engineering'
However, different types of varaibles can not be added (concatenated).
# classname = dept + clid # attempt to add a string and an integer
You can do what you wanted by using repr()
function that returns a string representation of a number.
classname = dept + repr(clid)
print(classname)
EE370
or, by using f'...string...'
which stands for 'formatted string'.
classid = f'The class ID for Software Lab is {dept}{clid}.'
print(classid)
The class ID for Software Lab is EE370.
These builtin functions for string variables are not interesting, but sometimes can be useful.
classid.capitalize()
'The class id for software lab is ee370.'
classid.upper()
'THE CLASS ID FOR SOFTWARE LAB IS EE370.'
classid.lower()
'the class id for software lab is ee370.'
classid.replace('EE', 'CS')
'The class ID for Software Lab is CS370.'
We will frequently use a specific type of containers called list
, which can be used to handle a list of numbers.
a = [1,3,4,8,2,5,9,7,6] # this is a list
print(a)
[1, 3, 4, 8, 2, 5, 9, 7, 6]
type(a)
list
len(a)
gives you the length (the number of elements) of it
len(a)
9
Be careful. a*2
does not multiply its elements by 2
, but it duplicates and concatenates the list.
a*2
[1, 3, 4, 8, 2, 5, 9, 7, 6, 1, 3, 4, 8, 2, 5, 9, 7, 6]
a+a
[1, 3, 4, 8, 2, 5, 9, 7, 6, 1, 3, 4, 8, 2, 5, 9, 7, 6]
Elements of a
can be accessed by a[...]
.
a
[1, 3, 4, 8, 2, 5, 9, 7, 6]
a[0] # accessing the first element
1
a[-1] # accessing the last element
6
A range of elements in a list can be specified by a[start_index:end_index:step_size]
.
a[1:6:1] # accessing the elements from index 1 up to (but not including) index 6, with step size of 1
[3, 4, 8, 2, 5]
The default value of the step_size
is 1
, so omitting it results in,
a[1:6:]
[3, 4, 8, 2, 5]
or simply,
a[1:6]
[3, 4, 8, 2, 5]
Or with non-default values,
a[1:6:2] # accessing the elements from index 1 up to (but not including) index 6, with steps specified by 2
[3, 8, 5]
Omitting start_index
implies 'from the first element', and omitting end_index
implies 'up to the last element', so omitting every argument will give you the entire list.
a[::]
[1, 3, 4, 8, 2, 5, 9, 7, 6]
a[::3]
[1, 8, 9]
a[2::3]
[4, 5, 6]
Different types can be contained in a single list
container, but we will rarely use it in this class.
b = [1,3,'four',8]
print(b)
[1, 3, 'four', 8]
We can define a list of discrete values on a range. range(numer_from,number_to,step_size)
generates integers from number_from
up to (but not including) number_to
with step size of step_size
, so,
a = range(0,10,1)
list(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The default value of number_from
is 0
, and the default of the step_size
is 1
, so
a = range(10)
list(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Or with non-default values, you will see,
a = range(3,20)
list(a)
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
and
a = range(3,20,2)
list(a)
[3, 5, 7, 9, 11, 13, 15, 17, 19]
It is easy to iterate over list
or range
using a for loop.
The for loop will go through the elements in the specified list, one item at a time, and provide a temporary variable for the current item. You can use this temporary variable like a normal variable.
Note that the command statements under
for
statement (or other control statements) are grouped by indentation (typically by tab), and no grouping brackets{...}
orend
are needed.
a = range(0,100,7)
for i in a:
i_squared = i*i
print(i_squared)
0 49 196 441 784 1225 1764 2401 3136 3969 4900 5929 7056 8281 9604
Conditional expressions can be used with these two conditional statements.
The if
statement allows you to test a condition and perform some actions if the condition evaluates to True
. You can also provide elif
and/or else
clauses to an if statement to take alternative actions if the condition evaluates to False
.
The while
loop will keep looping until its conditional expression evaluates to False
.
Note: It is possible to "loop forever" when using a while loop with a conditional expression that never evaluates to
False
.Note: Since the for loop will iterate over a container of items until there are no more, there is no need to specify a "stop looping" condition.
value = 9
# Controlling what happens next with if-elif-else
if (value < 5):
explanation = 'less than 5'
value = 10
elif (value == 5):
explanation = 'equal to 5'
value = 15
else:
explanation = 'greater than 5'
value = 20
print(value) # what should this be?
print(explanation)
20 greater than 5
i = 0
while (i<100):
print(i**2)
i += 7
0 49 196 441 784 1225 1764 2401 3136 3969 4900 5929 7056 8281 9604
Python functions can be defined by using def
keyword, for example,
def sign(x): # this defines sign() function
if x >= 0:
return 1
else:
return -1
Now you guess what the following for
loop will print.
for x in range(-5,5):
print(x, sign(x), x*sign(x))
-5 -1 5 -4 -1 4 -3 -1 3 -2 -1 2 -1 -1 1 0 1 0 1 1 1 2 1 2 3 1 3 4 1 4
lambda
functions are small functions usually not more than a line. It can have any number of arguments just like a normal function.
sqr = lambda x: x**2 # this defines sqr() function
for x in range(-5,5):
print(x,sqr(x))
-5 25 -4 16 -3 9 -2 4 -1 1 0 0 1 1 2 4 3 9 4 16