# 2-Variables and Basic Types


Always run this statement first, when working with this book:


```python
from scipy import *
from matplotlib.pyplot import *
%matplotlib   inline   # makes that plots appear within this notebook 
```

## Variables


```python
diameter=3.
height=5.
cylinder=[diameter,height] # reference to a list
```


```python
a = b = c = 1
print(a)
```

    1



```python
a = 1
```


```python
a = a + 1 # a gets the value 2
print(a)
```

    2



```python
a = 3 * a
print(a)
```

    6



```python
a += 1 # same as a = a + 1
a *= 3 # same as a = 3 * a
print(a)
```

    21


## Numeric Types

### Integers


```python
6 // 2  # 3
```




    3




```python
7 // 2  # 3
```




    3




```python
7 / 2   # 3.5 
```




    3.5



### Floating Point Numbers


```python
0.4 - 0.3 # returns 0.10000000000000003
```




    0.10000000000000003




```python
0.4 - 0.3 == 0.1  # returns False 
```




    False



####  Infinite and Not a Number


```python
exp(1000.)  #  inf
```

    /home/claus/anaconda3/lib/python3.5/site-packages/ipykernel/__main__.py:1: RuntimeWarning: overflow encountered in exp
      if __name__ == '__main__':





    inf




```python
a = inf
```


```python
3 - a       # -inf
```




    -inf




```python
3 + a       #  inf
```




    inf




```python
a+a  # inf
```




    inf




```python
a-a  # nan
```




    nan




```python
a/a  # nan
```




    nan




```python
x = nan 
```


```python
x < 0 # False
```




    False




```python
x > 0 # False
```




    False




```python
x == x # False
```




    False




```python
0 < inf # True
```




    True




```python
inf <= inf # True
```




    True




```python
inf == inf # True
```




    True




```python
-inf < inf # True
```




    True




```python
inf - inf  # nan
```




    nan




```python
exp(-inf)  # 0
```




    0.0




```python
exp(1/inf) # 1
```




    1.0



#### Underflow: Machine Epsilon


```python
import sys
sys.float_info.epsilon # 2.220446049250313e-16 (depending on your system)
```




    2.220446049250313e-16



#### Other float types in NumPy


```python
a  = pi # returns   3.141592653589793
a
```




    3.141592653589793




```python
a1 = float64(a)  # returns   3.1415926535897931
a1
```




    3.1415926535897931




```python
a2=float32(a)  # returns   3.1415927
a2
```




    3.1415927




```python
a - a1  # returns   0.0
```




    0.0




```python
 
a - a2  # returns   -8.7422780126189537e-08
```




    -8.7422780126189537e-08




```python
f32 = finfo(float32)
```


```python
f32.precision #  6 (decimal digits)
```




    6




```python
f64 = finfo(float64)
```


```python
f64.precision # 15 (decimal digits)
```




    15




```python
f   = finfo(float)
```


```python
f.precision  # 15 (decimal digits)
```




    15




```python
f64.max  # 1.7976931348623157e+308 (largest number)
```




    1.7976931348623157e+308




```python
f32.max  # 3.4028235e+38 (largest number)
```




    3.4028235e+38



### Complex Numbers


```python
b=5.2
```


```python
z=bj  # returns a (name) error
```


```python
z=b*j # returns a (name) error
```


```python
z=b*1j  # is correct
print(z)
```

    5.2j



```python
z=3.2+5.2j
z.conjugate()  # returns (3.2-5.2j)
```




    (3.2-5.2j)



#### Real and Imaginary Parts


```python
z = 1j
```


```python
z.real # 0
```




    0.0




```python
z.imag # 1
```




    1.0




```python
z.imag = 2 # error
```


```python
N = 10

# the following vector contains the Nth roots of unity:
unity_roots = array([exp(1j*2*pi*k/N) for k in range(N)])

# access all the real or imaginary parts with real or imag:
plot(unity_roots.real, unity_roots.imag, 'o')
axis('equal')

allclose(unity_roots**N, 1) # True
```


```python
z=3.2+5.2j
```


```python
(z+z.conjugate())/2. # returns (3.2+0j)
```




    (3.2+0j)




```python
((z+z.conjugate())/2.).real  # returns 3.2
```




    3.2




```python
(z-z.conjugate())/2.# returns 5.2j  
```




    5.2j




```python
((z-z.conjugate())/2.).imag  # returns 5.2
```




    5.2




```python
sqrt(z*z.conjugate()) # returns  (6.1057350089894991+0j) 
```




    (6.1057350089894991+0j)



## Booleans


```python
a = True
b = 30>45  # b gets the value False
print(a,b)
```

    True False



```python
x=3
if x>0:
   print("positive")
else:
   print("nonpositive")
```

    positive


### Boolean Operators


```python
True and False # False
```




    False




```python
False or True # True
```




    True




```python
(30 > 45) or (27 < 30) # True
```




    True




```python
not True # False
```




    False




```python
not (3 > 4) # True
```




    True




```python
a=3; b=4; c=-1

a < b < c # same as: a < b and b < c
```




    False




```python
a == b == c # same as: a == b and b == c
```




    False



### Boolean Casting


```python
bool([]) # False
```




    False




```python
bool(0) # False
```




    False




```python
bool(' ') # True
```




    True




