首页 技术 正文
技术 2022年11月17日
0 收藏 722 点赞 3,324 浏览 1703 个字

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 = -1if 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"))

您的关注,是我的无限动力!

公众号 @生活处处有BUG

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,104
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,581
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,428
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,835
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,918