<jupyter_start><jupyter_text>2-Variables and Basic TypesAlways run this statement first, when working with this book:<jupyter_code>from scipy import *
from matplotlib.pyplot import *
%matplotlib   inline    
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"<jupyter_output><empty_output><jupyter_text>Variables<jupyter_code>a = 1 
diameter = 3.
height = 5.
cylinder = [diameter, height] # reference to a list
a = b = c = 1
a
a = 1
a = a + 1 # a gets the value 2
a
a = 3 * a
a
a = 1
a += 1 # same as a = a + 1
a
a *= 3 # same as a = 3 * a
a<jupyter_output><empty_output><jupyter_text>Numeric Types Integers<jupyter_code>6 // 2  # 3

7 // 2  # 3

7 / 2   # 3.5<jupyter_output><empty_output><jupyter_text>Floating Point Numbers<jupyter_code>0.4 - 0.3 # returns 0.10000000000000003

0.4 - 0.3 == 0.1  # returns False<jupyter_output><empty_output><jupyter_text>Infinite and Not a Number<jupyter_code>exp(1000.)  #  inf

a = inf

3 - a       # -inf

3 + a       #  inf
a+a  # inf

a-a  # nan

a/a  # nan
x = nan 

x < 0 # False

x > 0 # False

x == x # False
0 < inf     # True 
inf <= inf  # True 
inf == inf  # True 
-inf < inf  # True 
inf - inf   # nan 
exp(-inf)   # 0 
exp(1 / inf)  # 1
seterr(all = 'raise')<jupyter_output><empty_output><jupyter_text>Underflow: Machine Epsilon<jupyter_code>import sys
sys.float_info.epsilon # 2.220446049250313e-16 (depending on your system)
a = '1.356'
float(a)<jupyter_output><empty_output><jupyter_text>Other float types in NumPy<jupyter_code>a  = pi # returns   3.141592653589793
a

a1 = float64(a)  # returns   3.1415926535897931
a1

a2=float32(a)  # returns   3.1415927
a2

a - a1  # returns   0.0 
a - a2  # returns   -8.7422780126189537e-08
f32 = finfo(float32) 
f32.precision   # 6 (decimal digits) 
f64 = finfo(float64) 
f64.precision   # 15 (decimal digits) 
f = finfo(float) 
f.precision     # 15 (decimal digits) 
f64.max         # 1.7976931348623157e+308 (largest number) 
f32.max         # 3.4028235e+38 (largest number) 
help(finfo)     # Check for more options<jupyter_output><empty_output><jupyter_text>Complex Numbers<jupyter_code>b = 5.2 
z = bj   # returns a NameError 
z = b*j  # returns a NameError
z = b*1j # is correct
z
z = 3.2 + 5.2j 
z.conjugate() # returns (3.2-5.2j)<jupyter_output><empty_output><jupyter_text>Real and Imaginary Parts<jupyter_code>z = 1j 
z.real       # 0.0 
z.imag       # 1.0 
z.imag = 2   # AttributeError: readonly attribute
z = 1 + 0j 
z == 1     # True 
float(z)   # TypeError
import matplotlib.pyplot as plt
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:
axes(aspect='equal')
plot(unity_roots.real, unity_roots.imag, 'o')
allclose(unity_roots**N, 1) # True
z = 3.2+5.2j 
(z + z.conjugate()) / 2.   # returns (3.2+0j) 
((z + z.conjugate()) / 2.).real   # returns 3.2 
(z - z.conjugate()) / 2.   # returns 5.2j 
((z - z.conjugate()) / 2.).imag   # returns 5.2 
sqrt(z * z.conjugate())   # returns (6.1057350089894991+0j)<jupyter_output><empty_output><jupyter_text>Booleans<jupyter_code>a = True
a
b = 30>45  # b gets the value False
b
x=3
if x>0:
   print("positive")
else:
   print("nonpositive")<jupyter_output><empty_output><jupyter_text>Boolean Operators<jupyter_code>True and False # False
False or True # True
(30 > 45) or (27 < 30) # True
not True # False
not (3 > 4) # True
a=3; b=4; c=-1

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

