Basics of Python

Description of the page content

Conversion of old BASIC programs to Python in order to learn the basics of this language.

Tags:

3D Plot

# 3D Plot

# Original version in BASIC:
#     Creative Computing (Morristown, New Jersey, USA), ca. 1980.

# This version in Python:
#     Copyright (c) 2024, Marcos Cruz (programandala.net)
#     SPDX-License-Identifier: Fair

# Written on 2024-10-29.

# Last modified: 20241029T1607+0100.

import math
import os

WIDTH = 56

def clear():
    if os.name == 'nt':
        _ = os.system('cls')
    else:
        # on mac and linux, `os.name` is 'posix'
        _ = os.system('clear')

def print_credits():
    clear()
    print("3D Plot\n")
    print("Original version in BASIC:")
    print("    Creative computing (Morristown, New Jersey, USA), ca. 1980.\n")
    print("This version in Python:")
    print("    Copyright (c) 2024, Marcos Cruz (programandala.net)")
    print("    SPDX-License-Identifier: Fair\n")
    input("Press Enter to start the program.")

def a(z):
    return 30 * math.exp(-z * z / 100)

def draw():
    x = -30.0
    while x <= 30.0:
        line = " " * WIDTH
        l = 0
        y1 = 5 * math.floor(math.sqrt(900 - x * x) / 5)
        for y in range(y1, -y1 - 1, -5):
            z = math.floor(25 + a(math.sqrt(x * x + y * y)) - .7 * y)
            if z > l:
                l = z
                line = line[: z] + "*" + line[z + 1:]
        print(line)
        x += 1.5

print_credits()
clear()
draw()

Bagels

# Bagels

# Original version in BASIC:
#   D. Resek, P. Rowe, 1978.
#   Creative Computing (Morristown, New Jersey, USA), 1978.

# This version in Python:
#   Copyright (c) 2024, Marcos Cruz (programandala.net)
#   SPDX-License-Identifier: Fair
#
# Written on 2024-10-29.
#
# Last modified: 20241203T2230+0100.

import os
import random

# Clear the screen and move the cursor to the home position.

def clear_screen():
    if os.name == 'nt':
        _ = os.system('cls')
    else:
        # on mac and linux, `os.name` is 'posix'
        _ = os.system('clear')

# Prompt the user to enter a command and return it.

def command(prompt = "> "):
    return input(prompt)

# Print the given prompt and wait until the user enters an empty string.

def press_enter(prompt):
    user_input = "X"
    while user_input != "":
        user_input = command(prompt)

# Return `True` if the given string is "yes" or a synonym; otherwise return
# `False`.

def is_yes(answer):
    return answer.lower() in ["y", "yeah", "yes", "ok"]

# Return `True` if the given string is "no" or a synonym; otherwise return
# `False`.

def is_no(answer):
    return answer.lower() in ["n", "no", "nope"]

# Print the given prompt, wait until the user enters a valid yes/no string, and
# return `True` for "yes" or `False` for "no".

def yes(prompt):
    answer = ""
    while not (is_yes(answer) or is_no(answer)):
        answer = command(prompt)
    return is_yes(answer)

# Clear the screen, display the credits and wait for a keypress.

def print_credits():
    clear_screen()
    print("Bagels")
    print("Number guessing game\n")
    print("Original source unknown but suspected to be:")
    print("    Lawrence Hall of Science, U.C. Berkely.\n")
    print("Original version in BASIC:")
    print("    D. Resek, P. Rowe, 1978.")
    print("    Creative computing (Morristown, New Jersey, USA), 1978.\n")
    print("This version in Python:")
    print("    Copyright (c) 2024, Marcos Cruz (programandala.net)")
    print("    SPDX-License-Identifier: Fair\n")
    press_enter("Press Enter to read the instructions. ")

# Clear the screen, print the instructions and wait for a keypress.

def print_instructions():
    clear_screen()
    print("Bagels")
    print("Number guessing game\n")
    print("I am thinking of a three-digit number that has no two digits the same.")
    print("Try to guess it and I will give you clues as follows:\n")
    print("   PICO   - one digit correct but in the wrong position")
    print("   FERMI  - one digit correct and in the right position")
    print("   BAGELS - no digits correct")
    press_enter("\nPress Enter to start. ")

DIGITS        = 3
MIN_DIGIT     = 0
MAX_DIGIT     = 9
INVALID_DIGIT = MAX_DIGIT + 1
TRIES         = 20

def has_other_than_digits(text):
    for char in text:
        if not char.isdigit():
            return True
    return False

