python输入水果查询个数_Python练习题4.9查询水果价格
时间: 2024-02-23 08:04:06 浏览: 26
以下是查询水果价格的Python代码示例:
```python
fruits = {'apple': 3.5, 'banana': 2.5, 'orange': 4.0, 'kiwi': 5.0}
while True:
fruit = input("请输入要查询的水果名称(输入 q 退出):")
if fruit == 'q':
break
price = fruits.get(fruit, None)
if price:
print("{} 的价格为:{:.2f} 元/斤".format(fruit, price))
else:
print("不好意思,没有 {} 这种水果。".format(fruit))
```
运行程序后,输入水果名称即可查询价格,输入 q 退出程序。该程序使用了一个字典来存储水果名称和价格的对应关系,使用 `get()` 方法来获取对应水果的价格,如果不存在则返回 None。最后使用格式化字符串输出查询结果。
相关问题
python查询水果价格_C语言查询水果价格
对于Python查询水果价格,你可以使用以下代码:
```python
fruit_prices = {"apple": 0.5, "banana": 0.3, "orange": 0.4}
fruit = input("请输入水果名称:")
if fruit in fruit_prices:
print("{}的价格是{}元/斤".format(fruit, fruit_prices[fruit]))
else:
print("很抱歉,我们暂时没有{}的价格信息。".format(fruit))
```
对于C语言查询水果价格,你可以使用以下代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char fruit[10];
float price;
printf("请输入水果名称:");
scanf("%s", fruit);
if (strcmp(fruit, "apple") == 0) {
price = 0.5;
} else if (strcmp(fruit, "banana") == 0) {
price = 0.3;
} else if (strcmp(fruit, "orange") == 0) {
price = 0.4;
} else {
printf("很抱歉,我们暂时没有%s的价格信息。\n", fruit);
return 0;
}
printf("%s的价格是%.2f元/斤\n", fruit, price);
return 0;
}
```
python查询水果价格
您好,您可以使用 Python 的 requests 库和 BeautifulSoup 库来爬取水果价格信息。以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 构造请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 构造请求参数
params = {
'q': '水果价格',
'rn': '10',
'ie': 'utf-8',
'oe': 'utf-8',
'tn': 'baiduhome_pg'
}
# 发送请求
response = requests.get('https://www.baidu.com/s', headers=headers, params=params)
# 解析响应
soup = BeautifulSoup(response.text, 'html.parser')
results = soup.select('.c-container')
# 输出结果
for result in results:
title = result.select_one('.t').text
link = result.select_one('.t a')['href']
abstract = result.select_one('.c-abstract').text
print(title)
print(link)
print(abstract)
```
以上代码会在百度搜索中搜索“水果价格”,并输出前 10 条搜索结果的标题、链接和摘要信息。