a == b == c # same as: a == b and b == c<jupyter_output><empty_output><jupyter_text>Boolean Casting<jupyter_code>bool([])   # False 
bool(0)   # False 
bool(' ')   # True 
bool('')   # False 
bool('hello')   # True 
bool(1.2)   # True 
bool(array([1]))   # True 
bool(array([1,2]))   # Exception raised!<jupyter_output><empty_output><jupyter_text>Automatic Boolean Casting<jupyter_code>if a:
   print('Im here')
if bool(a): # exactly the same as above
   print('Im there')
L=[]
if L:
    print("list not empty")
else:
    print("list is empty")
n=23
if n % 2:
    print("n is odd")
else:
    print("n is even")<jupyter_output><empty_output><jupyter_text>Return values of and and or<jupyter_code>def and_as_function(x,y):
    if not x:
        return x
    else:
        return y
    
and_as_function(True,False)
def or_as_function(x,y):
    if x:
        return x
    else:
        return y
    
or_as_function(True,False)
True or x_not_defined
False and x_not_defined
[1] or 'a' # produces [1]
'a' or [1] # produces 'a'<jupyter_output><empty_output><jupyter_text>Booleans and Integers<jupyter_code>def print_ispositive(x):
    possibilities=['nonpositive', 'positive']
    return "x is {}".format(possibilities[x>0])

print_ispositive(-23)
print_ispositive(7)
True+13
2*True+5<jupyter_output><empty_output><jupyter_text>Strings<jupyter_code>name = '<NAME>'
child = "Åsa is <NAME>'s daughter"
book = """Aunt Julia 
and the Scriptwriter""" 

print(name) 
print(child) 
print(book)
book[-1] # returns 'r'

book[-12:] # returns 'Scriptwriter'
book[1]='a'  # returns TypeError
print('Temperature:\t20\tC\nPressure:\t5\tPa')
a="""
A multiline
example"""
a # returns '\nA multiline\nexample'
latexfontsize="\\tiny"
print(latexfontsize)
latexfs=r"\tiny"  
latexfs             # returns "\\tiny"
latexfontsize == latexfs  # returns True
r"\""   # returns  '\\"'
r"\\"   # returns  '\\\\'

r"\"    # returns an error<jupyter_output><empty_output><jupyter_text>Operations on strings and string methods<jupyter_code>last_name='Carlsson'
first_name='Johanna'
Full_name=first_name+' '+last_name  # returns '<NAME>'

Full_name
game=2*'Yo' # returns 'YoYo'
game
'Anna' > 'Arvid' # returns false

'ANNA' < 'anna'  # returns true

'10B' < '11A' # returns true
text = 'quod erat    demonstrandum'
text.split() # returns ['quod', 'erat', 'demonstrandum']
table = 'Johan;Carlsson;19890327'
table.split(';') # returns ['Johan','Carlsson','19890327']
king = 'CarlXVIGustaf'
king.split('XVI')  # returns ['Carl','Gustaf']
sep=';'
sep.join(['Johan','Carlsson','19890327']) # returns 'Johan;Carlsson;19890327'
birthday='20101210'
birthday.find('10') # returns 2<jupyter_output><empty_output><jupyter_text>String Formatting<jupyter_code>course_code = "NUMA21"
print("This course's name is {}".format(course_code)) # This course's name is NUMA21
quantity = 33.45
print("qty{:f}".format(quantity)) # qty33.450000
print("qty{:8.1f}".format(quantity)) # qty    33.5
print("qty{:10.2e}".format(quantity)) # qty  3.35e+01
print("{name} {value:.1f}".format(name="quantity",value=quantity)) # "quantity 33.5"
r"we {} in LaTeX \begin{{equation}}".format('like')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14960275820716534, 'fraction_numerical': 0.05936141508019787, 'mean_word_length': 4.1600928074245935, 'pattern_counts': {'":': 0, '<': 87, '<?xml version=': 0, '>': 83, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '18', 'dir': 'jupyter-structured-clean-dedup', 'id': '593678', 'license': 'MIT', 'n_tokens_mistral': 2978, 'n_tokens_neox': 2682, 'n_words': 626, 'path': '2-VariablesandBasicTypes/2-VariablesandBasicTypes.ipynb', 'repo_name': 'karant17/Scientific-Computing-with-Python-3', 'size': '6697'}