Python as a calculator

Python can be used as calculator + - * / () ** // % abs min max, int and float


In [4]:
3 + 4


Out[4]:
7

In [5]:
3 * 5


Out[5]:
15

In [7]:
4 / 3


Out[7]:
1.3333333333333333

In [8]:
4 // 3


Out[8]:
1

In [9]:
4 % 3


Out[9]:
1

In [10]:
abs(-3)


Out[10]:
3

In [13]:
2**2024+2**1024


Out[13]:
1926243667084634739203147690812942502525097290856569053657671536655703493289225750756096924038107005577607033307665468424208137938409502571528443836358087248839788279968559509024035796546319252657655336760524962441730035462535605201830750366358528761302330842735547127895806782933537114179584526963468396756083778358107373922047409633064454473315599577916694901323931602865652624151417362745960219248296691741851020105901018627157708447211456231129323308989070886896430232091441485389750399668045623162044977567958935598020804175978152088930386334762931471726004347063865758145989982814611023235984738255634432

In [15]:
2.0**1024


---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
<ipython-input-15-2664e7a9cb23> in <module>()
----> 1 2.0**1024

OverflowError: (34, 'Numerical result out of range')

In [17]:
1.0+2


Out[17]:
3.0

In [18]:
2**-30


Out[18]:
9.313225746154785e-10

In [19]:
1.0e-10


Out[19]:
1e-10

Boolean

True False ==, <, >, <=, >=, !=, and, or


In [20]:
True


Out[20]:
True

In [21]:
False


Out[21]:
False

In [22]:
2 == 3


Out[22]:
False

In [23]:
3<5


Out[23]:
True

In [24]:
3 < 6 and 2 == 3


Out[24]:
False

In [25]:
True + 2


Out[25]:
3

In [26]:
True * 10


Out[26]:
10

Variable names

good practice: temp_var, tempVar, TempVar, unicode, = , a,b = b,a


In [27]:
a = 3

In [28]:
a


Out[28]:
3

In [29]:
a,b = 3,4

In [30]:
a


Out[30]:
3

In [31]:
b


Out[31]:
4

In [32]:
a,b = b,a

In [33]:
a


Out[33]:
4

In [35]:
b


Out[35]:
3

In [36]:
حسین = 3

In [39]:
حسین + b


Out[39]:
6

In [40]:
3 = a


  File "<ipython-input-40-7338ef2f1e4d>", line 1
    3 = a
         ^
SyntaxError: can't assign to literal

String

in, not in, +, *, [i], len()


In [41]:
s = 'This is a python string'

In [43]:
"is" in s


Out[43]:
True

In [44]:
'is' not in s


Out[44]:
False

In [45]:
s[5]


Out[45]:
'i'

In [47]:
len(s)


Out[47]:
23

In [52]:
'String one, ' + 'String tow'


Out[52]:
'String one, String tow'

In [53]:
3 * 'A '


Out[53]:
'A A A '

List

in, not in, +, *, [], len(), min(), max(), sum(), help()


In [54]:
l = ['akbar', 'mamad', 'mahmoud', 'hasan']

In [55]:
l


Out[55]:
['akbar', 'mamad', 'mahmoud', 'hasan']

In [57]:
l[2]


Out[57]:
'mahmoud'

In [58]:
l[2]=['mahmoud', 'ahmad']

In [59]:
l


Out[59]:
['akbar', 'mamad', ['mahmoud', 'ahmad'], 'hasan']

In [60]:
len(l)


Out[60]:
4

In [61]:
l[-1]


Out[61]:
'hasan'

In [62]:
ln = [2,5,6,1,3,5]

In [65]:
max(ln)


Out[65]:
6

In [66]:
sum(ln)


Out[66]:
22

In [67]:
ln1 = [1,2,4,5]

In [68]:
ln1+ln


Out[68]:
[1, 2, 4, 5, 2, 5, 6, 1, 3, 5]

In [69]:
l+ln+ln1


Out[69]:
['akbar', 'mamad', ['mahmoud', 'ahmad'], 'hasan', 2, 5, 6, 1, 3, 5, 1, 2, 4, 5]

List

.append(), .count(), .index(), .pop(), .remove(), .reverse(), help()


