python初学者问答
1.python-quiz-for-beginner
2.python-quiz-for-beginner
3.python-quiz-for-beginner
4.python-quiz-for-beginner
5.python-quiz-for-beginner
6.python-quiz-for-beginner
复习
虚拟环境
- 创建python虚拟环境 (windows平台)
C:\python\python3.10\python.exe -m venv my_venv # my_venv:任意命名,虚拟环境变量名
激活python虚拟环境变量
my_venv\scripts\activate.bat
在虚拟环境里面安装python包
pip install xxx -i https://pypi.tuna.tsinghua.edu.cn/simple # 指定使用国内清华源
notebook in VS Code
实战练习
- 赛车 cargame.zip
- 一些pattern demo python sample code
简单练习
鸡兔同笼程序
def calculate_chicken_rabbit(heads, legs):
"""
Calculates the number of chickens and rabbits given the total number of heads and legs.
Args:
heads (int): Total number of heads.
legs (int): Total number of legs.
Returns:
tuple: A tuple containing the number of chickens and rabbits, respectively. Returns (-1, -1) if no solution is possible.
"""
for chickens in range(heads + 1):
rabbits = heads - chickens
if (2 * chickens) + (4 * rabbits) == legs:
return chickens, rabbits
return -1, -1
# Test the function
total_heads = int(input("Enter the total number of heads: "))
total_legs = int(input("Enter the total number of legs: "))
chickens, rabbits = calculate_chicken_rabbit(total_heads, total_legs)
if chickens == -1 and rabbits == -1:
print("No solution possible.")
else:
print("Number of chickens:", chickens)
print("Number of rabbits:", rabbits)
'''
example 1:
Enter the total number of heads: 5
Enter the total number of legs: 14
Number of chickens: 3
Number of rabbits: 2
'''
'''
example 2:
Enter the total number of heads: 3
Enter the total number of legs: 8
Number of chickens: 2
Number of rabbits: 1
'''
'''
example 3
Enter the total number of heads: 2
Enter the total number of legs: 10
No solution possible.
'''
汇率转换程序
- API使用,获取汇率信息
简单的计算,转换
参考代码import requests
import json
url = 'http://data.fixer.io/api/latest?access_key=***267b3317dd4ef8af6760ac3c38c9b'
response = requests.get(url)
print(response.text)
json_object = json.loads(response.text)
print(f"base currency: {json_object['base']}")
print(f"to CNY rate: {json_object['rates']['CNY']}")
print(f"to USD rate: {json_object['rates']['USD']}")
汇率API,网上有很多免费的API,一般都需要注册一下,获取一个API key,然后根据API文档组合request url,访问服务器,获取返回数据,一般以json格式构成,如:
url: http://data.fixer.io/api/latest?access_key=***267b3317dd4ef8af6760ac3c38c9b
返回的结果, response.text
{
"success": true,
"timestamp": 1519296206,
"base": "EUR",
"date": "2023-07-09",
"rates": {
"AUD": 1.566015,
"CAD": 1.560132,
"CHF": 1.154727,
"CNY": 7.827874,
"GBP": 0.882047,
"JPY": 132.360679,
"USD": 1.23396,
[...]
}
}
将字符串转换为json object
json_object = json.loads(response.text)
访问对应的字段,比如基础货币,人民币,美元对应的汇率
print(f"base currency: {json_object['base']}")
print(f"to CNY rate: {json_object['rates']['CNY']}")
print(f"to USD rate: {json_object['rates']['USD']}")
剩下的就是简单计算,基于这些信息,可以编写一个实时计算汇率转换的程序