本篇文章给大家谈谈70个python练手项目 网盘,以及python简单易懂的小程序,希望对各位有所帮助,不要忘了收藏本站喔。
Python是一种广泛使用的编程语言,它简单易学,适合初学者入门。在这篇文章中,我将分享10个适合入门学习的Python小程序,希望帮助初学者更好地掌握这门语言python画雪人。
-
打印 Hello World:
print("Hello, World!")
-
计算器:
num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) result = num1 + num2 print("Sum:", result)
-
猜数字游戏:
import random target_number = random.randint(1, 100) guess = int(input("Guess the number between 1 and 100: ")) if guess == target_number: print("Congratulations! You guessed the correct number.") else: print("Sorry, the correct number was:", target_number)
-
字符串反转:
original_string = input("Enter a string: ") reversed_string = original_string[::-1] print("Reversed string:", reversed_string)
-
温度转换:
temperature_celsius = float(input("Enter temperature in Celsius: ")) temperature_fahrenheit = (temperature_celsius * 9/5) + 32 print("Temperature in Fahrenheit:", temperature_fahrenheit)
-
列表操作:
my_list = [1, 2, 3, 4, 5] doubled_list = [x * 2 for x in my_list] print("Original list:", my_list) print("Doubled list:", doubled_list)
-
求解二次方程:
import math a = float(input("Enter the coefficient a: ")) b = float(input("Enter the coefficient b: ")) c = float(input("Enter the coefficient c: ")) discriminant = b**2 - 4*a*c if discriminant > 0: x1 = (-b + math.sqrt(discriminant)) / (2*a) x2 = (-b - math.sqrt(discriminant)) / (2*a) print("Roots are real and different. x1 =", x1, "x2 =", x2) elif discriminant == 0: x = -b / (2*a) print("Roots are real and the same. x =", x) else: real_part = -b / (2*a) imaginary_part = math.sqrt(abs(discriminant)) / (2*a) print("Roots are complex. x1 =", real_part, "+", imaginary_part, "i, x2 =", real_part, "-", imaginary_part, "i")
-
文件读写:
with open("example.txt", "w") as file: file.write("Hello, this is an example.") with open("example.txt", "r") as file: content = file.read() print("File content:", content)
-
简单的类和对象:
class Dog: def __init__(self, name, age): self.name = name self.age = age def bark(self): print("Woof!") my_dog = Dog("Buddy", 3) print("My dog's name is", my_dog.name, "and age is", my_dog.age) my_dog.bark()
-
基本的异常处理:
try: num1 = int(input("Enter a number: ")) num2 = int(input("Enter another number: ")) result = num1 / num2 print("Result:", result) except ValueError: print("Please enter valid numbers.") except ZeroDivisionError: print("Cannot divide by zero.") except Exception as e: print("An error occurred:", e)
这些简单的小程序覆盖了一些基本的 Python 概念,包括输入输出、条件语句、循环、列表操作、文件读写、异常处理等。通过编写这些小程序,你可以逐步熟悉 Python 的语法和功能。