簡體   English   中英

使用不同的代碼但得到相同的結果

[英]Using different codes but getting same results

在代碼 A 和代碼 B 中,輸出是相同的。 我知道要使輸出相同,代碼不必是同一行。 但是如果你在代碼 A 和 B 中查看它,變量“word_length”有不同的值。

在代碼 a) 中,變量僅等於所選單詞的字符總數。

在代碼 BI 中,從列表中所選單詞的總長度中減去 1,計算機從 0 開始計算字符的位置。

在這兩個代碼中,變量在“for 循環”中的使用方式相同。 即使變量“word_length”的值不同,輸出也是相同的。

誰能解釋為什么會這樣?

代碼 A

import random

word_list = ["aardvark", "baboon", "camel"]

chosen_word = random.choice(word_list)

print(f'Pssst, the solution is {chosen_word}.')


display = []

word_length = len(chosen_word)

for _ in range(word_length):
       display += "_"
guess = input("Guess a letter: ").lower()

for position in range(word_length):
     letter = chosen_word[position]

     if letter == guess:
         display[position] = letter
print(display)

代碼 B

import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
 
print(f'Pssst, the solution is {chosen_word}.')
 
display = []
for letter in chosen_word:
   display += "_"
word_length = len(chosen_word)-1

guess = input("Guess a letter: ").lower()

for position in range(word_length):
        if guess == chosen_word[position]:
            display[position] = guess

print(display)

range()產生一個開放范圍,例如range(5)產生 (0, 1, 2, 3, 4)。

因此,從單詞長度中減去 1 的代碼存在一個錯誤,即您永遠無法猜出單詞的最后一個字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM