(Jan-19-2021, 12:04 PM)banidjamali Wrote: But can I define a validation function that uses 'while True' to validate an input that is defined outside of it? Like calling a validate function on any output that is outside of the function?!
You can always write a validation function that will take an argument and return True or False, based on some conditions. You don't need a loop though - you take one argument and check that argument against some conditions (i.e. no need of the loop at all)
Also, writing validation function makes sense if you perform some more complex validation. In this case it will not add much benefit and it can even be argued it complicates the code unnecessarily (i.e. compare
if some_input in valid_inputs:
vs if is_valid(some_input):
where is_valid(param)
is function that will do just return param in valid_inputs
couple of other things
- in your function it would be better if
choices
is defined inside the function, or provided as argument.
- something like this only makes the code more difficult to read and follow:
print(f"{player2} wins!" if choice1 == wins[choice2] else f"{player1} wins!" if choice2 == wins[choice1] else "Same!")
- many (me too) don't like one-line ifs like
if choice in choices: return choice
player1 = input("Give player 1 a name:\n") player2 = input("Give player 2 a name:\n") def move(player): choices = ['rock', 'paper', 'scissors'] while True: choice = input(f"{player}, choose one:({'/'.join(choices)}) ") if choice in choices: return choice print("Check the spelling.") wins = {'rock':'scissors', 'paper':'rock', 'scissors':'paper'} while True: choice1 = move(player1) choice2 = move(player2) if choice1 == choice2: print('Same') else: winner = player1 if choice2 == wins[choice1] else player2 print(f'{winner} wins') # alternatively if choice2 == wins[choice1]: print(f'{player1} wins') else: print(f'{player2} wins') if input("Continue?(y/n) ") == 'n': break
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs