Python入门系列(九)pip、try except、用户输入、字符串格式
2023-06-13 09:11:56 时间
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"))
相关文章
- 如何为pycharm配置Python解释器_pycharm选择python解释器
- python移动app开发_神奇的Kivy,让Python快速开发移动app
- python数组拼接字符串_Python练习题——数组拼接
- python实现求和,求平均值——函数[通俗易懂]
- python chmod_使Python脚本可执行chmod755?
- python在线代码编辑器-5种最佳Python IDE和代码编辑器
- 【说站】python中for语句读取生成器
- 怎样更改pycharm的项目默认保存路径_vscode怎么给python导入包
- python hexdump_笨办法学 Python · 续 练习 26:`hexdump`
- Python中logging模块用法
- PYTHON用户流失数据挖掘:建立逻辑回归、XGBOOST、随机森林、决策树、支持向量机、朴素贝叶斯和KMEANS聚类用户画像|附代码数据
- python通过MySQLdb访问mysql数据库详解编程语言
- Python列表和元组的底层实现
- Python os.rename()函数:重命名文件或目录
- 控制Linux下用Pip进行版本控制(linux pip 版本)
- Linux下PIP升级带来的更多便利(linux pip升级)
- Python解析XML文件
- Python入门篇之函数