Exercise 1
iteration = 0
while iteration < 5:
    count = 0
    for letter in "hello, world":
        count += 1
        if iteration % 2 == 0:
            break
    print("Iteration " + str(iteration) + "; count is: " + str(count))
    iteration += 1 


##
把这段代码放到Python可视化网站http://pythontutor.com/ ,可以了解整个代码的运行过程。
当iteration=0,2,4的时候,for letter in "hello, world"只调用了‘h’,然后就print了。
break的意思是跳出for loop.
Exercise guess my number
low = 0
high = 100
a = int((low+high)/2)
print("Please think of a number between 0 and 100!")
b = input("Is your secret number " + str(a) + "?" +"\n"
"Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
while True:
    if b not in "hlc":
        print("Sorry, I did not understand your input.")
    elif b == "h":
        high = a
    elif b == "l":
        low = a
    elif b == "c":
        print("Game over. Your secret number was: "+str(a))
        break
    a = int((low+high)/2)
    b = input("Is your secret number " + str(a) + "?" +"\n"
    "Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
Exercise 3

True:

The internal representation of the decimal number 1/10 = 0.1 requires an infinite number of digits.

Reason:

in order to convert fractions to binary, first we must find a number such that 0.1*(2**x) is a whole number, then we can convert them. But in this case, there is no such number that fulfills this condition, so it doesn't matter how many digits we have to represent the decimal number, it can never be represented with a binary number, but we can have a very good approximation.

watch this(Floating Point Numbers):

https://www.youtube.com/watch?v=PZRI1IfStY0

results matching ""

    No results matching ""