python新手练习代码
时间: 2023-09-07 16:17:54 浏览: 62
以下是一些适合Python新手练习的代码:
1. 打印“Hello, World!”
```
print("Hello, World!")
```
2. 计算两个数的和
```
num1 = 6
num2 = 4
sum = num1 + num2
print("The sum of", num1, "and", num2, "is", sum)
```
3. 判断一个数是否为偶数
```
num = 8
if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd")
```
4. 将一个字符串反转
```
str = "hello world"
reverse_str = str[::-1]
print("The reverse of", str, "is", reverse_str)
```
5. 计算一个列表中所有数字的平均值
```
nums = [1, 3, 5, 7, 9]
avg = sum(nums) / len(nums)
print("The average of", nums, "is", avg)
```
6. 判断一个字符串是否为回文
```
str = "racecar"
reverse_str = str[::-1]
if str == reverse_str:
print(str, "is a palindrome")
else:
print(str, "is not a palindrome")
```
7. 将一个列表中的数字按照从小到大排序
```
nums = [5, 2, 8, 1, 9]
nums.sort()
print("The sorted list is", nums)
```
8. 统计一个字符串中每个字符出现的次数
```
str = "hello world"
count = {}
for char in str:
if char in count:
count[char] += 1
else:
count[char] = 1
print("The count of each character in", str, "is", count)
```
9. 打印九九乘法表
```
for i in range(1, 10):
for j in range(1, i+1):
print(j, "*", i, "=", i*j, end="\t")
print()
```
10. 判断一个数是否为质数
```
num = 7
if num > 1:
for i in range(2, int(num/2)+1):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
```
相关推荐
![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_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)