输入分数字符串,判断并输出相应的百分数;特例不足1%输出E,超出99%输出F
1,从字符串中取出x,y;
2,按题中要求计算输出;
while True:
try:
## 取出x,y
x, z, y= input("Fraction: ")
x, y = int(x), int (y)
##防止出错
if y == 0:
raise ZeroDivisionError
if x > y:
raise ValueError
break
except(ValueError, ZeroDivisionError):
pass
## 模拟题
if 0 < x/y < 0.99:
print(f"{round(x/y*100)}%")
elif x/y >= 0.99:
print("F")
else:
print("E")
根据用户输入的信息,匹配菜单价格,最终算出最终价格。
## 菜单信息
menu = {
"Baja Taco": 4.00,
"Burrito": 7.50,
"Bowl": 8.50,
"Nachos": 11.00,
"Quesadilla": 8.50,
"Super Burrito": 8.50,
"Super Quesadilla": 9.50,
"Taco": 3.00,
"Tortilla Salad": 8.00,
}
##total:结果
total = 0
## 计算输出
while True:
try:
## title(): 首字母大写其余小写
item = input("Item: ").title()
if item in menu:
total += menu[item]
print(f"Total: ${total:.2f}")
except EOFError:
print()
break
记录用户输入商品,最终输出已输入的商品以及商品数量;
## 存储商品信息
list = {}
while True:
## 输入处理
try:
## upper():字符串大写
item = input("").upper()
except EOFError:
print()
break
## 记录商品
if item in list:
list[item] += 1
else:
list[item] = 1
## 输出结果
for item, cnt in sorted(list.items()):
print(f"{cnt} {item}")
用户输入9/8/1636,September 8, 1636形式,系统转换输出1636-09-08;若用户输出其他形式抛异常。
## 月份记录
months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]
##思路:分情况讨论
while True:
date = input("Date: ")
month,day,year = "", "", ""
try:
## 9/8/1636
if len(date.split("/")) == 3:
date = date.split("/")
month, day, year = map(int, date)
## September 8, 1636
else:
date = date.split(",")
if len(date) == 2:
month, day = date[0].split()
month = months.index(month)+1
day, year = int(day), int(date[1])
##输出
if 1<=int(month)<=12 and 1<=int(day)<=31:
print(f"{year:04}-{month:02}-{day:02}")
break
except ValueError:
pass
练习python调用库操作;
from emoji import emojize
print("Output:", emojize(input("Input: ")))
The documentation for pyfiglet isn’t very clear, but you can use the module as follows:
from pyfiglet import Figlet
figlet = Figlet()
You can then get a list of available fonts with code like this:
figlet.getFonts()
You can set the font with code like this, wherein f is the font’s name as a str:
figlet.setFont(font=f)
And you can output text in that font with code like this, wherein s is that text as a str:
print(figlet.renderText(s))
from pyfiglet import Figlet
import random
import sys
fonts = Figlet().getFonts()
# Zero if the user would like to output text in a random font.
# Two if the user would like to output text in a specific font, in which case the first of the two should be -f or --font, and the second of the two should be the name of the font.
if len(sys.argv) == 1:
font = random.choice(fonts)
elif len(sys.argv) == 3:
if sys.argv[1] in ["-f", "--font"] and sys.argv[2] in fonts:
font = sys.argv[2]
else:
sys.exit("Invalid arguments.")
else:
sys.exit("Invalid number of arguments.")
## 输出
text = input("Input: ")
print("Output:\n", Figlet(font=font).renderText(text))
用户输入名字,将所有名字按照inflect中的操作输出;
import inflect
p = inflect.engine()
names = []
while True:
try:
names.append(input("Name: ").strip())
except EOFError:
print()
break
print(f"Adieu, adieu, to {p.join(names)}")
用户选择猜数等级,然后进行竞猜。竞猜过程中会提示用户信息,直到猜中为止;
from random import randint
## 选择猜数等级
while True:
try:
n = int(input("Level: "))
if n < 0:
raise ValueError
break
except ValueError:
pass
## 生成竞猜的数
rand = randint(1, n)
## 用户判断
while True:
try:
guess = int(input("Guess: "))
if guess < rand:
print("Too small!")
elif guess > rand:
print("Too large!")
else:
print("Just right!")
break
except ValueError:
pass
用户选择等级进行随机式子生成,最后根据算式正确结果算取所得分数;
import random
def main():
level = get_level()
score = 0
for _ in range(10):
x = generate_integer(level)
y = generate_integer(level)
## 计算score
tries = 0
while tries < 3:
try:
tries += 1
answer = int(input(f"{x} + {y} = "))
if answer == x+y:
score += 1
break
else:
print("EEE")
except ValueError:
pass
print(f"{x} + {y} = {x+y}")
print("Score", score)
## 获取等级
def get_level():
while True:
try:
level = int(input("Level: "))
if level in [1, 2, 3]:
return level
except ValueError:
pass
## 在范围内生成数字
def generate_integer(level):
if level == 1:
return random.randint(0, 9)
return random.randint(10 ** (level - 1), 10**level - 1)
if __name__ == "__main__":
main()
Expects the user to specify as a command-line argument the number of Bitcoins n, that they would like to buy. If that argument cannot be converted to a float, the program should exit via sys.exit with an error message.
Queries the API for the CoinDesk Bitcoin Price Index at https://api.coindesk.com/v1/bpi/currentprice.json, which returns a JSON object, among whose nested keys is the current price of Bitcoin as a float. Be sure to catch any exceptions, as with code like:
import requests
try:
...
except requests.RequestException:
...
Outputs the current cost of Bitcoins in USD to four decimal places, using , as a thousands separator.
import sys
import requests
try:
response = requests.get("https://api.coindesk.com/v1/bpi/currentprice.json")
data = response.json()
current_price = data["bpi"]["USD"]["rate_float"]
except requests.RequestException:
sys.exit()
try:
n = float(sys.argv[1])
except IndexError:
sys.exit("Missing command-line argument")
except ValueError:
sys.exit("Command-line argument is not a number")
print(f"${n * current_price:,.4f}")
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Pythonconditionalassignmentoperator对于这样一个简单的问题表示歉意,但是谷歌搜索||=并不是很有帮助;)Python中是否有与Ruby和Perl中的||=语句等效的语句?例如:foo="hey"foo||="what"#assignfooifit'sundefined#fooisstill"hey"bar||="yeah"#baris"yeah"另外,类似这样的东西的通用术语是什么?条件分配是我的第一个猜测,但Wikipediapage跟我想的不太一样。
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht
华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o
我想解析一个已经存在的.mid文件,改变它的乐器,例如从“acousticgrandpiano”到“violin”,然后将它保存回去或作为另一个.mid文件。根据我在文档中看到的内容,该乐器通过program_change或patch_change指令进行了更改,但我找不到任何在已经存在的MIDI文件中执行此操作的库.他们似乎都只支持从头开始创建的MIDI文件。 最佳答案 MIDIpackage会为您完成此操作,但具体方法取决于midi文件的原始内容。一个MIDI文件由一个或多个音轨组成,每个音轨是十六个channel中任何一个上的
本文主要介绍在使用Selenium进行自动化测试或者任务时,对于使用了iframe的页面,如何定位iframe中的元素文章目录场景描述解决方案具体代码场景描述当我们在使用Selenium进行自动化测试的时候,可能会遇到一些界面或者窗体是使用HTML的iframe标签进行承载的。对于iframe中的标签,如果直接查找是无法找到的,会抛出没有找到元素的异常。比如近在咫尺的例子就是,CSDN的登录窗体就是使用的iframe,大家可以尝试通过F12开发者模式查看到的tag_name,class_name,id或者xpath来定位中的页面元素,会抛出NoSuchElementException异常。解决
2022/8/4更新支持加入水印水印必须包含透明图像,并且水印图像大小要等于原图像的大小pythonconvert_image_to_video.py-f30-mwatermark.pngim_dirout.mkv2022/6/21更新让命令行参数更加易用新的命令行使用方法pythonconvert_image_to_video.py-f30im_dirout.mkvFFMPEG命令行转换一组JPG图像到视频时,是将这组图像视为MJPG流。我需要转换一组PNG图像到视频,FFMPEG就不认了。pyav内置了ffmpeg库,不需要系统带有ffmpeg工具因此我使用ffmpeg的python包装p
ValidPalindromeGivenastring,determineifitisapalindrome,consideringonlyalphanumericcharactersandignoringcases. [#125]Example:"Aman,aplan,acanal:Panama"isapalindrome."raceacar"isnotapalindrome.Haveyouconsiderthatthestringmightbeempty?Thisisagoodquestiontoaskduringaninterview.Forthepurposeofthisproblem
是否可以在PyYAML或Ruby的Psych引擎中禁用创建anchor和引用(并有效地显式列出冗余数据)?也许我在网上搜索时遗漏了一些东西,但在Psych中似乎没有太多可用的选项,而且我也无法确定PyYAML是否允许这样做.基本原理是我必须序列化一些数据并将其以可读的形式传递给一个不是真正的技术同事进行手动验证。有些数据是多余的,但我需要以最明确的方式列出它们以提高可读性(anchor和引用是提高效率的好概念,但不是人类可读性)。Ruby和Python是我选择的工具,但如果有其他一些相当简单的方法来“展开”YAML文档,它可能就可以了。 最佳答案
我很好奇.NET将如何影响Python和Ruby应用程序。用IronPython/IronRuby编写的应用程序是否会非常特定于.NET环境,以至于它们实际上将变得特定于平台?如果他们不使用任何.NET功能,那么IronPython/IronRuby相对于非.NET同类产品的优势是什么? 最佳答案 我不能说任何关于IronRuby的东西,但是大多数Python实现(如IronPython、Jython和PyPy)都试图尽可能忠实于CPython实现。不过,IronPython正在迅速成为这方面的佼佼者之一,并且在PlanetPyth