python自定义函数加多条件判断
时间: 2023-06-18 08:08:41 浏览: 110
你可以在Python自定义函数中加入多个条件判断语句,以根据不同的情况执行不同的代码。例如:
```python
def my_function(x):
if x > 10:
print("x is greater than 10")
elif x < 0:
print("x is negative")
else:
print("x is between 0 and 10")
```
在上面的代码中,如果传入的参数x大于10,就会执行第一个条件判断语句;如果x小于0,就会执行第二个条件判断语句;否则就会执行最后一个else语句。
你还可以在条件判断语句中使用逻辑运算符来组合多个条件,例如:
```python
def my_function(x, y):
if x > 0 and y > 0:
print("Both x and y are positive")
elif x > 0 or y > 0:
print("At least one of x and y is positive")
else:
print("Both x and y are non-positive")
```
在上面的代码中,第一个条件判断语句使用了and运算符,表示只有当x和y都大于0时才会执行;第二个条件判断语句使用了or运算符,表示只要x和y中有一个大于0就会执行。最后一个else语句则表示x和y都不大于0。
相关问题
python自定义函数判断闰年
以下是一个用于判断闰年的自定义函数的例子:
```python
def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
return True
else:
return False
year = int(input("请输入年份:"))
print(is_leap_year(year))
```
这个函数接受一个年份作为参数,然后根据以下规则判断是否为闰年:
- 如果年份能够被4整除,但不能被100整除,或者能够被400整除,那么就是闰年。
- 否则,不是闰年。
你可以输入一个年份来测试这个函数,它会返回True或False来表示是否为闰年。
python自定义函数判断素数
判断素数的函数可以自定义实现,以下是一个示例代码:
```python
def isPrime(x):
"""
判断一个数是否为素数
"""
if x < 2:
return False
for i in range(2, int(x ** 0.5) + 1):
if x % i == 0:
return False
return True
```
该函数接受一个整数参数x,如果x小于2,则返回False;否则,从2到x的平方根范围内遍历,如果存在一个数能够整除x,则返回False,否则返回True。
下面是一个示例代码,用于判断m-n之间有几个素数,并输出结果:
```python
def countPrimes(m, n):
"""
判断m-n之间有几个素数,输出结果
"""
if m > n:
m, n = n, m
count = 0
for i in range(m, n + 1):
try:
if isPrime(i):
print(i, "是素数")
count += 1
else:
print(i, "不是素数")
except:
print(i, "输入错误")
print("在", m, "和", n, "之间有", count, "个素数")
# 示例调用
countPrimes(1, 20)
```
该函数接受两个整数参数m和n,如果m大于n,则交换两个参数的值。然后,遍历m到n之间的所有整数,对于每个整数,调用isPrime函数判断是否为素数,并输出结果。如果输入的整数无法转换为整型,则输出输入错误。最后,输出在m和n之间有多少个素数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)