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
原文地址:https://www.cnblogs.com/xkxf/p/8098425.html