Below is a statement to be executed in the shell. Write Python statements to go before it that will guarantee that the statement will run without error. It doesn't matter what the code does, just that it runs. Below is an example. Code: a = p(b % c)
Statements to go before this one to guarantee that it will run without error:
def p(n):
return n + 1
b = 45
c = 13
Code:
n = d[x](96) + 7
Statements to go before this one to guarantee that it will run without error:
def hello(n):
return n + 5
d = {1:hello}
x = 1
I don't get the code. How can there be a square bracket, [x], with a parenthesis, (96), together to get a value in the dictionary d? What does that mean? Also, how come "hello" does not have quotes around the word since it is a string? I just don't get the code overall.
2 Answers 2
Since d is a dictionary, so accessing any element inside it requires you to use a index number, in the shown code, it is x. So, d[x] accesses the element at index x of dictionary.
When the defining of d is done, there is d = { 1:hello} this means that the 1th index of dictionary is referring to the predefined function named hello hence, during the call, there is a parenthesis used in the following line:
n = d[x](96) + 7
Since, we set x = 1, therefor, the call will actually be parsed as follows:
# d[x] calls dictionary element at index x
# x = 1, therefore, d[x] => d[1]
# d[1] is function hello
# d[1](96) will pass number 96 to function hello.
Comments
a = p(b % c)
a is the name of the value returned by p. p is a function name ie def p(args): pass, (b % c) is the argument being fed to the p function, which finds the remainder from the division: b/c and passes that to p.
n = d[x](96) + 7
n is the name of the value returned by the value of the entry. d could be a list or a dict. [x] is the index of the item that is retrieved. (96) is the argument you're passing to the item returned from the function in d at index x. +7 is added to the object returned from the function d[x] with the argument 96.
Hopefully this will be a good starting point for you to understand what's going on.
hellois a function not a string. 1 is the key in the dictionary which has a value of thefunctionhello. Dictionary values can be anything and keys don't have to be strings.