# Print the given prompt and get a three-digit number from the user.

def input_digits(prompt):
    user_digit = []
    while True:
        user_input = command(prompt)
        if len(user_input) != DIGITS:
            print(f"Remember it's a {DIGITS}-digit number.")
            continue
        elif has_other_than_digits(user_input):
            print("What?")
            continue
        user_digit.clear()
        for c in user_input:
            user_digit.append(int(c))
        if len(set(user_digit)) != len(user_digit):
            print("Remember my number has no two digits the same.")
            continue
        break
    return user_digit

# Init and run the game loop.

def play():
    computer_number = [INVALID_DIGIT, INVALID_DIGIT, INVALID_DIGIT]
    user_number = [INVALID_DIGIT, INVALID_DIGIT, INVALID_DIGIT]
    score = 0
    fermi = 0  # counter
    pico = 0   # counter
    while True: # game loop
        clear_screen()
        for i in range(0, DIGITS):
            while True:
                digit = random.randrange(MIN_DIGIT, MAX_DIGIT + 1)
                if digit in computer_number:
                    continue
                else:
                    computer_number[i] = digit
                    break
        print("O.K.  I have a number in mind.")
        for guess in range(0, TRIES):
            user_number = input_digits("Guess #" + str(guess).zfill(2) + ": ")
            fermi = 0
            pico = 0
            for i in range(0, DIGITS):
                for j in range(0, DIGITS):
                    if computer_number[i] == user_number[j]:
                        if i == j:
                            fermi += 1
                        else:
                            pico += 1
            print("PICO " * pico, end = "")
            print("FERMI " * fermi, end = "")
            if pico + fermi == 0:
                print("BAGELS", end = "")
            print()
            if fermi == DIGITS:
                print("You got it!!!")
                score += 1
                break # tries loop
        # end of tries loop
        if fermi != DIGITS:
            print("Oh well.")
            print(f"That's {TRIES} guesses.  My number was ", end = "")
            for i in range(0, DIGITS):
                print(computer_number[i], end = "")
            print(".")
        if not yes("Play again? "):
            break # game loop
    # end of game loop
    if score != 0:
        print(f"A {score}-point bagels, buff!!")
    print("Hope you had fun.  Bye.")

print_credits()
print_instructions()
play()

Bunny

# Bunny

# Original version in BASIC:
#   Creative Computing (Morristown, New Jersey, USA), 1978.

# This version in Python:
#   Copyright (c) 2024, Marcos Cruz (programandala.net)
#   SPDX-License-Identifier: Fair
#
# Written on 2024-10-29.
#
# Last modified: 20241203T2229+0100.

import os

# Clear the terminal and move the cursor to the top left position.
def clear_screen():
    if os.name == 'nt':
        _ = os.system('cls')
    else:
        # on mac and linux, `os.name` is 'posix'
        _ = os.system('clear')

# Clear the screen, print the credits and wait for the Enter key.
def print_credits():
    print("Bunny\n")
    print("Original version in BASIC:")
    print("    Creative Computing (Morristown, New Jersey, USA), 1978.\n")
    print("This version in Python:")
    print("    Copyright (c) 2024, Marcos Cruz (programandala.net)")
    print("    SPDX-License-Identifier: Fair\n")
    print("Press Enter to start the program.")
    input()

WIDTH = 53

# Print the given line buffer array.
def print_line(line):
    for item in line:
        print(item, end = "")
    print()

EOL = -1 # end of line identifier

line = [] # line buffer

def init_line():
    global line
    line = []
    for _ in range(0, WIDTH):
        line.append(" ")

# Draw the graphic.
def draw():

    global line

    letter = ['B', 'U', 'N', 'N', 'Y']
    LETTERS = len(letter)

    data = [
        1, 2, EOL, 0, 2, 45, 50, EOL, 0, 5, 43, 52, EOL, 0, 7, 41, 52, EOL,
        1, 9, 37, 50, EOL, 2, 11, 36, 50, EOL, 3, 13, 34, 49, EOL, 4, 14,
        32, 48, EOL, 5, 15, 31, 47, EOL, 6, 16, 30, 45, EOL, 7, 17, 29, 44,
        EOL, 8, 19, 28, 43, EOL, 9, 20, 27, 41, EOL, 10, 21, 26, 40, EOL,
        11, 22, 25, 38, EOL, 12, 22, 24, 36, EOL, 13, 34, EOL, 14, 33, EOL,
        15, 31, EOL, 17, 29, EOL, 18, 27, EOL, 19, 26, EOL, 16, 28, EOL,
        13, 30, EOL, 11, 31, EOL, 10, 32, EOL, 8, 33, EOL, 7, 34, EOL, 6,
        13, 16, 34, EOL, 5, 12, 16, 35, EOL, 4, 12, 16, 35, EOL, 3, 12, 15,
        35, EOL, 2, 35, EOL, 1, 35, EOL, 2, 34, EOL, 3, 34, EOL, 4, 33,
        EOL, 6, 33, EOL, 10, 32, 34, 34, EOL, 14, 17, 19, 25, 28, 31, 35,
        35, EOL, 15, 19, 23, 30, 36, 36, EOL, 14, 18, 21, 21, 24, 30, 37, 37,
        EOL, 13, 18, 23, 29, 33, 38, EOL, 12, 29, 31, 33, EOL, 11, 13, 17,
        17, 19, 19, 22, 22, 24, 31, EOL, 10, 11, 17, 18, 22, 22, 24, 24, 29,
        29, EOL, 22, 23, 26, 29, EOL, 27, 29, EOL, 28, 29, EOL ]

    init_line()

    data_index = 0
    while data_index < len(data):
        first_column = data[data_index]
        data_index += 1
        if first_column == EOL:
            print_line(line)
            init_line()
        else:
            last_column = data[data_index]
            data_index += 1
            for column in range(first_column, last_column + 1):
                line[column] = letter[column % LETTERS]

clear_screen()
print_credits()
clear_screen()
draw()

Diamond

# Diamond

# Original version in BASIC:
#     Example included in Vintage BASIC 1.0.3.
#     http://www.vintage-basic.net

# This version in Python:
#     Copyright (c) 2024, Marcos Cruz (programandala.net)
#     SPDX-License-Identifier: Fair
#
# Written on 2024-10-29.
#
# Last modified: 20241203T2230+0100.

import math

LINES = 17

for i in range(1, math.floor(LINES / 2 + 1) + 1):
    for j in range(1, math.floor((LINES + 1) / 2 - i + 1) + 1):
        print(" ", end = "")
    for j in range(1, i * 2):
        print("*", end = "")
    print()

for i in range(1, math.floor(LINES / 2) + 1):
    for j in range(1, i + 2):
        print(" ", end = "")
    for j in range(1, math.floor(((LINES + 1) / 2 - i) * 2 - 1) + 1):
        print("*", end = "")
    print()

Math

# Math

# Original version in BASIC:
#     Example included in Vintage BASIC 1.0.3.
#     http://www.vintage-basic.net

# This version in Python:
#     Copyright (c) 2023, Marcos Cruz (programandala.net)
#     SPDX-License-Identifier: Fair
#
# Written on 2024-10-29.
#
# Last modified: 20241203T2230+0100.

import ast
import math

def sign(n):
    if n > 0:
        return 1
    elif n < 0:
        return -1
    else:
        return 0

while True:
    try:
        n = ast.literal_eval(input("Enter a number: "))
        break
    except:
        print("Not a valid number.")

print(f"ABS({n}) --> abs({n}) --> ", abs(n))
print(f"ATN({n}) --> math.atan({n}) --> ", math.atan(n))
print(f"COS({n}) --> math.cos({n}) --> ", math.cos(n))
print(f"EXP({n}) --> math.exp({n}) --> ", math.exp(n))
print(f"INT({n}) --> int({n}) --> ", int(n))

if n >= 0:
    print(f"LOG({n}) --> math.log({n}) --> ", math.log(n))
else:
    print(f"LOG({n}) --> math.log({n}) --> undefined")

print(f"SGN({n}) --> sign({n}) # custom function --> ", sign(n))

if n >= 0:
    print(f"SQR({n}) --> math.sqrt({n}) --> ", math.sqrt(n))
else:
    print(f"SQR({n}) --> math.sqrt({n}) --> math domain error")

print(f"TAN({n}) --> math.tan({n}) --> ", math.tan(n))

Mugwump

# Mugwump

# Original version in BASIC:
#   Written by Bud Valenti's students of Project SOLO (Pittsburg, Pennsylvania, USA).
#   Slightly modified by Bob Albrecht of People's Computer Company.
#   Published by Creative Computing (Morristown, New Jersey, USA), 1978.
#   - https://www.atariarchives.org/basicgames/showpage.php?page=114
#   - http://vintage-basic.net/games.html

