#!/usr/bin/env python # coding: utf-8 # In[7]: # Question -- if we run the following code and then # try to run the code below ("print") before we give # the response to the input box, then the code below # doesn't run. How to fix it? # Answer: use the "stop" button at the top to terminate # the code looking for an input from the user # worst case: save then "close and halt" from the File # menu and try again variable=input("question") # In[10]: print("program") # In[21]: # finish up Section 2.7 # How does mixing data types in python arithmetic work? x=5 y=1.0 # 1. Operations involving only ints will return an int if possible. # 2. Operations with only floats will return a float # 3. Mixed operations default to returning a float print("x+x=",x+x) print("type(x+x)=",type(x+x)) print("x+y=",x+y) print("type(x+y)=",type(x+y)) print("type(x)=",type(x)) print("type(float(x))=",type(float(x))) print("type(x)=",type(x)) z=float(x) print("type(z)=",type(z)) # In[36]: # Section 2.8 -- more about data output # We know already: the following code will print A, B, and C # each on a new line. print('A') print('B') print('C') print('---------------') # An option for the print function: end print('A',end=".") print('B',end=" ") print('C',end="\n") print('D',end="\n") print('-----------') x='a string of characters' print('x=',x,"and also don't forget that x=",x) print('x=',x,"and also don't forget that x=",x,sep='1234') # In[37]: # Section 2.9 -- named constants # Imagine: you are hired by a bank to write code # you open the code and see the following: account=5.00 fee=account*0.069 # <-- this 0.069 number is mysterious -- no clear # indication from the code of what its purpose is # such mysterious numbers are called "magic numbers" # better to use a "Named constant" which is just a variable that # describes its purpose, usually in all capitals to distinguish it to the eye FEE_RATE=0.069 fee=account*FEE_RATE print("11>>1=",11>>1) # Great example of a magic number: source code of Quake III Arena # Here is the procedure used by the programmers of this game to compute 1/sqrt(x): # 1. get x # 2. shift x right by 1 --- x>>1 # 3. subtract x>>1 from the magic number 0x5F3759DF # 4. apply one step of Newton's method to increase precision # read more: https://en.wikipedia.org/wiki/Fast_inverse_square_root