python 代码 例子
标题:Python代码示例
1. 计算两个数的和
```python
a = 10
b = 5
c = a + b
print("两个数的和为:", c)
```
2. 判断一个数是否为奇数
```python
num = 7
if num % 2 == 0:
    print(num, "是偶数")
else:
    print(num, "是奇数")
```
3. 出列表中的最大值
```python
numbers = [10, 5, 8, 15, 3]
max_num = max(numbers)
print("列表中的最大值是:", max_num)
```
4. 判断一个字符串是否为回文字符串
```python
def is_palindrome(word):
    reversed_word = word[::-1]
    if word == reversed_word:
        return True
    else:
        return False
word = "level"
if is_palindrome(word):
    print(word, "是回文字符串")
else:
    print(word, "不是回文字符串")
```
5. 计算圆的面积
```python
import math
radius = 5
area = math.pi * radius ** 2
print("圆的面积为:", area)
```
6. 判断一个年份是否为闰年
```python
year = 2020
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
    print(year, "是闰年")
else:
    print(year, "不是闰年")
```
7. 实现字符串的反转
```python
def reverse_string(word):
    reversed_word = word[::-1]
    return reversed_word
word = "Hello World!"
reversed_word = reverse_string(word)
print("反转后的字符串为:", reversed_word)
```
8. 将列表中的元素按照从大到小的顺序排序
```python
numbers = [10, 5, 8, 15, 3]
sorted_numbers = sorted(numbers, reverse=True)
print("排序后的列表为:", sorted_numbers)
```
9. 计算斐波那契数列的第n项
```python
def fibonacci(n):
    if n <= 0:
        return []
    elif n == 1:
        return [0]
    elif n == 2:
        return [0, 1]
    else:
        fib = [0, 1]
        for i in range(2, n):
            fib.append(fib[i-1] + fib[i-2])
        return fib
n = 10
fibonacci_sequence = fibonacci(n)
print("斐波那契数列的前", n, "项为:", fibonacci_sequence)
```
10. 判断一个数是否为质数
```pythonpython新手代码例子
def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            return False

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。