for i in range(5):
print(i)
0 1 2 3 4
for i in range (8):
print(i ** 2)
0 1 4 9 16 25 36 49
list = []
for i in range(8):
list.append(i**2)
print(list)
[0, 1, 4, 9, 16, 25, 36, 49]
list = [2, 4, 6, 8]
for i in list:
print(i)
2 4 6 8
list = [2, 4, 6, 8]
for i in enumerate(list):
print("(Index, Elements) = {}".format(i))
(Index, Elements) = (0, 2) (Index, Elements) = (1, 4) (Index, Elements) = (2, 6) (Index, Elements) = (3, 8)
list = [2, 4, 6, 8]
for i, j in enumerate(list):
print("Index {} contains {}".format(i, j))
Index 0 contains 2 Index 1 contains 4 Index 2 contains 6 Index 3 contains 8
list = [i ** 2 for i in range(8)]
print(list)
[0, 1, 4, 9, 16, 25, 36, 49]
for i in range(4):
for j in range(4):
print("i={}, j={}".format(i,j))
i=0, j=0 i=0, j=1 i=0, j=2 i=0, j=3 i=1, j=0 i=1, j=1 i=1, j=2 i=1, j=3 i=2, j=0 i=2, j=1 i=2, j=2 i=2, j=3 i=3, j=0 i=3, j=1 i=3, j=2 i=3, j=3
a = True
b = False
print (a)
True
print(b)
False
c = a + b
print (c)
1
c = a - b
print(c)
1
a1 = False
b1 = False
c1 = a1 + b1
print (c1)
0
a1 = False
b1 = False
c1 = a1 - b1
print (c1)
0
print (a or b)
True
print (a and b)
False
print(not(b))
True
print (a and not(b))
True
if a:
print("yes")
yes
if b:
print("yes")
if not(b):
print("yes")
yes
if a or b:
print("yes")
yes
i = 0
a = i == 1
print(a)
False
a = i != 1
print(a)
True
if i == 0:
print("yes")
yes
if i != 1:
print("yes")
yes
i = 1
j = 0
if i != 1 or j == 0:
print("yes")
yes
"bo" in "book"
True
if "bo" in "book":
print("yes")
yes
if "be" in "book":
print("yes")
if "be" in "book":
print("yes")
else:
print("no")
no
if "bo" in "book" and 1 == 2:
print("yes")
elif "bo" in "book":
print("only one is true")
else:
print("no")
only one is true
if 0:
print("yes")
if 1:
print("yes")
yes
if 2:
print("yes")
yes
if 5.4:
print("yes")
yes
age = int(input("Please enter your age: "))
gender = input("Please, enter your gender: ")
if age < 18:
if gender == 'M' or gender == 'm':
print('son')
else:
print('daughter')
elif age >= 18 and age < 65:
if gender == 'M' or gender == 'm':
print('father')
else:
print('mother')
else:
if gender == 'M' or gender == 'm':
print('grandfather')
else:
print('grandmother')
Please enter your age: 4 Please, enter your gender: M son
The equation for the height of a thrown ball is $y = -1/2 g t^2 + v_0 t$ where
import numpy as np
t = np.linspace(0, 2, 100)
g = 9.8
v0_1 = 10
v0_2 = 15
print(t)
[0. 0.02020202 0.04040404 0.06060606 0.08080808 0.1010101 0.12121212 0.14141414 0.16161616 0.18181818 0.2020202 0.22222222 0.24242424 0.26262626 0.28282828 0.3030303 0.32323232 0.34343434 0.36363636 0.38383838 0.4040404 0.42424242 0.44444444 0.46464646 0.48484848 0.50505051 0.52525253 0.54545455 0.56565657 0.58585859 0.60606061 0.62626263 0.64646465 0.66666667 0.68686869 0.70707071 0.72727273 0.74747475 0.76767677 0.78787879 0.80808081 0.82828283 0.84848485 0.86868687 0.88888889 0.90909091 0.92929293 0.94949495 0.96969697 0.98989899 1.01010101 1.03030303 1.05050505 1.07070707 1.09090909 1.11111111 1.13131313 1.15151515 1.17171717 1.19191919 1.21212121 1.23232323 1.25252525 1.27272727 1.29292929 1.31313131 1.33333333 1.35353535 1.37373737 1.39393939 1.41414141 1.43434343 1.45454545 1.47474747 1.49494949 1.51515152 1.53535354 1.55555556 1.57575758 1.5959596 1.61616162 1.63636364 1.65656566 1.67676768 1.6969697 1.71717172 1.73737374 1.75757576 1.77777778 1.7979798 1.81818182 1.83838384 1.85858586 1.87878788 1.8989899 1.91919192 1.93939394 1.95959596 1.97979798 2. ]
y_1 = -1/2 * g * t ** 2 + v0_1 * t
y_2 = -1/2 * g * t ** 2 + v0_2 * t
import matplotlib.pyplot as plt
plt.plot(t, y_1)
[<matplotlib.lines.Line2D at 0x7ff28c4fceb0>]
import matplotlib.pyplot as plt
plt.plot(t, y_2)
[<matplotlib.lines.Line2D at 0x7ff28ee0d580>]
import matplotlib.pyplot as plt
plt.plot(t, y_1)
plt.plot(t, y_2)
[<matplotlib.lines.Line2D at 0x7ff28ede8d30>]
import matplotlib.pyplot as plt
plt.plot(t, y_1)
plt.plot(t, y_2)
plt.xlabel("Time")
plt.ylabel("Height")
Text(0, 0.5, 'Height')
import matplotlib.pyplot as plt
plt.plot(t, y_1)
plt.plot(t, y_2)
plt.xlabel("Time")
plt.ylabel("Height")
plt.grid()
import matplotlib.pyplot as plt
plt.plot(t, y_1, label = "Ball Number 1")
plt.plot(t, y_2, label = "Ball Number 2")
plt.xlabel("Time")
plt.ylabel("Height")
plt.grid()
plt.legend()
<matplotlib.legend.Legend at 0x7ff28ff72e50>
statments = ["Quantum mechanics is a fundamental theory in physics that provides",
"a description of the physical properties of nature at the scale of atoms and subatomic particles.",
"It is the foundation of all quantum physics including quantum chemistry,"
"quantum field theory,",
"quantum technology,"
"and quantum information science.",
"Classical physics, the collection of theories that existed before the advent of quantum mechanics,"
"describes many aspects of nature at an ordinary (macroscopic) scale,"
"but is not sufficient for describing them at small (atomic and subatomic) scales."
"Most theories in classical physics can be derived from quantum mechanics",
"as an approximation valid at large (macroscopic) scale."]
statments
['Quantum mechanics is a fundamental theory in physics that provides', 'a description of the physical properties of nature at the scale of atoms and subatomic particles.', 'It is the foundation of all quantum physics including quantum chemistry,quantum field theory,', 'quantum technology,and quantum information science.', 'Classical physics, the collection of theories that existed before the advent of quantum mechanics,describes many aspects of nature at an ordinary (macroscopic) scale,but is not sufficient for describing them at small (atomic and subatomic) scales.Most theories in classical physics can be derived from quantum mechanics', 'as an approximation valid at large (macroscopic) scale.']
statments[0]
'Quantum mechanics is a fundamental theory in physics that provides'
statments[1]
'a description of the physical properties of nature at the scale of atoms and subatomic particles.'
for i, line in enumerate(statments):
if "quantum" in line:
print("line {} contains quantum".format(i))
line 2 contains quantum line 3 contains quantum line 4 contains quantum
for i, line in enumerate(statments):
if "Quantum" in line:
print("line {} contains Quantum".format(i))
line 0 contains Quantum
for i, line in enumerate(statments):
if "physics" in line:
print("line {} contains physics".format(i))
line 0 contains physics line 2 contains physics line 4 contains physics
s = 0
for i in range(1001):
if not(i % 3 == 0) and not(i % 7 == 0):
s = s + i
print(s)
286284
s = 0
for i in range(101):
# if not(i % 4 == 0) and not(i % 6 == 0):
s = s + i
print(s)
5050
i = 1
while i < 6:
print(i)
i += 1
1 2 3 4 5
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
1 2 3
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
1 2 4 5 6
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
1 2 3 4 5 i is no longer less than 6
# Program to add natural
# numbers up to
# sum = 1+2+3+...+n
# To take input from the user,
# n = int(input("Enter n: "))
n = 10
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
The sum is 55
'''Example to illustrate
the use of else statement
with the while loop'''
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
Inside loop Inside loop Inside loop Inside else
a = ['Car', 'Book', 'Cat']
while a:
print(a.pop(-1))
Cat Book Car
n = 5
while n > 0:
n -= 1
if n == 2:
break
print(n)
print('Loop ended.')
4 3 Loop ended.
n = 5
while n > 0:
n -= 1
if n == 2:
continue
print(n)
print('Loop ended.')
4 3 1 0 Loop ended.
n = 5
while n > 0:
n -= 1
print(n)
else:
print('Loop done.')
4 3 2 1 0 Loop done.
a = ['car', 'cat', 'carpet', 'book']
s = 'shark'
i = 0
while i < len(a):
if a[i] == s:
print(s, 'found in list.')
break
i += 1
else:
# Processing for item not found
print(s, 'not found in list.')
shark not found in list.
a = ['car', 'cat', 'carpet', 'book']
s = 'cat'
i = 0
while i < len(a):
if a[i] == s:
print(s, 'found in list.')
break
i += 1
else:
# Processing for item not found
print(s, 'not found in list.')
cat found in list.
s = 'shark'
if s in a:
print(s, 'found in list.')
else:
print(s, 'not found in list.')
shark not found in list.
s = 'cat'
if s in a:
print(s, 'found in list.')
else:
print(s, 'not found in list.')
cat found in list.
try:
print(a.index('shark'))
except ValueError:
print(s, 'not found in list.')
shark not found in list.
try:
print(a.index('cat'))
except ValueError:
print(s, 'not found in list.')
1
while True:
print('foo')
a = ['car', 'cat', 'carpet', 'book']
while True:
if not a:
break
print(a.pop(-1))
book carpet cat car
a
['car', 'cat', 'carpet', 'book']
a.pop(-1)
'book'
a
['car', 'cat', 'carpet']
a.pop(-1)
'carpet'
a
['car', 'cat']
a.pop(-1)
'cat'
a
['car']
a.pop(-1)
'car'
a
[]
a = ['car', 'cat']
while len(a):
print(a.pop(0))
b = ['carpet', 'book']
while len(b):
print('>', b.pop(0))
car > carpet > book cat > carpet > book
a = ['car', 'cat']
a
['car', 'cat']
len(a)
2
a.pop(0)
'car'
a
['cat']
len(a)
1
a.pop(0)
'cat'
a
[]
len(a)
0
# One-Line while Loops
n = 5
while n > 0: n -= 1; print(n)
4 3 2 1 0
# One-Line if
if True: print('foo')
foo
# But you can’t do this:
while n > 0: n -= 1; if True: print('foo')
File "/var/folders/dw/p9lncvq57tv4px69pk911vl40000gn/T/ipykernel_2914/4240503912.py", line 2 while n > 0: n -= 1; if True: print('foo') ^ SyntaxError: invalid syntax
def func1(x, y, z):
return x ** 3 + y ** 2 + z
func1(1, 2, 3)
8
func1(2, 1, 3)
12
func1(3, 2, 1)
32
func1(x = 1, y = 2, z = 3)
8
func1(y = 2, x = 1, z = 3)
8
func1(z = 3, y = 2, x = 1)
8
def func2(x,y,z, w):
return (y + z + w) / x, (x + z + w) / y, (x + y + w) / z, (x + y + z) / w
x1, y1, z1, w1 = func2(2, 4, 6, 8)
print(x1, y1, z1, w1)
9.0 4.0 2.3333333333333335 1.5
def func2(x,y,z, w):
return (y + z + w) / x, (x + z + w) / y, (x + y + w) / z, (x + y + z) / w
Values = func2(2, 4, 6, 8)
print(Values)
(9.0, 4.0, 2.3333333333333335, 1.5)
print (type(x1))
<class 'float'>
print(type(Values))
<class 'tuple'>
def func3(x):
return x + 10
print (func3(2))
12
func4 = lambda x: x + 10
print(func4(2))
12
x = lambda a, b : a * b
print(x(5, 6))
30
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
13
def myfunc(n):
return lambda a : a * n
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
22
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
22 33
def derivative(f, x, delta = 0.01): #returns derivative of f at value x
return (f(x + delta) - f(x))/delta
def x_cube(x):
return x ** 3
derivative(x_cube, 2)
12.060099999999707
def derivative(f, x, delta = 0.01): #returns derivative of f at value x
return (f(x+delta) - f(x))/delta
derivative(lambda x: x ** 3, 2)
12.060099999999707
func5 = lambda x, y, z, w : ((y + z + w) / x, (x + z + w) / y, (x + y + w) / z, (x + y + z) / w)
x1, y1, z1, w1 = func5(2, 4, 6, 8)
print(x1, y1, z1, w1)
9.0 4.0 2.3333333333333335 1.5
func5 = lambda x, y, z, w : ((y + z + w) / x, (x + z + w) / y, (x + y + w) / z, (x + y + z) / w)
Values = func5(2, 4, 6, 8)
print(Values)
(9.0, 4.0, 2.3333333333333335, 1.5)
def subtract(x, y):
return x - y
subtract_10 = lambda x: subtract(x, 10)
print(subtract_10(6))
-4
# list of students
list1 = ['s', 't', 'u', 'd', 'e', 'n', 't', 's']
list1_iter = iter(list1)
print(next(list1_iter)) # 's'
print(next(list1_iter)) # 't'
print(next(list1_iter)) # 'u'
print(next(list1_iter)) # 'd'
print(next(list1_iter)) # 'e'
print(next(list1_iter)) # 'n'
print(next(list1_iter)) # 't'
print(next(list1_iter)) # 's'
s t u d e n t s
dic1 = {'a':1, 'b':2, 'c':3}
for item in dic1:
print(item)
a b c
dic1 = {'a':1, 'b':2, 'c':3}
dic1_iter = iter(dic1)
print(next(dic1_iter))
print(next(dic1_iter))
print(next(dic1_iter))
a b c
# ends the output with a <space>
print("Amir" , end = ' ')
print("Akbari")
Amir Akbari
# ends the output with a <@>
print("Amir" , end = '@')
print("gmail.com")
Amir@gmail.com
s = 0
f = (x ** 2 for x in range(10))
for x in f:
print(x, end= ' ')
s = s + x
print(f"===> sum = {s}")
print("sum obtained from sum function is also", sum(x**2 for x in range(10)))
0 1 4 9 16 25 36 49 64 81 ===> sum = 285 sum obtained from sum function is also 285
def f(n = 10):
for i in range(1, n + 1):
yield i + 5
gen1 = f()
gen1
<generator object f at 0x7ff28ff11b30>
for x in gen1:
print(x, end= ' ')
6 7 8 9 10 11 12 13 14 15
def sentence_gen():
yield 'Physics is the natural science '
yield 'that studies matter, its fundamental constituents, '
yield 'its motion and behavior through space and time, '
yield 'and the related entities of energy and force.'
gen2 = sentence_gen()
for x in gen2:
print(x, end='')
Physics is the natural science that studies matter, its fundamental constituents, its motion and behavior through space and time, and the related entities of energy and force.
Like lambda functions for functions, there are more concise way to make generators as well. This involves using a generator expression like such:
gen3 = (x ** 2 for x in range(11))
gen3
<generator object <genexpr> at 0x7ff29010bc10>
for x in gen3:
print(x, end=' ')
0 1 4 9 16 25 36 49 64 81 100
Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators.
import itertools
# for in loop
for i in itertools.count(0, 5):
if i == 35:
break
else:
print(i, end =" ")
0 5 10 15 20 25 30
import itertools
count = 0
for i in itertools.cycle('ABC'):
if count > 7:
break
else:
print(i, end = " ")
count += 1
A B C A B C A B
l = ['Course', 'Presented', 'For', 'Students']
count = 0
for i in itertools.cycle(l):
if count > 10:
break
else:
print(i, end = " ")
count += 1
Course Presented For Students Course Presented For Students Course Presented For
l = ['Course', 'Presented', 'For', 'Students']
# defining iterator
iterators = itertools.cycle(l)
for i in range(11):
print(next(iterators), end = " ")
Course Presented For Students Course Presented For Students Course Presented For