In [1]:
# setting a variable
a = 1.23
# although just writing the variable will show it's value, but this is not the recommended
# way, because per cell only the last one will be printed and stored in the out[]
# list that the notebook maintains
a
a+1
Out[1]:
The right way to print is using the official print() function in python and this way you can also print out multiple lines in the out[]
In [2]:
print(a)
print(type(a))
Now you can see that each call to print() will cause output on a new line,and also note they are not in the Out[] list
overwriting the same variable , now as a string
In [5]:
a="1.23"
print(a,type(a))
In [4]:
# checking the value of the variable
a
Out[4]:
In [5]:
from __future__ import print_function
Now we can print(pi) in python2. The old style would be print pi
In [6]:
pi = 3.1415
print("pi=",pi)
print("pi=%15.10f" % pi)
In [7]:
# for reference, here is the old style of printing in python2
# print "pi=",pi
Most programming languages have a way to control the flow of the program. The common ones are
While you are looking at this code, note that white-space (indentation) controls the extent of the code, and unlike other language, there is no special symbol or end type statement. This is probably the single most confusing thing about those new to the python language.
In [10]:
n = 1
if n > 0:
print("yes, n>0")
else:
print("not")
for i in [2,4,n,6]:
print("i=",i)
print("oulala, after this for loop, i=",i)
n = 10
while n>0:
# n = n - 2
print("whiling",n)
n = n - 2
print("last n",n)
A list is one of four major data structures (lists, dictionaries, sets, tuples) that python uses. It is the most simple one, and has direct parallels to those in other languages such as Fortran, C/C++, Java etc.
Python uses special symbols to make up these collection, briefly they are:
In [ ]:
In [9]:
a1 = [1,2,3,4]
a2 = range(1,5)
print(a1)
print(a2)
a2 = ['a',1,'cccc']
print(a1)
print(a2)
a3 = range(12,20,2)
print(a3)
In [10]:
a1=range(3)
a2=range(1,4)
print(a1,a2)
In [11]:
a1+a2
Out[11]:
In [12]:
import math
import numpy as np
In [13]:
math.pi
Out[13]:
In [14]:
np.pi
Out[14]:
In [15]:
# %matplotlib inline
import matplotlib.pyplot as plt
In [16]:
a=np.arange(0,1,0.01)
In [17]:
b = a*a
c = np.sqrt(a)
In [18]:
plt.plot(a,b,'-bo',label='b')
plt.plot(a,c,'-ro',label='c')
plt.legend()
Out[18]:
In [19]:
plt.plot(a,a+1)
Out[19]:
In [20]:
plt.show()
In [ ]:
In [ ]: