python100例
Python是一种简单易学的编程语言,被广泛应用于各种领域,如Web开发、数据分析、人工智能等。为了帮助大家更好地掌握Python编程,今天我将为大家分享100个Python编程实例,希望能给大家一个全面的了解和实践的机会。
1. 打印"Hello
World!"
```python
print("Hello
World!")
```
2. 计算两个数的和
```python
a = 2
b = 3
sum = a + b
print("The sum of a and b is:"
sum)
```
3. 判断一个数是偶数还是奇数
```python
num = 4
if num % 2 == 0:
print(num
"is even")
else:
print(num
"is odd")
```
4. 计算一个数的阶乘
```python
num = 5
factorial = 1
for i in range(1
num + 1):
factorial *= i
print("The factorial of"
num
"is:"
factorial)
```
5. 判断一个数是否为质数
```python
num = 7
is_prime = True
for i in range(2
num):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num
"is a prime number")
else:
print(num
"is not a prime number")
```
6. 翻转一个字符串
```python
s = "hello"
reversed_s = s[::-1]
print("The reversed string is:"
reversed_s)
```
7. 找出一个列表中的*值和最小值
```python
nums = [1
3
5
7
9]
max_num = max(nums)
min_num = min(nums)
print("The maximum number is:"
max_num)
print("The minimum number is:"
min_num)
```
8. 计算两个列表的交集
```python
list1 = [1
2
3
4
5]
list2 = [4
5
6
7
8]
intersection = list(set(list1) & set(list2))
print("The intersection of list1 and list2 is:"
intersection)
```
9. 将一个字符串中的字符按照字母顺序排列
```python
s = "cbade"
sorted_s = ''.join(sorted(s))
print("The sorted string is:"
sorted_s)
```
10. 计算斐波那契数列的前n项
```python
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
n = 5
fibonacci_seq = [fibonacci(i) for i in range(n)]
print("The Fibonacci sequence of"
n
"terms is:"
fibonacci_seq)
```
这些实例只是Python编程的冰山一角,通过练习这些实例,你可以逐步提升自己的编程能力,掌握更多Python编程的技巧和应用。希望大家能够坚持练习,不断提升自己的编程水平,让Python成为你的得力工具!