# This version in Python:
#   Copyright (c) 2024, Marcos Cruz (programandala.net)
#   SPDX-License-Identifier: Fair
#
# Written on 2024-10-29.
#
# Last modified: 20241203T2231+0100.

import ast
from dataclasses import dataclass
import math
import os
import random

GRID_SIZE = 10
TURNS     = 10
MUGWUMPS  =  4

@dataclass
class Mugwump:
    hidden: bool
    x: int
    y: int

# Clear the terminal and move the cursor to the top left position.

def clear():
    if os.name == 'nt':
        _ = os.system('cls')
    else:
        # on mac and linux, `os.name` is 'posix'
        _ = os.system('clear')

# Print the given prompt, wait until the user enters a valid integer and return
# it.

def get_number(prompt):
    while True:
        try:
            n = ast.literal_eval(input(prompt))
            break
        except:
            print("Not a valid number.")
    return n

# Prompt the user to enter a command and return it.

def command(prompt = "> "):
    print(prompt, end = "")
    return input()

# Print the given prompt and wait until the user enters an empty string.

def press_enter(prompt):
    user_input = "X"
    while user_input != "":
        user_input = command(prompt)

# Return `True` if the given string is "yes" or a synonym; otherwise return
# `False`.

def is_yes(answer):
    return answer.lower() in ["ok", "yeah", "yes", "y"]

# Return `True` if the given string is "no" or a synonym; otherwise return
# `False`.

def is_no(answer):
    return answer.lower() in ["no", "nope", "n"]

# Print the given prompt, wait until the user enters a valid yes/no string, and
# return `True` for "yes" or `False` for "no".

def yes(prompt):
    answer = ""
    while not (is_yes(answer) or is_no(answer)):
        answer = command(prompt)
    return is_yes(answer)

# Clear the screen, print the credits and ask the user to press enter.

def print_credits():
    clear()
    print("Mugwump\n")
    print("Original version in BASIC:")
    print("    Written by Bud Valenti's students of Project SOLO (Pittsburg, Pennsylvania, USA).")
    print("    Slightly modified by Bob Albrecht of People's Computer Company.")
    print("    Published by Creative Computing (Morristown, New Jersey, USA), 1978.")
    print("    - https://www.atariarchives.org/basicgames/showpage.php?page=114")
    print("    - http://vintage-basic.net/games.html\n")
    print("This version in Python:")
    print("    Copyright (c) 2024, Marcos Cruz (programandala.net)")
    print("    SPDX-License-Identifier: Fair\n")
    press_enter("Press Enter to read the instructions. ")

# Clear the screen, print the instructions and ask the user to press enter.

def print_instructions():
    clear()
    print("Mugwump\n")
    print("The object of this game is to find four mugwumps")
    print("hidden on a 10 by 10 grid.  Homebase is position 0,0.")
    print("Any guess you make must be two numbers with each")
    print("number between 0 and 9, inclusive.  First number")
    print("is distance to right of homebase and second number")
    print("is distance above homebase.\n")
    print(f"You get {TURNS} tries.  After each try, you will see")
    print("how far you are from each mugwump.\n")
    press_enter("Press Enter to start. ")

# Print the given prompt, then waits until the user enters a valid coord and
# returns it.

def get_coord(prompt):
    coord = 0
    while True:
        coord = get_number(prompt)
        if coord < 0 or coord >= GRID_SIZE:
            print(f"Invalid value {coord}: not in range [0, {GRID_SIZE - 1}].")
        else:
            break
    return coord

# Return `True` if the given mugwump is hidden in the given coords.

def is_here(m, x, y):
    return m.hidden and m.x == x and m.y == y

# Return the distance between the given mugwump and the given coords.

def distance(m, x, y):
    return round(math.sqrt((m.x - x) ** 2 + (m.y - y) ** 2))

# If the given number is greater than 1, return the given plural ending
# (default: "s"); otherwise return the given singular ending (default: an empty
# string).

def plural(n, plural = "s", singular = ""):
    return plural if n > 1 else singular

# Print the mugwumps found in the given coordinates and return the count.

def mugwumps_found(mugwump, x, y):
    found = 0
    for m in range(0, MUGWUMPS):
        if is_here(mugwump[m], x, y):
            mugwump[m].hidden = False
            found += 1
            print(f"You have found mugwump {m}!")
    return found

# Run the game.

def play():
    while True : # game
        clear()
        mugwump = []
        for m in range(0, MUGWUMPS):
            mugwump.append(
                Mugwump(
                    True,
                    random.randrange(0, GRID_SIZE),
                    random.randrange(0, GRID_SIZE)))
        found = 0
        turn = 1
        while turn < TURNS:
            print(f"Turn number {turn}\n")
            print(f"What is your guess (in range [0, {GRID_SIZE - 1}])?")
            x = get_coord("Distance right of homebase (x-axis): ")
            y = get_coord("Distance above homebase (y-axis): ")
            print(f"\nYour guess is ({x}, {y}).")
            found += mugwumps_found(mugwump, x, y)
            if found == MUGWUMPS:
                break # turns
            else:
                for m in range(0, MUGWUMPS):
                    if mugwump[m].hidden:
                        print("You are", distance(mugwump[m], x, y), f"units from mugwump {m}.")
                print()
            turn += 1
        # end of turns
        if found == MUGWUMPS:
            print(f"\nYou got them all in {turn} turn", plural(turn), "!\n", sep = "")
            print("That was fun! let's play again…")
            print("Four more mugwumps are now in hiding.")
        else:
            print(f"Sorry, that's {TURNS} tr", plural(TURNS, "ies", "y"), ".\n", sep = "")
            print("Here is where they're hiding:")
            for m in range(0, MUGWUMPS):
                if mugwump[m].hidden:
                    print(f"Mugwump {m} is at (", mugwump[m].x, ", ", mugwump[m].y, ").", sep = "")
        print()
        if not yes("Do you want to play again? "):
            break # game
    # end of game

print_credits()
print_instructions()
play()

Name

# Name

# Original version in BASIC:
#     Example included in Vintage BASIC 1.0.3.
#     http://www.vintage-basic.net

# This version in Python:
#     Copyright (c) 2024, Marcos Cruz (programandala.net)
#     SPDX-License-Identifier: Fair
#
# Written on 2024-10-29.
#
# Last modified: 20241029T2042+0100.

import ast

print("What is your name? ", end = "")
name = input()

while True:
    try:
        n = ast.literal_eval(input("Enter a number: "))
        break
    except:
        print("Number expected. Retry input line.")

for _ in range(0, n):
    print(f"Hello, {name}!")

Poetry

# Poetry

# Original version in BASIC:
#     Unknown author.
#     Modified and reworked by Jim Bailey, Peggy Ewing, and Dave Ahl at DEC.
#     Published in "BASIC Computer Games", Creative Computing (Morristown, New Jersey, USA), 1978.
#     https://archive.org/details/Basic_Computer_Games_Microcomputer_Edition_1978_Creative_Computing
#     https://github.com/chaosotter/basic-games/tree/master/games/BASIC%20Computer%20Games/Poetry
#     http://vintage-basic.net/games.html

# This version in Python:
#     Copyright (c) 2024, Marcos Cruz (programandala.net)
#     SPDX-License-Identifier: Fair
#
# Written on 2024-10-29, 2024-12-12.
#
# Last modified: 20241212T2228+0100.

# ==============================================================

import os
import random
from time import sleep

MAX_PHRASES_AND_VERSES = 20

# Clear the screen.
def clear_screen():
    if os.name == 'nt':
        _ = os.system('cls')
    else:
        # on mac and linux, `os.name` is 'posix'
        _ = os.system('clear')

# Print the given prompt and wait until the user enters an empty string.
def press_enter(prompt = ""):
    input_string = "x"
    while not input_string == "":
        input_string = input(prompt)

# Print the credits at the current cursor position.

def print_credits():

    print("Poetry\n")
    print("Original version in BASIC:")
    print("    Unknown author.")
    print("    Published in \"BASIC Computer Games\",")
    print("    Creative Computing (Morristown, New Jersey, USA), 1978.\n")

    print("This improved remake in Julia:")
    print("    Copyright (c) 2024, Marcos Cruz (programandala.net)")
    print("    SPDX-License-Identifier: Fair")

def is_odd(n):
    return n % 2 != 0

def play():

    action = 0
    phrase = 0
    phrases_and_verses = 0
    verse_chunks = 0

    while True: # verse loop

        manage_the_verse_continuation = True
        maybe_add_comma = True

        if action in [0, 1]:
            if phrase == 0:
                 print("MIDNIGHT DREARY", end = "")
            elif phrase == 1:
                 print("FIERY EYES", end = "")
            elif phrase == 2:
                 print("BIRD OR FIEND", end = "")
            elif phrase == 3:
                 print("THING OF EVIL", end = "")
            elif phrase == 4:
                 print("PROPHET", end = "")
        elif action == 2 :
            if phrase == 0:
                 print("BEGUILING ME", end = "")
                 verse_chunks = 2
            elif phrase == 1:
                 print("THRILLED ME", end = "")
            elif phrase == 2:
                 print("STILL SITTING…", end = "")
                 maybe_add_comma = False
            elif phrase == 3:
                 print("NEVER FLITTING", end = "")
                 verse_chunks = 2
            elif phrase == 4:
                 print("BURNED", end = "")
        elif action == 3 :
            if phrase == 0:
                 print("AND MY SOUL", end = "")
            elif phrase == 1:
                 print("DARKNESS THERE", end = "")
            elif phrase == 2:
                print("SHALL BE LIFTED", end = "")
            elif phrase == 3:
                print("QUOTH THE RAVEN", end = "")
            elif phrase == 4 and verse_chunks != 0:
                print("SIGN OF PARTING", end = "")
        elif action == 4 :
            if phrase == 0:
                 print("NOTHING MORE", end = "")
            elif phrase == 1:
                 print("YET AGAIN", end = "")
            elif phrase == 2:
                 print("SLOWLY CREEPING", end = "")
            elif phrase == 3:
                 print("…EVERMORE", end = "")
            elif phrase == 4:
                 print("NEVERMORE", end = "")
        elif action == 5 :
            action = 0
            print()
            if phrases_and_verses > MAX_PHRASES_AND_VERSES:
                print()
                verse_chunks = 0
                phrases_and_verses = 0
                action = 2
                continue
            else:
                manage_the_verse_continuation = False

        if manage_the_verse_continuation:

            sleep(0.250) # 250 ms

            if maybe_add_comma and not (verse_chunks == 0 or random.random() > 0.19):
                print(",", end = "")
                verse_chunks = 2

            if random.random() > 0.65:
                print()
                verse_chunks = 0
            else:
                print(" ", end = "")
                verse_chunks += 1


        action += 1
        phrase = random.randrange(0, 5)
        phrases_and_verses += 1

        if not (verse_chunks > 0 or not is_odd(action)):
            print("     ", end = "")

clear_screen()
print_credits()
press_enter("\nPress the Enter key to start. ")
clear_screen()
play()

Russian Roulette

# Russian Roulette

# Original version in BASIC:
#   Creative Computing (Morristown, New Jersey, USA), ca. 1980.

# This version in Python:
#   Copyright (c) 2024, Marcos Cruz (programandala.net)
#   SPDX-License-Identifier: Fair
#
# Written on 2024-10-29.
#
# Last modified: 20241029T1937+0100.

import math
import os
from random import random

# Clear the terminal and move the cursor to the top left position.
def clear_screen():
    if os.name == 'nt':
        _ = os.system('cls')
    else:
        # on mac and linux, `os.name` is 'posix'
        _ = os.system('clear')

# Prompt the user to enter a command and return it.
def get_command(prompt = "> "):
    print(prompt, end = "")
    return input()

def press_enter_to_start():
    _ = get_command("Press Enter to start. ")

def print_credits():
    clear_screen()
    print("Russian Roulette\n")
    print("Original version in BASIC:")
    print("    Creative Computing (Morristown, New Jersey, USA), ca. 1980.\n")
    print("This version in Python:")
    print("    Copyright (c) 2024, Marcos Cruz (programandala.net)")
    print("    SPDX-License-Identifier: Fair\n")
    press_enter_to_start()

def print_instructions():
    clear_screen()
    print("Here is a revolver.")
    print("Type 'f' to spin chamber and pull trigger.")
    print("Type 'g' to give up, and play again.")
    print("Type 'q' to quit.\n")

def play():
    while True: # game loop
        print_instructions()
        times = 0
        while True: # play loop
            command = get_command()
            if command == "f": # fire
                if int(math.floor(100 * random())) > 83:
                    print("Bang! You're dead!")
                    print("Condolences will be sent to your relatives.")
                    break
                else:
                    times += 1
                    if times == 10:
                        print("You win!")
                        print("Let someone else blow his brains out.")
                        break
                    else:
                        print("Click.")
            elif command == "g": # give up
                print("Chicken!")
                break
            elif command == "q": # quit
                return False
            # end of case
        # end of play loop
        press_enter_to_start()
    # end of game loop
    return True # play again, do not quit

print_credits()

playing = True
while playing:
    playing = play()

print("Bye!")

Sine Wave

# Sine Wave

# Original version in BASIC:
#     Creative Computing (Morristown, New Jersey, USA), ca. 1980.

# This version in Python:
#     Copyright (c) 2024, Marcos Cruz (programandala.net)
#     SPDX-License-Identifier: Fair
#
# Written on 2024-10-29.
#
# Last modified: 20241203T2231+0100.

import math
import os

word = ["", ""]
order = ["first", "second"]

def clear():
    if os.name == 'nt':
        _ = os.system('cls')
    else:
        # on mac and linux, `os.name` is 'posix'
        _ = os.system('clear')

def print_credits():
    clear()
    print("Sine Wave\n")
    print("Original version in BASIC:")
    print("    Creative computing (Morristown, New Jersey, USA), ca. 1980.\n")
    print("This version in Julia:")
    print("    Copyright (c) 2023, Marcos Cruz (programandala.net)")
    print("    SPDX-License-Identifier: Fair\n")
    _ = input ("Press Enter to start the program.")

def get_words():
    clear()
    for n in range(0, 2):
        word[n] = input("Enter the " + order[n] + " word: ")

def draw():
    clear()
    even = False
    angle = 0
    while angle <= 40:
        print(" " * int(26 + 25 * math.sin(angle)), end = "")
        print(word[int(even)])
        even = not even
        angle += 0.25

print_credits()
get_words()
draw()

Stars

# Stars

# Original version in BASIC:
#     Example included in Vintage BASIC 1.0.3.
#     http://www.vintage-basic.net

# This version in Python:
#     Copyright (c) 2024, Marcos Cruz (programandala.net)
#     SPDX-License-Identifier: Fair
#
# Written on 2024-10-29.
#
# Last modified: 20241029T2037+0100.

import ast

name = input("What is your name? ")
print(f"Hello, {name}.")

n = 0

while True:

    while True:
        try:
            n = ast.literal_eval(input("How many stars do you want? "))
            break
        except:
            print("Number expected. Retry input line.")

    print("*" * n)

    answer = input("Do you want more stars? ").lower()

    if not (answer in ["yeah", "yes", "y", "ok"]):
        break

print(f"Goodbye, {name}")

Strings

# Strings

# Original version in BASIC:
#     Example included in Vintage BASIC 1.0.3.
#     http://www.vintage-basic.net

# This version in Python:
#     Copyright (c) 2024, Marcos Cruz (programandala.net)
#     SPDX-License-Identifier: Fair
#
# Written on 2024-10-29.
#
# Last modified: 20241203T2231+0100.

import ast

s = input("Enter a string: ")

while True:
    try:
        n = int(ast.literal_eval(input("Enter a number: ")))
        break
    except:
        print("Not a valid number.")

print(f"ASC(\"{s}\"[0]) --> ", end = "")
print(f"ord(\"{s}\"[0])) --> ", end = "")
print(ord(s[0]))

print(f"CHR$({n}) --> ", end = "")
print(f"chr({n}) --> ", end = "")
print('"', chr(n), '"', sep = "")

print(f"LEFT$(\"{s}\", {n}) --> ", end = "")
print(f"\"{s}\"[:{n}] --> ", end = "")
print("\"", s[:n], "\"", sep = "")

print(f"MID$(\"{s}\", {n}) --> ", end = "")
print(f"\"{s}\"[{n} : len(\"{s}\")] --> ", end = "")
print("\"", s[n : len(s)], "\"", sep = "")

print(f"MID$(\"{s}\", {n}, 3) --> ", end = "")
print(f"\"{s}\"[{n} : min({n} + 3, len(\"{s}\"))] --> ", end = "")
print("\"", s[n : min(n + 3, len(s))], "\"", sep = "")

print(f"RIGHT$(\"{s}\", {n}) --> ", end = "")
print(f"(\"{s}\", max(len(\"{s}\") - {n}, 1) : length(\"{s}\") --> ", end = "")
print("\"", s[max(len(s) - n, 0) : len(s)], "\"", sep = "")

print(f"LEN(\"{s}\") --> ", end = "")
print(f"len(\"{s}\") --> ", end = "")
print(len(s))

# XXX TODO return 0 is the string is not a valid number
print(f"VAL(\"{s}\") --> ", end = "")
print(f"int(\"{s}\") --> ", end = "")
print(int(s))

print(f"STR$({n}) --> ", end = "")
print(f"str({n}) --> ", end = "")
print("\"", str(n), "\"", sep = "")

print(f"SPC({n}) --> ", end = "")
print(f"\" \" * {n} --> ", end = "")
print("\"", " " * n, "\"", sep = "")

Related pages

Basics off
Metaproject about the "Basics of…" projects.
Basics of 8th
Conversion of old BASIC programs to 8th in order to learn the basics of this language.
Basics of Ada
Conversion of old BASIC programs to Ada in order to learn the basics of this language.
Basics of Arturo
Conversion of old BASIC programs to Arturo in order to learn the basics of this language.
Basics of C#
Conversion of old BASIC programs to C# in order to learn the basics of this language.
Basics of C3
Conversion of old BASIC programs to C3 in order to learn the basics of this language.
Basics of Chapel
Conversion of old BASIC programs to Chapel in order to learn the basics of this language.
Basics of Clojure
Conversion of old BASIC programs to Clojure in order to learn the basics of this language.
Basics of Crystal
Conversion of old BASIC programs to Crystal in order to learn the basics of this language.
Basics of D
Conversion of old BASIC programs to D in order to learn the basics of this language.
Basics of Elixir
Conversion of old BASIC programs to Elixir in order to learn the basics of this language.
Basics of F#
Conversion of old BASIC programs to F# in order to learn the basics of this language.
Basics of Factor
Conversion of old BASIC programs to Factor in order to learn the basics of this language.
Basics of FreeBASIC
Conversion of old BASIC programs to FreeBASIC in order to learn the basics of this language.
Basics of Gleam
Conversion of old BASIC programs to Gleam in order to learn the basics of this language.
Basics of Go
Conversion of old BASIC programs to Go in order to learn the basics of this language.
Basics of Hare
Conversion of old BASIC programs to Hare in order to learn the basics of this language.
Basics of Haxe
Conversion of old BASIC programs to Haxe in order to learn the basics of this language.
Basics of Icon
Conversion of old BASIC programs to Icon in order to learn the basics of this language.
Basics of Io
Conversion of old BASIC programs to Io in order to learn the basics of this language.
Basics of Janet
Conversion of old BASIC programs to Janet in order to learn the basics of this language.
Basics of Julia
Conversion of old BASIC programs to Julia in order to learn the basics of this language.
Basics of Kotlin
Conversion of old BASIC programs to Kotlin in order to learn the basics of this language.
Basics of Lobster
Conversion of old BASIC programs to Lobster in order to learn the basics of this language.
Basics of Lua
Conversion of old BASIC programs to Lua in order to learn the basics of this language.
Basics of Nature
Conversion of old BASIC programs to Nature in order to learn the basics of this language.
Basics of Neat
Conversion of old BASIC programs to Neat in order to learn the basics of this language.
Basics of Neko
Conversion of old BASIC programs to Neko in order to learn the basics of this language.
Basics of Nelua
Conversion of old BASIC programs to Nelua in order to learn the basics of this language.
Basics of Nim
Conversion of old BASIC programs to Nim in order to learn the basics of this language.
Basics of Nit
Conversion of old BASIC programs to Nit in order to learn the basics of this language.
Basics of Oberon-07
Conversion of old BASIC programs to Oberon-07 in order to learn the basics of this language.
Basics of OCaml
Conversion of old BASIC programs to OCaml in order to learn the basics of this language.
Basics of Odin
Conversion of old BASIC programs to Odin in order to learn the basics of this language.
Basics of Pike
Conversion of old BASIC programs to Pike in order to learn the basics of this language.
Basics of Pony
Conversion of old BASIC programs to Pony in order to learn the basics of this language.
Basics of Racket
Conversion of old BASIC programs to Racket in order to learn the basics of this language.
Basics of Raku
Conversion of old BASIC programs to Raku in order to learn the basics of this language.
Basics of Retro
Conversion of old BASIC programs to Retro in order to learn the basics of this language.
Basics of Rexx
Conversion of old BASIC programs to Rexx in order to learn the basics of this language.
Basics of Ring
Conversion of old BASIC programs to Ring in order to learn the basics of this language.
Basics of Rust
Conversion of old BASIC programs to Rust in order to learn the basics of this language.
Basics of Scala
Conversion of old BASIC programs to Scala in order to learn the basics of this language.
Basics of Scheme
Conversion of old BASIC programs to Scheme in order to learn the basics of this language.
Basics of Styx
Conversion of old BASIC programs to Styx in order to learn the basics of this language.
Basics of Swift
Conversion of old BASIC programs to Swift in order to learn the basics of this language.
Basics of V
Conversion of old BASIC programs to V in order to learn the basics of this language.
Basics of Vala
Conversion of old BASIC programs to Vala in order to learn the basics of this language.
Basics of Zig
Conversion of old BASIC programs to Zig in order to learn the basics of this language.

External related links