控制結(jié)構(gòu):
- while
if else
if elif - list comprehension
>>> sqlist=[]
>>> for x in range(1,11):
sqlist.append(x*x)
>>> sqlist
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>>
可以簡(jiǎn)化為:
>>> sqlist=[x*x for x in range(1,11)]
>>> sqlist
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>>
還可以增加條件語(yǔ)句
>>> sqlist=[x*x for x in range(1,11) if x%2 != 0]
>>> sqlist
[1, 9, 25, 49, 81]
>>>
3.Exception Handling
常見(jiàn)錯(cuò)誤有兩種,分別是語(yǔ)法錯(cuò)誤錯(cuò)誤和邏輯錯(cuò)誤庞呕。
the logic error leads to a runtime error that causes the program to terminate. These types of runtime errors are typically called exceptions
處理.exceptions的方法:try函數(shù):
>>> anumber = int(input("Please enter an integer "))
Please enter an integer -23
>>> print(math.sqrt(anumber))
Traceback (most recent call last):
File "<pyshell#102>", line 1, in <module>
print(math.sqrt(anumber))
ValueError: math domain error
>>>
處理為:
>>> try:
print(math.sqrt(anumber))
except:
print("Bad Value for square root")
print("Using absolute value instead")
print(math.sqrt(abs(anumber)))
Bad Value for square root
Using absolute value instead
4.79583152331
>>>
使用raise
來(lái)創(chuàng)造 a new RuntimeError exception
>>> if anumber < 0:
... raise RuntimeError("You can't use a negative number")
... else:
... print(math.sqrt(anumber))
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
RuntimeError: You can't use a negative number
>>>