python经典代码
下面是一些经典的Python代码示例:
1. Hello World程序:
```python
print("Hello, World!"```
2. 计算两个数的和:
```python
a = 5
b = 10
sum = a + b
print("The sum is:" sum)
```
3. 判断一个数是否为素数:
```python
num = int(input("Enter a number: "is_prime = True
if num > 1:
for i in range(2, num):
if (num % i) == 0:
is_prime = False
break
if is_pri
print(num, "is a prime number"else:
print(num, "is not a prime number"```
4. 反转字符串:
```python
string = input("Enter a string: "reversed_string = string[::-1]
print("Reversed string:" reversed_string)
```
5. 斐波那契数列:
```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[-1] + fib[-2])
return fib
num_terms = int(input("Enter the number of terms: "fib_sequence = fibonacci(num_terms)
print("Fibonacci sequence:" fib_sequence)python新手代码示例
```
这些代码示例包括了常见的Hello World程序、数学计算、判断、字符串处理和递归等方面的经典代码。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论