ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python入门系列(九)pip、try except、用户输入、字符串格式

2022-09-04 14:00:08  阅读:199  来源: 互联网

标签:format Python price except try print txt


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"))

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

公众号 @生活处处有BUG

标签:format,Python,price,except,try,print,txt
来源: https://www.cnblogs.com/bugs-in-life/p/16654985.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有