mercredi 10 mars 2021

How to create a Random Walk program in Python?

so I just started learning Python and this is the first code I wrote. It's a Random Walk generator. I think I got it to work pretty well but I'm also sure there are more effective and less clunky ways to do this. Could you give me some tips on what to change to make the code shorter/more optimized and just objectively more "pythonian" and better?

# Random Walk in two dimensions

import random

steps = "a"
maximal = "a"
minimal = "a"
Xstep = 0
Ystep = 0
StepSize = 0
PosNeg = 0


def new_line():
    print(" ")


def invalid_enter_number():
    print("Invalid input! Enter a number.")
    new_line()


def invalid_enter_positive():
    print("Invalid input! Enter a positive number.")
    new_line()


new_line()
print("Random Walk in two dimensions")
new_line()

while type(steps) != int:
    try:
        steps = int(input("How many steps should be done? "))
        while steps <= 0:
            invalid_enter_positive()
            steps = int(input("How many steps should be done? "))
    except:
        steps = ValueError
        invalid_enter_number()
        continue

while type(maximal) != int:
    try:
        maximal = int(input("How big is the biggest possible step? "))
        while maximal <= 0:
            invalid_enter_positive()
            maximal = int(input("How big is the biggest possible step? "))
    except:
        maximal = ValueError
        invalid_enter_number()
        continue

if maximal != 1:
    while type(minimal) != int:
        try:
            minimal = int(input("How big is the smallest possible step? "))
            while minimal <= 0 or minimal >= maximal:
                if minimal <= 0:
                    invalid_enter_positive()
                    minimal = int(input("How big is the smallest possible step? "))
                else:
                    print("Number must be smaller than the biggest possible step!")
                    new_line()
                    minimal = int(input("How big is the smallest possible step? "))
        except:
            minimal = ValueError
            invalid_enter_number()
            continue
else:
    minimal = 1

new_line()
print("Number of steps:", steps)

if maximal != 1:
    print("Step size range:", minimal, "-", maximal)
else:
    print("Step size: 1")

new_line()
print("Steps:")

while steps > 0:
    StepSize = random.randint(minimal, maximal)
    PosNeg = random.randint(0, 1)
    chance = random.randint(0, 1)
    if chance == 0 and PosNeg == 0:
        Xstep += StepSize
    elif chance == 0 and PosNeg == 1:
        Xstep -= StepSize
    elif chance == 1 and PosNeg == 0:
        Ystep += StepSize
    else:
        Ystep -= StepSize
    print("X:", Xstep, " Y:", Ystep)
    steps -= 1




Aucun commentaire:

Enregistrer un commentaire