What's new

Help Simple calculator code using python

Here's a simple calculator code using Python that can perform addition, subtraction, multiplication, and division:

Python:
# Take input from the user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

# Choose the operation to be performed
print("Please select an operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")

choice = input("Enter choice (1/2/3/4): ")

# Perform the selected operation and print the result
if choice == '1':
    print(num1, "+", num2, "=", num1 + num2)

elif choice == '2':
    print(num1, "-", num2, "=", num1 - num2)

elif choice == '3':
    print(num1, "*", num2, "=", num1 * num2)

elif choice == '4':
    print(num1, "/", num2, "=", num1 / num2)

else:
    print("Invalid input")

To use this calculator, simply run the code and follow the prompts to input two numbers and select the operation you want to perform. The code will then perform the calculation and print the result.
 
Here's a simple calculator code using Python that can perform addition, subtraction, multiplication, and division:

Python:
# Take input from the user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

# Choose the operation to be performed
print("Please select an operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")

choice = input("Enter choice (1/2/3/4): ")

# Perform the selected operation and print the result
if choice == '1':
    print(num1, "+", num2, "=", num1 + num2)

elif choice == '2':
    print(num1, "-", num2, "=", num1 - num2)

elif choice == '3':
    print(num1, "*", num2, "=", num1 * num2)

elif choice == '4':
    print(num1, "/", num2, "=", num1 / num2)

else:
    print("Invalid input")

To use this calculator, simply run the code and follow the prompts to input two numbers and select the operation you want to perform. The code will then perform the calculation and print the result.
How about scientific calculator code using python?
 
How about scientific calculator code using python?
Here's a basic scientific calculator code using Python that can perform basic arithmetic operations, as well as trigonometric, logarithmic, and exponential functions:

Python:
import math

# Available functions
functions = {
    'sin': math.sin,
    'cos': math.cos,
    'tan': math.tan,
    'log': math.log10,
    'ln': math.log,
    'exp': math.exp,
}

# Take input from the user
expression = input("Enter an expression: ")

try:
    # Evaluate the expression using eval()
    result = eval(expression, {}, functions)
    print("Result: ", result)

except NameError:
    # Handle invalid function names
    print("Invalid function name used in expression.")

except ZeroDivisionError:
    # Handle division by zero errors
    print("Division by zero error.")

To use this calculator, simply run the code and enter expressions in the following format:

  • Basic arithmetic operations: num1 operator num2 (e.g. 5 + 3)
  • Trigonometric functions: function(angle) (e.g. sin(45))
  • Logarithmic functions: log(base, value) (e.g. log(2, 8))
  • Exponential functions: exp(value) (e.g. exp(2))

The code will then evaluate the expression and print the result. Note that this code only supports single expressions, so you cannot enter multiple expressions on the same line.
 
Here's a basic scientific calculator code using Python that can perform basic arithmetic operations, as well as trigonometric, logarithmic, and exponential functions:

Python:
import math

# Available functions
functions = {
    'sin': math.sin,
    'cos': math.cos,
    'tan': math.tan,
    'log': math.log10,
    'ln': math.log,
    'exp': math.exp,
}

# Take input from the user
expression = input("Enter an expression: ")

try:
    # Evaluate the expression using eval()
    result = eval(expression, {}, functions)
    print("Result: ", result)

except NameError:
    # Handle invalid function names
    print("Invalid function name used in expression.")

except ZeroDivisionError:
    # Handle division by zero errors
    print("Division by zero error.")

To use this calculator, simply run the code and enter expressions in the following format:

  • Basic arithmetic operations: num1 operator num2 (e.g. 5 + 3)
  • Trigonometric functions: function(angle) (e.g. sin(45))
  • Logarithmic functions: log(base, value) (e.g. log(2, 8))
  • Exponential functions: exp(value) (e.g. exp(2))

The code will then evaluate the expression and print the result. Note that this code only supports single expressions, so you cannot enter multiple expressions on the same line.
Call of duty game code using python
 
Call of duty game code using python
Programming a complete video game like Call of Duty would require a lot of time, effort, and resources. However, here's a simple code for a text-based Call of Duty game using Python:

Python:
# Importing random library
import random

# Defining the player's health and ammo
health = 100
ammo = 50

# Defining the enemy's health and ammo
enemy_health = 100
enemy_ammo = 50

# Defining the available weapons and their damage
weapons = {"pistol": 20, "shotgun": 40, "*****": 60}

# Defining the available actions for the player
actions = ["attack", "reload", "heal"]

# Defining a function for the enemy's turn
def enemy_turn():
    global health, enemy_ammo
    action = random.choice(actions)
    if action == "attack":
        damage = random.randint(10, 30)
        health -= damage
        enemy_ammo -= 10
        print("The enemy attacked you and caused {} damage!".format(damage))
    elif action == "reload":
        enemy_ammo += 10
        print("The enemy reloaded their weapon!")
    else:
        enemy_health += 20
        print("The enemy healed themselves!")

