back

Lecture 03

In [1]:
for i in range(1, 5):
    print(i)
else:
    print('The for loop is over')
1
2
3
4
The for loop is over
In [2]:
for i in range(1, 5,1):
    print(i)
else:
    print('The for loop is over')
1
2
3
4
The for loop is over
In [3]:
for i in range(1, 5,2):
    print(i)
else:
    print('The for loop is over')
1
3
The for loop is over
In [4]:
for i in range(0, 5,1):
    x=i*2+1
    print(x)
1
3
5
7
9
In [5]:
for i in range(0, 3,1):
    for j in range(0,3,1):
        print(i,j)
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
In [6]:
x=[1,2,9,2,3]
In [7]:
len(x)
Out[7]:
5
In [8]:
x[0]
Out[8]:
1
In [9]:
x[4]
Out[9]:
3
In [10]:
x[5]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-10-df3e65441209> in <module>
----> 1 x[5]

IndexError: list index out of range
In [11]:
for i in range(len(x)):
    print(x[i])
1
2
9
2
3
In [12]:
type(x)
Out[12]:
list
In [13]:
type(x[0])
Out[13]:
int
In [14]:
y=[2.3,'a',9,'salam',3]
In [15]:
for i in range(len(y)):
    print(y[i])
2.3
a
9
salam
3
In [16]:
type(y[0])
Out[16]:
float
In [17]:
type(y[3])
Out[17]:
str
In [18]:
z=[]
In [19]:
len(z)
Out[19]:
0
In [20]:
for i in range(0,5,1):
    z.append(i)
In [21]:
z
Out[21]:
[0, 1, 2, 3, 4]
In [22]:
len(z)
Out[22]:
5
In [23]:
mat1=[[1,2,3],[3,4,5],[6,7,8]]
In [24]:
mat1
Out[24]:
[[1, 2, 3], [3, 4, 5], [6, 7, 8]]
In [25]:
mat1[1][1]
Out[25]:
4
In [26]:
for i in range(len(mat1)):
    print(mat1[i])
[1, 2, 3]
[3, 4, 5]
[6, 7, 8]
In [27]:
a=3.1
f=1
if type(a)==type(1):
    for i in range(1,a+1,1):
        f=f*i
    print(f)
else:
    print("error! the input number should be integer!")
error! the input number should be integer!
In [28]:
l1=[1,'a',3,6]
for i in l1:
    print(i)
1
a
3
6
In [29]:
l1=[1,3,5,6]
l2=[9,7,2,5]
l3=[]
l4=[]
l5=[]
for i in range(len(l1)):
    l3.append(l1[i]+l2[i])
    l4.append(l1[i]-l2[i])
    l5.append(l1[i]*l2[i])
In [30]:
l3
Out[30]:
[10, 10, 7, 11]
In [31]:
l4
Out[31]:
[-8, -4, 3, 1]
In [32]:
l5
Out[32]:
[9, 21, 10, 30]
In [35]:
l3
Out[35]:
[10, 10, 7, 11]
In [36]:
list0=[[1,2,3,4,5],[9,5,7,1],[0,2]]
for i in range(len(list0)):
    for j in range(len(list0[i])):
        print(list0[i][j])
1
2
3
4
5
9
5
7
1
0
2
In [37]:
l_test=[0,9,2,3,6,8,7]
for i in range(1,len(l_test),2):
    print(l_test[i])
9
3
8