Reputation: 19
For example in the computer variable, what purpose do the square brackets enclosed by the normal brackets server? I am new to python and confused about this. Thanks in advance!
import random
def play():
user = input(" 'r' for rock, 'p' for paper, 's' for scissors: ")
computer = random.choice(['r', 'p', 's'])
if user == computer:
return "tie"
Upvotes: 0
Views: 108
Reputation: 189908
function(a)
means, call the function function
with the argument a
.
function([a])
means, call the function with the list [a]
as its argument. Equivalently, you could write function(list(a))
Both characters have other uses; round parentheses can be used to group expressions, like in mathematics, which in Python also gets used to indicate a tuple. So,
function((a,))
means, call the function with the tuple (a,)
as the argument. The comma is necessary to make it into a tuple; just (a)
is merely the mathematical grouping we mentioned before, saying evaluate a
before ... nothing. Equivalently, you could write function(tuple(a))
Square brackets are also used in indexing, so listvar[a]
means the a
:th element of the list variable listvar
, and dictvar[a]
means get the value for the key a
from the dictionary dictvar
.
For lists, the notation actually allows you to pull out sublists, called slices, in various ways, like listvar[:-a]
or listvar[::]
. This is complex enough that I'll defer the explanation of it to a separate question: Understanding slice notation
Square brackets are also used for various matrix notations in Numpy and Pandas, but that's not part of the Python core.
Upvotes: 0
Reputation: 141
The square brackets are actually a very simple term in python known as a list.
The code above could also translate to:
import random #Import random module
userinput = input(" 'r' for rock, 'p' for paper, 's' for scissors: ") #ask user what they want to input
choicelist = ['r', 'p', 's'] #List of options
computer = random.choice(choicelist) #pick a random option from list
if user == computer: #checking if they are both the same
print("tie") #return tie if equal (Also this was a return which only works in functions, but i removed the function because it was not needed)
Please comment if you have any more questions!
Upvotes: 1
Reputation: 1725
whenever you use squared brackets you are defining a list (an array)
when you call a function (like random.choice
) need to use () to pass arguments
so in this case you are calling a function over a list the equivalen should be:
def play():
user = input(" 'r' for rock, 'p' for paper, 's' for scissors: ")
myList = ['r','p','s']
random.choice(myList)
if user == computer:
return "tie"
this is a paper scissor rock game where the only response is to tie. the random.choice function select one element from an input List
Upvotes: 1