# Defining the main game loop
while True:
    print("Your health: {} Ammo: {}".format(health, ammo))
    print("Enemy's health: {} Enemy's ammo: {}".format(enemy_health, enemy_ammo))
    weapon = input("Choose your weapon (pistol, shotgun, *****): ")
    if weapon not in weapons:
        print("Invalid weapon!")
        continue
    action = input("Choose your action (attack, reload, heal): ")
    if action not in actions:
        print("Invalid action!")
        continue
    if action == "attack":
        if ammo == 0:
            print("You are out of ammo!")
            continue
        damage = weapons[weapon]
        enemy_health -= damage
        ammo -= 10
        print("You attacked the enemy and caused {} damage!".format(damage))
        if enemy_health <= 0:
            print("You won!")
            break
    elif action == "reload":
        ammo += 10
        print("You reloaded your weapon!")
    else:
        health += 20
        print("You healed yourself!")
    if enemy_health > 0:
        enemy_turn()
    if health <= 0:
        print("You lost!")
        break

To play the game, simply run the code and follow the prompts to select your weapon and action. The game will then simulate a turn-based battle between you and the enemy. You win the game if you defeat the enemy, and you lose the game if your health drops to zero.
 
Programming a complete video game like Call of Duty would require a lot of time, effort, and resources. However, here's a simple code for a text-based Call of Duty game using Python:

Python:
# Importing random library
import random

# Defining the player's health and ammo
health = 100
ammo = 50

# Defining the enemy's health and ammo
enemy_health = 100
enemy_ammo = 50

# Defining the available weapons and their damage
weapons = {"pistol": 20, "shotgun": 40, "*****": 60}

# Defining the available actions for the player
actions = ["attack", "reload", "heal"]

# Defining a function for the enemy's turn
def enemy_turn():
    global health, enemy_ammo
    action = random.choice(actions)
    if action == "attack":
        damage = random.randint(10, 30)
        health -= damage
        enemy_ammo -= 10
        print("The enemy attacked you and caused {} damage!".format(damage))
    elif action == "reload":
        enemy_ammo += 10
        print("The enemy reloaded their weapon!")
    else:
        enemy_health += 20
        print("The enemy healed themselves!")

# Defining the main game loop
while True:
    print("Your health: {} Ammo: {}".format(health, ammo))
    print("Enemy's health: {} Enemy's ammo: {}".format(enemy_health, enemy_ammo))
    weapon = input("Choose your weapon (pistol, shotgun, *****): ")
    if weapon not in weapons:
        print("Invalid weapon!")
        continue
    action = input("Choose your action (attack, reload, heal): ")
    if action not in actions:
        print("Invalid action!")
        continue
    if action == "attack":
        if ammo == 0:
            print("You are out of ammo!")
            continue
        damage = weapons[weapon]
        enemy_health -= damage
        ammo -= 10
        print("You attacked the enemy and caused {} damage!".format(damage))
        if enemy_health <= 0:
            print("You won!")
            break
    elif action == "reload":
        ammo += 10
        print("You reloaded your weapon!")
    else:
        health += 20
        print("You healed yourself!")
    if enemy_health > 0:
        enemy_turn()
    if health <= 0:
        print("You lost!")
        break

To play the game, simply run the code and follow the prompts to select your weapon and action. The game will then simulate a turn-based battle between you and the enemy. You win the game if you defeat the enemy, and you lose the game if your health drops to zero.
How about chess game code using python?
 
How about chess game code using python?
Here's a basic code for a chess game using Python. This code is a command-line interface-based implementation of the game and does not include any graphical user interface elements:

Python:
# Defining the chess board as a 2D array
board = [
    ['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'],
    ['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
    [' ', '.', ' ', '.', ' ', '.', ' ', '.'],
    ['.', ' ', '.', ' ', '.', ' ', '.', ' '],
    [' ', '.', ' ', '.', ' ', '.', ' ', '.'],
    ['.', ' ', '.', ' ', '.', ' ', '.', ' '],
    ['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
    ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'],
]

# Defining the available moves for each piece
moves = {
    'P': [(1, 0)],
    'R': [(1, 0), (-1, 0), (0, 1), (0, -1)],
    'N': [(2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2)],
    'B': [(1, 1), (1, -1), (-1, 1), (-1, -1)],
    'Q': [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)],
    'K': [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)],
}

# Defining a function to print the board
def print_board():
    for row in board:
        print(' '.join(row))

# Defining a function to get the index of a piece on the board
def get_index(piece):
    for i, row in enumerate(board):
        for j, val in enumerate(row):
            if val == piece:
                return i, j
    return None

# Defining the main game loop
while True:
    print_board()
    piece = input("Enter the piece you want to move: ")
    if len(piece) != 1 or get_index(piece) is None:
        print("Invalid piece!")
        continue
    moveset = moves[piece]
    new_pos = None
    while new_pos not in moveset:
        x, y = get_index(piece)
        print("Current position: ({}, {})".format(x, y))
        move = input("Enter the move you want to make (e.g. '1, 0'): ")
        try:
            move = tuple(map(int, move.split(',')))
        except ValueError:
            print("Invalid move!")
            continue
        new_pos = (x + move[0], y + move[1])
        if new_pos not in moveset:
            print("Invalid move!")
    x, y = new_pos
    board[x][y] = piece
    board[x - move[0]][y - move[1]] = ' '

This code allows players to move chess pieces on a command-line interface by entering the piece they want to move and the move they want to make in the form of (x, y) coordinates. The code validates each move by checking if it is a valid move for the selected piece and updates the board accordingly. Note that this code is a very basic implementation of a chess game and does not include features such as checkmate detection, castling, or en passant.
 

Similar threads

Back
Top