In [70]:
ll = []

In [72]:
ll.append(1)

In [73]:
ll


Out[73]:
[1]

In [75]:
l.reverse()

In [76]:
l


Out[76]:
['hasan', ['mahmoud', 'ahmad'], 'mamad', 'akbar']

In [77]:
l.pop()


Out[77]:
'akbar'

In [78]:
l


Out[78]:
['hasan', ['mahmoud', 'ahmad'], 'mamad']

Math


In [80]:
sqrt(2)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-80-40e415486bd6> in <module>()
----> 1 sqrt(2)

NameError: name 'sqrt' is not defined

In [82]:
import math

In [83]:
math.sqrt(2)


Out[83]:
1.4142135623730951

In [84]:
from math import sqrt

In [85]:
sqrt(2)


Out[85]:
1.4142135623730951

In [86]:
help(math)


Help on built-in module math:

NAME
    math

DESCRIPTION
    This module is always available.  It provides access to the
    mathematical functions defined by the C standard.

FUNCTIONS
    acos(...)
        acos(x)
        
        Return the arc cosine (measured in radians) of x.
    
    acosh(...)
        acosh(x)
        
        Return the inverse hyperbolic cosine of x.
    
    asin(...)
        asin(x)
        
        Return the arc sine (measured in radians) of x.
    
    asinh(...)
        asinh(x)
        
        Return the inverse hyperbolic sine of x.
    
    atan(...)
        atan(x)
        
        Return the arc tangent (measured in radians) of x.
    
    atan2(...)
        atan2(y, x)
        
        Return the arc tangent (measured in radians) of y/x.
        Unlike atan(y/x), the signs of both x and y are considered.
    
    atanh(...)
        atanh(x)
        
        Return the inverse hyperbolic tangent of x.
    
    ceil(...)
        ceil(x)
        
        Return the ceiling of x as an int.
        This is the smallest integral value >= x.
    
    copysign(...)
        copysign(x, y)
        
        Return a float with the magnitude (absolute value) of x but the sign 
        of y. On platforms that support signed zeros, copysign(1.0, -0.0) 
        returns -1.0.
    
    cos(...)
        cos(x)
        
        Return the cosine of x (measured in radians).
    
    cosh(...)
        cosh(x)
        
        Return the hyperbolic cosine of x.
    
    degrees(...)
        degrees(x)
        
        Convert angle x from radians to degrees.
    
    erf(...)
        erf(x)
        
        Error function at x.
    
    erfc(...)
        erfc(x)
        
        Complementary error function at x.
    
    exp(...)
        exp(x)
        
        Return e raised to the power of x.
    
    expm1(...)
        expm1(x)
        
        Return exp(x)-1.
        This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
    
    fabs(...)
        fabs(x)
        
        Return the absolute value of the float x.
    
    factorial(...)
        factorial(x) -> Integral
        
        Find x!. Raise a ValueError if x is negative or non-integral.
    
    floor(...)
        floor(x)
        
        Return the floor of x as an int.
        This is the largest integral value <= x.
    
    fmod(...)
        fmod(x, y)
        
        Return fmod(x, y), according to platform C.  x % y may differ.
    
    frexp(...)
        frexp(x)
        
        Return the mantissa and exponent of x, as pair (m, e).
        m is a float and e is an int, such that x = m * 2.**e.
        If x is 0, m and e are both 0.  Else 0.5 <= abs(m) < 1.0.
    
    fsum(...)
        fsum(iterable)
        
        Return an accurate floating point sum of values in the iterable.
        Assumes IEEE-754 floating point arithmetic.
    
    gamma(...)
        gamma(x)
        
        Gamma function at x.
    
    hypot(...)
        hypot(x, y)
        
        Return the Euclidean distance, sqrt(x*x + y*y).
    
    isfinite(...)
        isfinite(x) -> bool
        
        Return True if x is neither an infinity nor a NaN, and False otherwise.
    
    isinf(...)
        isinf(x) -> bool
        
        Return True if x is a positive or negative infinity, and False otherwise.
    
    isnan(...)
        isnan(x) -> bool
        
        Return True if x is a NaN (not a number), and False otherwise.
    
    ldexp(...)
        ldexp(x, i)
        
        Return x * (2**i).
    
    lgamma(...)
        lgamma(x)
        
        Natural logarithm of absolute value of Gamma function at x.
    
    log(...)
        log(x[, base])
        
        Return the logarithm of x to the given base.
        If the base not specified, returns the natural logarithm (base e) of x.
    
    log10(...)
        log10(x)
        
        Return the base 10 logarithm of x.
    
    log1p(...)
        log1p(x)
        
        Return the natural logarithm of 1+x (base e).
        The result is computed in a way which is accurate for x near zero.
    
    log2(...)
        log2(x)
        
        Return the base 2 logarithm of x.
    
    modf(...)
        modf(x)
        
        Return the fractional and integer parts of x.  Both results carry the sign
        of x and are floats.
    
    pow(...)
        pow(x, y)
        
        Return x**y (x to the power of y).
    
    radians(...)
        radians(x)
        
        Convert angle x from degrees to radians.
    
    sin(...)
        sin(x)
        
        Return the sine of x (measured in radians).
    
    sinh(...)
        sinh(x)
        
        Return the hyperbolic sine of x.
    
    sqrt(...)
        sqrt(x)
        
        Return the square root of x.
    
    tan(...)
        tan(x)
        
        Return the tangent of x (measured in radians).
    
    tanh(...)
        tanh(x)
        
        Return the hyperbolic tangent of x.
    
    trunc(...)
        trunc(x:Real) -> Integral
        
        Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.

