Sample programs for practice.(Python)

Japanese version.

Here are some sample programs suitable for beginners in programming to practice.

As you create these, you will learn programming skills if you carefully consider the meaning of the code.

Rock-Paper-Scissors game

Here's a sample code for a Rock-Paper-Scissors game in Python.

This program is a game of Rock-Paper-Scissors between the player and the computer. The player selects "r", "p", or "s" and the computer chooses randomly. Their choices are compared and a winner is determined. The player can choose to continue playing if they want.

import random

def get_player_choice():

    valid = False

    while not valid:

        player_choice = input("Choose rock (r), paper (p), or scissors (s): ")

        if player_choice in ['r', 'p', 's']:

            valid = True

        else:

            print("Invalid choice, please try again.")

    return player_choice

def get_computer_choice():

    return random.choice(['r', 'p', 's'])

def determine_winner(player_choice, computer_choice):

    if player_choice == computer_choice:

        return "tie"

    elif (player_choice == 'r' and computer_choice == 's') or \

         (player_choice == 'p' and computer_choice == 'r') or \

         (player_choice == 's' and computer_choice == 'p'):

        return "player"

    else:

        return "computer"

def print_result(winner):

    if winner == "player":

        print("Congratulations! You won!")

    elif winner == "computer":

        print("Sorry, the computer won. Better luck next time.")

    else:

        print("It's a tie!")

def play_again():

    valid = False

    while not valid:

        play_again = input("Would you like to play again? (y/n): ")

        if play_again.lower() in ['y', 'n']:

            valid = True

        else:

            print("Invalid choice, please try again.")

    return play_again.lower() == 'y'

def main():

    play_game = True

    while play_game:

        print("Let's play Rock-Paper-Scissors!")

        player_choice = get_player_choice()

        computer_choice = get_computer_choice()

        print(f"You chose {player_choice}, and the computer chose {computer_choice}.")

        winner = determine_winner(player_choice, computer_choice)

        print_result(winner)

        play_game = play_again()

if __name__ == '__main__':

    main()

Count the number of times a word appears in a file

This program reads data from a text file, counts the occurrences of each word, and outputs the result. First, the user is prompted to enter the file name. Next, the read_file function is used to read the data from the file. Then, the process_data function is used to count the words and returns a dictionary containing the word counts. Finally, the print_results function is used to output the count results.

Here is a sample code in Python that reads data from a text file, processes it, and outputs the result. This program counts the occurrences of each word in the file:

def read_file(filename):

    with open(filename, 'r') as file:

        data = file.read()

    return data

def process_data(data):

    words = data.split()

    word_count = {}

    for word in words:

        if word in word_count:

            word_count[word] += 1

        else:

            word_count[word] = 1

    return word_count

def print_results(word_count):

    for word, count in word_count.items():

        print(f"{word}: {count}")

def main():

    filename = input("Enter the filename: ")

    data = read_file(filename)

    word_count = process_data(data)

    print_results(word_count)

if __name__ == '__main__':

    main()

Simple calculator

This program defines functions for basic arithmetic operations and prompts the user to input two numbers and select an operation. Based on the selected operation, the program calls the corresponding function to perform the calculation and output the result. If the user attempts to divide by zero, the program outputs an error message.

def add(num1, num2):

    return num1 + num2

def subtract(num1, num2):

    return num1 - num2

def multiply(num1, num2):

    return num1 * num2

def divide(num1, num2):

    if num2 == 0:

        return "Error: Division by zero"

    else:

        return num1 / num2

def main():

    print("Welcome to the calculator!")

    valid_operations = ['+', '-', '*', '/']

    valid = False

    while not valid:

        operation = input("Please select an operation (+, -, *, /): ")

        if operation in valid_operations:

            valid = True

        else:

            print("Invalid operation, please try again.")

    num1 = float(input("Enter the first number: "))

    num2 = float(input("Enter the second number: "))

    if operation == '+':

        result = add(num1, num2)

    elif operation == '-':

        result = subtract(num1, num2)

    elif operation == '*':

        result = multiply(num1, num2)

    else:

        result = divide(num1, num2)

    print(f"Result: {result}")

if __name__ == '__main__':

    main()

Links

Python Articles

Python