brittAnderson / Intro2Computing4Psychology

A guided introduction to computing tools useful for research in psychology - targeted to complete beginners
46 stars 159 forks source link

Sharing useful codes #25

Closed w24cai closed 3 years ago

w24cai commented 3 years ago

To make hangman in python a bit more like a hangman game, I would like to share some useful slicing code here. For example, suppose the word is "psych" and the guess is "s", instead of printing the index, I think displaying the word be clearer for visualization, i.e., "_s___".

To do so, we can use slicing method, i.e.,

display = "_" * len(word) display = display[:index]+word[index]+display[index+1:] print(display) Where index is the corresponding index that was guessed correctly, here, index will be 1.

We can put display = "_" * len(word) outside the loop so that the word displaying can be successfully updated in each iteration.

Thanks.

brittAnderson commented 3 years ago

Nice suggestion. Python prioritizes readability. So it does "overloadding" of operators. E.g. the "times" sign. You can say 2*3 and python know it is math. You can say you want it to print the underscore 9 /times/ ("_"*9)and python will know you mean something different. Same for +. If you add 'lastname' to 'firstname' you get the lists stuck together.