简体   繁体   中英

Program prints correct output from dictionary, but I don't fully understand how the print statements work

The program gives the correct output; but, I just executed a program given to me, I don't understand how it works, especially the lines I've commented:

dictionary = {
    "pani": "water",
    "hara": "green",
    "kapda": "clothe,",
    "ungli": "finger",
}

print("options are", dictionary.keys()) # why do i need to use comma here

ask = input("Enter a word to translate in English\n")

print("The meaning of word is: ", dictionary[ask]) # i dont understand this line

Output:

options are dict_keys(['pani', 'hara', 'kapda', 'ungli'])
Enter a word to translate in English
kapda
The meaning of word is:  clothe,

This is how print() statement works:

Step 1 . The print() statement takes an arbitrary number of arguments each of which are separated by commas(,).

Step 2 . It then simply prints all those argument in sequence from left to right.

For example,

Example 1 print(1, 2, 3, 4, 18, 24, 1000, 0) will print all of these numbers in the sequence from left to right on the console(screen).

Example 2 print("options are", dictionary.keys()) will print the two arguments that you have supplied from left to right. In this case, the first argument is "options are" and the second argument is dictionary.keys() which is a object whose value is dict_keys(['pani', 'hara', 'kapda', 'ungli']) . That is why you get the following text on your screen: options are dict_keys(['pani', 'hara', 'kapda', 'ungli'])

The same exact thing will happen to your second print statement.The only difference will be that now the value of your second argument is different. That is now you have the 2nd argument as dictionary[ask]=clothe, since it is the corresponding value of the input you supplied(kapda).

, is used to concatenate strings when used with print .

The , you see in your output is due to the typo you have in dictionary creation as:

dictionary = { "kapda": "clothe,"} 

I think you meant clothes .

dictionary = { "pani" : "water", "hara" : "green", "kapda": "clothes", "ungli": "finger", } 
print("options are" , dictionary.keys()) # why do i need to use comma here 
ask = input("Enter a word to translate in English\n")

print("The meaning of word is: ", dictionary[ask])

Output (for input kapda ):

The meaning of word is:  clothes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM