Share 3 python programs

minhvuong463

New member
### 3 Python Programs for Beginners

**1. A simple calculator**

This is a great first program to write in Python. It will allow you to add, subtract, multiply, and divide numbers. Here is the code:

```python
def add(a, b):
return a + b

def subtract(a, b):
return a - b

def multiply(a, b):
return a * b

def divide(a, b):
return a / b

# Get the numbers from the user
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

# Add the numbers
sum = add(num1, num2)
print("The sum of the numbers is", sum)

# Subtract the numbers
diff = subtract(num1, num2)
print("The difference of the numbers is", diff)

# Multiply the numbers
product = multiply(num1, num2)
print("The product of the numbers is", product)

# Divide the numbers
quotient = divide(num1, num2)
print("The quotient of the numbers is", quotient)
```

**2. A guessing game**

This program will allow the user to guess a number between 1 and 100. The program will give the user hints as to whether the number is too high or too low. Here is the code:

```python
import random

# Generate a random number
number = random.randint(1, 100)

# Get the user's guess
guess = int(input("Guess a number between 1 and 100: "))

# Check if the guess is correct
while guess != number:
if guess < number:
print("Your guess is too low.")
else:
print("Your guess is too high.")

# Get the user's new guess
guess = int(input("Guess again: "))

# Print a message if the user guessed correctly
print("You guessed the number!")
```

**3. A text adventure game**

This program will allow the user to explore a text-based world and interact with objects and characters. Here is the code:

```python
import sys

# Define the world
world = {
"START": {
"description": "You are standing in a forest. There is a path to the north and a river to the south.",
"exits": {"north": "PATH", "south": "RIVER"}
},
"PATH": {
"description": "You are on a path in the forest. There is a cave to the east and a clearing to the west.",
"exits": {"east": "CAVE", "west": "CLEARING"}
},
"CAVE": {
"description": "You are in a cave. There is a fire burning in the center of the cave.",
"exits": {"east": "PATH"}
},
"CLEARING": {
"description": "You are in a clearing in the forest. There is a tree in the center of the clearing.",
"exits": {"east": "PATH"}
}
}

# Define the player
player = {
"name": "Mia",
"location": "START",
"inventory": []
}

# Define the game loop
while True:
# Print the description of the player's current location
print(world[player["location"]]["description"])

# Print the available exits
print("Available exits:")
for exit in world[player["location"]]["exits"]:
print(exit)

# Get the player's next move
move = input("What do you want to do? ")

# Move the player to the new location
if move
 
Join Telegram ToolsKiemTrieuDoGroup
Back
Top