乐趣区

关于python3.x:Python入门系列九piptry-except用户输入字符串格式

pip

蕴含模块所需的所有文件。

查看是否装置了 PIP

$ pip --version

装置

$ pip install package_name

应用包

import package_name

删除包

$ pip uninstall camelcase

列出包

pip list

Try Except

try:
  print(x)
except:
  print("An exception occurred")

您能够依据须要定义任意数量的异样块,例如,如果您想为非凡类型的谬误执行非凡代码块

try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")

如果没有引发谬误,能够应用 else 关键字定义要执行的代码块

try:
  print("Hello")
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")

如果指定了 finally 块,则无论 try 块是否引发谬误,都将执行 finally。

ry:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The'try except'is finished")

这对于敞开对象和清理资源十分有用

try:
  f = open("demofile.txt")
  try:
    f.write("Lorum Ipsum")
  except:
    print("Something went wrong when writing to the file")
  finally:
    f.close()
except:
  print("Something went wrong when opening the file")

作为 Python 开发人员,如果呈现条件,您能够抉择抛出异样。

x = -1

if x < 0:
  raise Exception("Sorry, no numbers below zero")

您能够定义要引发的谬误类型,以及要打印给用户的文本。

x = "hello"

if not type(x) is int:
  raise TypeError("Only integers are allowed")

用户输出

username = input("Enter username:")
print("Username is:" + username)

字符串格局

price = 49
txt = "The price is {} dollars"
print(txt.format(price)) # The price is 49 dollars

能够在花括号内增加参数,以指定如何转换值

price = 49
txt = "The price is {:.2f} dollars"
print(txt.format(price)) # The price is 49.00 dollars

如果要应用更多值,只需在 format()办法中增加更多值

quantity = 3
itemno = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))

您能够应用索引号(大括号{0}内的数字)确保将值搁置在正确的占位符中

quantity = 3
itemno = 567
price = 49
myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."
print(myorder.format(quantity, itemno, price))

此外,如果要屡次援用同一值,请应用索引号

age = 36
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))

命名索引

myorder = "I have a {carname}, it is a {model}."
print(myorder.format(carname = "Ford", model = "Mustang"))
退出移动版