Я только начал изучать Python, и это мой первый код, который я написал. Это генератор случайного блуждания. Я думаю, что у меня это работает довольно хорошо, но я также уверен, что есть более эффективные и менее громоздкие способы сделать это. Не могли бы вы дать мне несколько советов о том, что нужно изменить, чтобы сделать код короче / более оптимизированным и просто объективно более «питонским» и лучше?
# 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
1 ответ
Вот одно предложение; другие читатели, вероятно, предложат больше. Несколько раз нужно получить от пользователя целое число. Вы можете создать функцию для обработки таких деталей. В приведенном ниже коде показано, какая функция может выглядеть легкой и как ее использовать.
def int_from_user(prompt):
while True:
try:
n = int(input(prompt + ' '))
if n > 0:
return n
else:
raise ValueError()
except ValueError:
print('Invalid input! Enter a positive number.')
steps = int_from_user('How many steps should be done?')
print(steps)