DATA
    e = 2.718281828459045
    pi = 3.141592653589793

FILE
    (built-in)


Input and outputs

print(), '{0:8.4}'.format(), input(), eval()


In [87]:
print(l)


['hasan', ['mahmoud', 'ahmad'], 'mamad']

In [89]:
print(l,ln,ln1)


['hasan', ['mahmoud', 'ahmad'], 'mamad'] [2, 5, 6, 1, 3, 5] [1, 2, 4, 5]

In [95]:
'b is {1} and a is {0}, {2:5.3}.'.format(a,b, 0.3333333333)


Out[95]:
'b is 3 and a is 4, 0.333.'

In [100]:
a = input("Engter somthing:")


Engter somthing:2*3

In [101]:
a


Out[101]:
'2*3'

In [103]:
eval(a)


Out[103]:
6

In [104]:
eval('math.sqrt(2)')


Out[104]:
1.4142135623730951

Flow Controls

if else, for


In [113]:
if 2>3:
    # This is inside of loop
    print('this')
    print('this')
    print('this')
    if 2<5:
        print('2<5')
else:
    print('that')
    print('that')    
print("end")


that
that
end

In [116]:
list(range(3,10,2))


Out[116]:
[3, 5, 7, 9]

In [110]:
for i in range(10):
    print(i)


0
1
2
3
4
5
6
7
8
9

In [111]:
for i in l:
    print(i)


hasan
['mahmoud', 'ahmad']
mamad

In [112]:
for i in [0, 0.1, 0.2, 0.3]:
    print(i)


0
0.1
0.2
0.3

In [117]:
for i in range(10):
    print(i*0.1)


0.0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6000000000000001
0.7000000000000001
0.8
0.9

function

comments, docstrings, numbers and lists


In [135]:
def f(x):
    '''
    Add one to x and return it. 
    This is a simple function to demonstrate a concept.
    '''
    x+=1
    return x

In [136]:
help(f)


Help on function f in module __main__:

f(x)
    Add one to x and return it. 
    This is a simple function to demonstrate a concept.


In [120]:
a = 3

In [121]:
f(a)


Out[121]:
4

In [122]:
a


Out[122]:
3

In [130]:
def g(l):
    l[0] = 'saeed'
    return l

In [131]:
l


Out[131]:
['hasan', ['mahmoud', 'ahmad'], 'mamad']

In [132]:
g(l)


Out[132]:
['saeed', ['mahmoud', 'ahmad'], 'mamad']

In [133]:
l


Out[133]:
['saeed', ['mahmoud', 'ahmad'], 'mamad']

In [137]:
help(g)


Help on function g in module __main__:

g(l)