CODES For Long Weekend

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

The following is code for a regular calculation machine

# This function adds two numbers


def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
# check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
# check if user wants another calculation
# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")

The following are the codes for TIC TAC TOE game
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)
def check_winner(board):
for row in board:
if row.count(row[0]) == len(row) and row[0] != ' ':
return True
for col in range(len(board[0])):
if board[0][col] == board[1][col] == board[2][col] and board[0][col] != ' ':
return True
if board[0][0] == board[1][1] == board[2][2] and board[0][0] != ' ':
return True
if board[0][2] == board[1][1] == board[2][0] and board[0][2] != ' ':
return True
return False
def is_board_full(board):
for row in board:
if ' ' in row:
return False
return True
def tic_tac_toe():
board = [[' ' for _ in range(3)] for _ in range(3)]
player = 'X'
while True:
print_board(board)
try:
row = int(input(f"Player {player}, enter row number (0, 1, 2): "))
col = int(input(f"Player {player}, enter column number (0, 1, 2): "))
except ValueError:
print("Invalid input! Please enter a number.")
continue
if row < 0 or row > 2 or col < 0 or col > 2:
print("Invalid input! Please enter a number between 0 and 2.")
continue
if board[row][col] == ' ':
board[row][col] = player
if check_winner(board):
print_board(board)
print(f"Player {player} wins!")
return
elif is_board_full(board):
print_board(board)
print("It's a tie!")
return
else:
player = 'O' if player == 'X' else 'X'
else:
print("That spot is already taken! Try again.")

tic_tac_toe()

You might also like