• Python笔记 #01# Convert Python values into any type


    源:DataCamp

    datacamp 的 DAILY PRACTICE  + 日常收集。

     How much is your $100 worth after 7 years?

     Guess the type

     convert Python values into any type

     Which one of these will throw an error?

    How much is your $100 worth after 7 years?

    Suppose you have $100, which you can invest with a 10% return each year. After one year, it's 100×1.1=110100×1.1=110 dollars, and after two years it's 100×1.1×1.1=121100×1.1×1.1=121. Add code on the right to calculate how much money you end up with after 7 years.

    # How much is your $100 worth after 7 years?
    print(100 * 1.1 ** 7)

    Guess the type

    Suppose you've defined a variable a, but you forgot the type of this variable. 

    In [1]: type(a)
    Out[1]: float
    
    In [2]: type(b)
    Out[2]: str
    
    In [3]: type(c)
    Out[3]: bool
    
    In [4]: 

    Convert Python values into any type

    # Definition of savings and result
    savings = 100
    result = 100 * 1.10 ** 7
    
    # Fix the printout
    print("I started with $" + str(savings) + " and now have $" + str(result) + ". Awesome!")
    
    # Definition of pi_string
    pi_string = "3.1415926"
    
    # Convert pi_string into float: pi_float
    pi_float = float(pi_string)

    Which one of these will throw an error?

    In [1]: "I can add integers, like " + str(5) + " to strings."
    Out[1]: 'I can add integers, like 5 to strings.'
    
    In [2]: "I said " + ("Hey " * 2) + "Hey!"
    Out[2]: 'I said Hey Hey Hey!'
    
    In [3]: True + False
    Out[3]: 1
    
    In [4]: "The correct answer to this multiple choice exercise is answer number " + 2
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
        "The correct answer to this multiple choice exercise is answer number " + 2
    TypeError: Can't convert 'int' object to str implicitly
  • 相关阅读:
    人月神话2
    cJson 常见用法
    Python C扩展
    动态链接--运行时加载dlopen
    mtrace 简介
    Linux coredump
    动态链接--so的搜索过程
    线程同步--条件变量
    编译过程学习
    Linux 信号
  • 原文地址:https://www.cnblogs.com/xkxf/p/8098425.html
Copyright © 2020-2023  润新知