Outline
if condition1:
statement1_1
statement1_2
...
elif condition2:
statement2_1
statement2_2
...
...
else:
statementn_1
statementn_2
...
x=input("Give an integer: ")
x=int(x)
if x >= 0:
a=x
else:
a=-x
print("The absolute value of %i is %i" % (x, a))
c=float(input("Give a number: "))
if c > 0:
print("c is positive")
elif c<0:
print("c is negative")
else:
print("c is zero")
In Python we have two kinds of loops: while
and for
.
i=1
while i*i < 200:
print("Square of", i, "is", i*i)
i = i + 1
print("Finished printing all the squares below 200.")
s=0
for i in [0,1,2,3,4,5,6,7,8,9]:
s = s + i
print("The sum is", s)
s=0
for i in range(10):
s = s + i
print("The sum is", s)
for i in range(3,7):
print(i)
for i in range(3,7,2):
print(i)
break
statementcontinue
statementl=[1,3,65,3,-1,56,-10]
for x in l:
if x < 0:
break
print("The first negative list element was", x)
from math import sqrt, log
l=[1,3,65,3,-1,56,-10]
for x in l:
if x < 0:
continue
print(f"Square root of {x} is {sqrt(x):.3f}")
print(f"Natural logarithm of {x} is {log(x):.4f}")
A function is defined with the def
statement.
def double(x):
"This function multiplies its argument by two."
return x*2
print(double(4), double(1.2), double("abc")) # It even happens to work for strings!
help(double)
Set defalut value to argument
def double(x=2):
"This function multiplies its argument by two."
return x*2
double()
Return multiple outputs
def dou_tri(x=2):
"This function multiplies its argument by two."
return x*2, x*3
dou_tri()
def dou_tri(x=2):
"This function multiplies its argument by two."
return { 'double': x*2, 'triple': x*3}
dou_tri()
Global and local evironments
def myfun():
eggs = 10
myfun()
print(eggs)
def myfun2():
print(eggs)
eggs = 10
myfun2()
def sum_of_squares(a, b):
"Computes the sum of arguments squared"
return a**2 + b**2
print(sum_of_squares(3, 4))
def sum_of_squares(lst):
"Computes the sum of squares of elements in the list given as parameter"
s=0
for x in lst:
s += x**2
return s
print(sum_of_squares([-2]))
print(sum_of_squares([-2,4,5]))
def sum_of_squares(*t):
"Computes the sum of squares of arbitrary number of arguments"
s=0
for x in t:
s += x**2
return s
print(sum_of_squares(-2))
print(sum_of_squares(-2,4,5))
t
.The map
function gets a list and a function as parameters, and it returns a new list whose elements are elements of the original list transformed by the parameter function.
s="12 43 64 6"
L=s.split() # The split method of the string class, breaks the string at whitespaces
# to a list of strings.
print(L)
int(L)
print(list(map(int, L))) # The int function converts a string to an integer
lambda param1,param2, ... : expression
L=[2,3,5]
list(map(lambda x : 2*x+x**2, L))
filter
function takes a function and a list as parameters.filter
function creates a new list with only those elements from the original list for which the parameter function returns True.def is_odd(x):
"""Returns True if x is odd and False if x is even"""
return x % 2 == 1 # The % operator returns the remainder of integer division
L=[1, 4, 5, 9, 10]
list(filter(is_odd, L))
sum
function that returns the sum of a numeric list, can be though to reduce a list to a single element. +
operator until all the list elements are consumed.[1,2,3,4]
is reduced by the expression (((0+1)+2)+3)+4
of repeated applications of the +
operator.L=[1,2,3,4]
from functools import reduce # import the reduce function from the functools module
reduce(lambda x,y:x+y, L, 0) # 0 is the starting value
reduce(lambda x,y:x*y, L, 1)
This corresponds to the sequence (((1*1)*2)*3)*4
of application of operator *
.py
) corresponds to a module. re
math
random
os
sys
import module
import module as m
from module import fun1, fun2
math.cos(1)
import math
math.cos(1)
from math import cos
cos(1)
import math
math.sqrt(3)
from math import sqrt
sqrt(3)
import math as shuxue
shuxue.sqrt(3)
Important libraries of Python
Numpy provides a basic data structure for numerical analysis, and enables storing and handling data in an efficient way.
import numpy as np
my_arr = np.arange(10000000)
my_list = range(10000000)
%time a = my_arr*2
b = my_list*2
b = list(my_list) * 2
len(b)
%time b = [x*2 for x in my_list]