```python
bool('') # False
```




    False




```python
bool('hello') # True
```




    True




```python
bool(1.2) # True
```




    True




```python
bool(array([1])) # True
```




    True




```python
bool(array([1,2])) # Exception raised!
```

#### Automatic Boolean Casting


```python
L=[]
if L:
    print("list not empty")
else:
    print("list is empty")
```

    list is empty



```python
n=23
if n % 2:
    print("n is odd")
else:
    print("n is even")
```

    n is odd



```python
def and_as_function(x,y):
    if not x:
        return x
    else:
        return y
    
and_as_function(True,False)
```




    False




```python
def or_as_function(x,y):
    if x:
        return x
    else:
        return y
    
or_as_function(True,False)
```




    True




```python
True or x_not_defined

```




    True




```python
False and x_not_defined
```




    False




```python
[1] or 'a' # produces [1]
```




    [1]




```python
'a' or [1] # produces 'a'
```




    'a'



### Booleans and Integers


```python
def print_ispositive(x):
    possibilities=['nonpositive', 'positive']
    return "x is {}".format(possibilities[x>0])

print_ispositive(-23)
```




    'x is nonpositive'




```python
print_ispositive(7)
```




    'x is positive'




```python
True+13
```




    14



## Strings


```python
name = 'Johan Carlsson'
child = "Åsa is Johan Carlsson's daughter"
book = """Aunt Julia 
and the Scriptwriter""" 

print(name) 
print(child) 
print(book)
```

    Johan Carlsson
    Åsa is Johan Carlsson's daughter
    Aunt Julia 
    and the Scriptwriter



```python
book[-1] # returns 'r'
```




    'r'




```python
book[-12:] # returns 'Scriptwriter'
```




    'Scriptwriter'




```python
book[1]='a'
```


```python
print('Temperature:\t20\tC\nPressure:\t5\tPa')
```

    Temperature:	20	C
    Pressure:	5	Pa



```python
a="""
A multiline
example"""
a # returns '\nA multiline\nexample'
```




    '\nA multiline\nexample'




```python
latexfontsize="\\tiny"
print(latexfontsize)
```

    \tiny



```python
latexfs=r"\tiny"  # returns "\\tiny"
latexfontsize == latexfs  # returns True
```




    True



### Operations on strings and string methods


```python
last_name='Carlsson'
first_name='Johanna'
Full_name=first_name+' '+last_name  # returns 'Johanna Carlsson'

print(Full_name)
```

    Johanna Carlsson



```python
game=2*'Yo' # returns 'YoYo'
print(game)
```

    YoYo



```python
'Anna' > 'Arvid' # returns false
```




    False




```python
'ANNA' < 'anna'  # returns true
```




    True




```python
'10B' < '11A' # returns true
```




    True




```python
text='quod erat    demonstrandum'
text.split() # returns ['quod', 'erat', 'demonstrandum']
```




    ['quod', 'erat', 'demonstrandum']




```python
table='Johan;Carlsson;19890327'
table.split(';') # returns ['Johan','Carlsson','19890327']
```




    ['Johan', 'Carlsson', '19890327']




```python
king='CarlXVIGustaf'
king.split('XVI')  # returns ['Carl','Gustaf']
```




    ['Carl', 'Gustaf']




```python
sep=';'
sep.join(['Johan','Carlsson','19890327']) # returns 'Johan;Carlsson;19890327'
```




    'Johan;Carlsson;19890327'




```python
birthday='20101210'
birthday.find('10') # returns 2 
```




    2



### String Formatting


```python
course_code = "NUMA21"
print("This course's name is {}".format(course_code)) # This course's name is NUMA21
```

    This course's name is NUMA21



```python
quantity = 33.45
print("{:f}".format(quantity)) # 33.450000
print("{:1.1f}".format(quantity)) # 33.5
print("{:.2e}".format(quantity)) # 3.35e+01
```

    33.450000
    33.5
    3.35e+01



```python
print("{name} {value:.1f}".format(name="quantity",value=quantity)) # "quantity 33.5"
```

    quantity 33.5



```python
r"we {} in LaTeX \begin{{equation}}".format('like')
```




    'we like in LaTeX \\begin{equation}'



7f2b69541361fb102584f8a1b59e00e92c9cc0a6
ipynb
Jupyter Notebook
11-Namespaces/1-GettingStarted/1-GettingStarted/.ipynb_checkpoints/Untitled-checkpoint.ipynb
karant17/Scientific-Computing-with-Python-3
b300338dea1bb7676e908eb3643ad5d01bd19d72
MIT
2016-12-29T15:16:27.000Z
2021-11-08T09:30:08.000Z
11-Namespaces/1-GettingStarted/1-GettingStarted/.ipynb_checkpoints/Untitled-checkpoint.ipynb
karant17/Scientific-Computing-with-Python-3
b300338dea1bb7676e908eb3643ad5d01bd19d72
MIT
11-Namespaces/1-GettingStarted/1-GettingStarted/.ipynb_checkpoints/Untitled-checkpoint.ipynb
karant17/Scientific-Computing-with-Python-3
b300338dea1bb7676e908eb3643ad5d01bd19d72
MIT
2016-12-30T12:36:49.000Z
2021-05-06T07:44:05.000Z
Qwen/Qwen-72B
1. YES
2. YES