初学编程100个代码大全python

打印"Hello, World!":

python
print("Hello, World!")

计算两个数字的和:

python
num1 = 5 num2 = 3 sum = num1 + num2 print("The sum is:", sum)

计算两个数字的乘积:

python
num1 = 5 num2 = 3 product = num1 * num2 print("The product is:", product)

判断一个数是奇数还是偶数:

python
num = 6 if num % 2 == 0: print(num, "is even.") else: print(num, "is odd.")

判断一个年份是否是闰年:

python
year = 2024 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): print(year, "is a leap year.") else: print(year, "is not a leap year.")

计算斐波那契数列:

python
def fibonacci(n): if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n-2) nterms = 10 if nterms <= 0: print("Please enter a positive integer") else: print("Fibonacci sequence:") for i in range(nterms): print(fibonacci(i))

计算阶乘:

python
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) num = 5 print("Factorial of", num, "is", factorial(num))

检查一个数字是否为素数:

python
def is_prime(num): if num <= 1: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True num = 17 if is_prime(num): print(num, "is a prime number.") else: print(num, "is not a prime number.")

这些示例可以帮助你开始练习Python编程。你可以尝试编写这些代码,并根据需要进行修改和扩展。

反转字符串:

python
string = "hello" reversed_string = string[::-1] print("Reversed string:", reversed_string)

计算列表中的最大值和最小值:

python
numbers = [3, 7, 2, 9, 5] print("Maximum number:", max(numbers)) print("Minimum number:", min(numbers))

求一个列表的平均值:

python
numbers = [3, 7, 2, 9, 5] average = sum(numbers) / len(numbers) print("Average:", average)

检查一个字符串是否是回文字符串:

python
def is_palindrome(s): return s == s[::-1] string = "radar" if is_palindrome(string): print(string, "is a palindrome.") else: print(string, "is not a palindrome.")

打印九九乘法表:

python
for i in range(1, 10): for j in range(1, i+1): print(i * j, end="\t") print()

实现冒泡排序算法:

python
def bubble_sort(arr): n = len(arr) for i in range(n-1): for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] arr = [64, 34, 25, 12, 22, 11, 90] bubble_sort(arr) print("Sorted array:", arr)

实现二分查找算法:

python
def binary_search(arr, target): low, high = 0, len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == target: return mid elif arr[mid] < target: low = mid + 1 else: high = mid - 1 return -1 arr = [2, 3, 4, 10, 40] target = 10 result = binary_search(arr, target) if result != -1: print("Element is present at index", result) else: print("Element is not present in array")

这些示例可以帮助你建立起对Python编程的基础,并为你提供了实践各种编程概念的机会。