python if else用法小案例
时间: 2024-02-26 13:50:33 浏览: 41
当然可以!下面是一个简单的Python if else的小案例:
```python
# 用户输入一个数字
num = int(input("请输入一个数字:"))
# 使用if else语句判断数字的正负性
if num > 0:
print("输入的数字是正数")
elif num < 0:
print("输入的数字是负数")
else:
print("输入的数字是零")
```
在这个案例中,我们首先通过`input()`函数获取用户输入的数字,并将其转换为整数类型。然后,使用if else语句对数字进行判断。如果数字大于0,则打印"输入的数字是正数";如果数字小于0,则打印"输入的数字是负数";如果数字等于0,则打印"输入的数字是零"。
这个案例展示了如何使用if else语句根据条件执行不同的代码块,根据用户输入的数字判断其正负性。
相关问题
策略模式替代if else 案例
以下是一个简单的示例,说明如何使用策略模式来替代if else语句:
假设我们现在有一个计算器程序,能够对两个数字进行加、减、乘、除四种运算。如果我们使用if else语句来实现这个程序,代码可能如下所示:
```python
class Calculator:
def calculate(self, operation, num1, num2):
if operation == "add":
return num1 + num2
elif operation == "subtract":
return num1 - num2
elif operation == "multiply":
return num1 * num2
elif operation == "divide":
return num1 / num2
```
在这个代码中,我们使用了if else语句来根据不同的运算符执行不同的操作。如果我们想要添加更多的运算符,就需要修改calculate方法中的if else语句,这会导致代码变得越来越复杂和难以维护。
现在,我们可以使用策略模式来重构这个代码。首先,我们定义一个抽象的运算策略接口:
```python
class OperationStrategy:
def execute(self, num1, num2):
pass
```
然后,我们定义具体的加、减、乘、除策略类,它们都实现了这个接口:
```python
class AddStrategy(OperationStrategy):
def execute(self, num1, num2):
return num1 + num2
class SubtractStrategy(OperationStrategy):
def execute(self, num1, num2):
return num1 - num2
class MultiplyStrategy(OperationStrategy):
def execute(self, num1, num2):
return num1 * num2
class DivideStrategy(OperationStrategy):
def execute(self, num1, num2):
return num1 / num2
```
最后,在计算器类中,我们使用一个字典来存储不同运算符对应的策略对象,然后根据运算符从字典中获取对应的策略对象,从而执行相应的计算操作:
```python
class Calculator:
def __init__(self):
self.strategies = {
"add": AddStrategy(),
"subtract": SubtractStrategy(),
"multiply": MultiplyStrategy(),
"divide": DivideStrategy()
}
def calculate(self, operation, num1, num2):
strategy = self.strategies.get(operation)
if strategy is None:
raise ValueError("Invalid operation")
return strategy.execute(num1, num2)
```
在这个代码中,我们使用字典来将运算符与对应的策略对象进行映射。当需要添加新的运算符时,我们只需要添加一个新的策略类,并在字典中添加对应的映射关系即可,而不需要修改calculate方法。这样就避免了使用if else语句来处理不同的运算符,提高了代码的可读性、可维护性和可扩展性。
python requests 使用案例
### 回答1:
Python的requests库是一个非常流行的HTTP请求库,可以用于向Web服务器发送请求和获取响应。以下是一些常见的requests使用案例:
1. 发送GET请求
```python
import requests
response = requests.get('http://www.example.com')
print(response.text)
```
2. 发送POST请求
```python
import requests
data = {'username': 'user123', 'password': '123456'}
response = requests.post('http://www.example.com/login', data=data)
print(response.text)
```
3. 发送带有头部信息的请求
```python
import requests
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.36'}
response = requests.get('http://www.example.com', headers=headers)
print(response.text)
```
4. 发送带有查询参数的请求
```python
import requests
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('http://www.example.com', params=params)
print(response.url)
```
5. 发送带有Cookies的请求
```python
import requests
cookies = {'cookie1': 'value1', 'cookie2': 'value2'}
response = requests.get('http://www.example.com', cookies=cookies)
print(response.text)
```
这些只是requests库的一些常见用例,它可以用于处理各种HTTP请求和响应,例如处理文件上传、会话管理、代理设置等。
### 回答2:
Python的Requests库是一个常用的HTTP库,可以发送HTTP请求并处理响应结果。下面是一个使用Python的Requests库的案例:
案例:使用Requests库发送GET请求并获取服务器响应数据
```python
import requests
# 发送GET请求
response = requests.get('https://api.example.com/users')
# 获取响应结果
if response.status_code == 200:
# 请求成功
data = response.json()
for user in data:
print(f"用户名:{user['name']},年龄:{user['age']}")
else:
# 请求失败
print(f"请求失败,状态码:{response.status_code}")
```
在这个案例中,我们首先导入了`requests`模块。然后,我们使用`get()`方法发送了一个GET请求到`https://api.example.com/users`这个URL,并将响应结果保存在`response`变量中。
接下来,我们判断了响应的状态码是否为200。如果是200,表示请求成功,我们调用`json()`方法将响应结果转换为JSON格式的字典,并遍历输出了每个用户的用户名和年龄。
如果状态码不是200,表示请求失败,我们打印出请求失败的状态码。
通过这个案例,我们可以看到,在Python中使用Requests库发送HTTP请求非常简单。只需要调用`get()`、`post()`等方法,并传递URL和请求参数,就可以发送请求并获取服务器的响应数据。我们还可以通过处理响应的状态码和内容,根据需要来处理和操作数据。
### 回答3:
Python的requests库是一个用于发送HTTP请求的强大工具。它提供了简单且直观的方法来与Web进行交互,如发送GET和POST请求、处理请求的响应、设置请求Headers和Cookies等。
下面是一个使用requests库的简单示例:
```python
import requests
# 发送GET请求
response = requests.get("https://api.github.com")
# 打印响应内容的文本形式
print(response.text)
# 打印响应的状态码
print(response.status_code)
# 发送带参数的GET请求
params = {"key": "value"}
response = requests.get("https://api.example.com", params=params)
# 发送POST请求
data = {"key": "value"}
response = requests.post("https://api.example.com", data=data)
# 设置请求Headers
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get("https://api.example.com", headers=headers)
# 设置请求Cookies
cookies = {"key": "value"}
response = requests.get("https://api.example.com", cookies=cookies)
# 处理异常
try:
response = requests.get("https://api.example.com")
response.raise_for_status() # 抛出HTTPError异常
except requests.exceptions.HTTPError as e:
print("HTTP Error:", e)
except requests.exceptions.RequestException as e:
print("Error:", e)
```
上面的示例展示了requests库的常见用法。我们可以发送GET和POST请求,并处理请求的响应。还可以设置请求Headers和Cookies,以及处理异常情况。requests库的优势在于其简洁的API和丰富的功能,使得与Web进行交互变得轻松而便捷。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)