python条件语句和循环语句练习
时间: 2023-11-17 14:03:44 浏览: 121
python 中循环语句及if语句的简单练习和答案.pdf
以下是Python条件语句和循环语句的练习:
1. if语句
```python
# 判断一个数是否为偶数
num = 6
if num % 2 == 0:
print(num, "是偶数")
else:
print(num, "是奇数")
```
2. for循环
```python
# 计算列表中所有元素的和
lst = [1, 2, 3, 4, 5]
sum = 0
for num in lst:
sum += num
print("列表", lst, "中所有元素的和为:", sum)
```
3. while循环
```python
# 计算1到100的和
i = 1
sum = 0
while i <= 100:
sum += i
i += 1
print("1到100的和为:", sum)
```
4. break语句
```python
# 找到列表中第一个负数并输出
lst = [1, 2, -3, 4, -5]
for num in lst:
if num < 0:
print("列表", lst, "中第一个负数为:", num)
break
```
5. continue语句
```python
# 输出1到10中所有的奇数
for i in range(1, 11):
if i % 2 == 0:
continue
print(i, end=" ")
```
阅读全文