![](/img/trans.png)
[英]Python - I'm not sure why this function I'm defining isn't working. Very fresh to programming
[英]Why is this code not working (i'm new to programming, python)
import random
guesses = 3
number = random.randint(1, 10)
print (number) #<- To test what number im supposed to write.
while guesses > 0: # When you have more than 0 guesses -> guess another number
guess = input("Guess: ")
if guess == number : # If guess is equal to number -> end game
print ('Your guess is right!.')
break
if guess != number : # If not number -> -1 guess
print ("Nope!")
guesses -= 1
if guesses == 0: #If all 3 guesses are made -> end game
print("That was it! Sorry.")
print(number,"was the right answer!")
我究竟做錯了什么? 我想不通,希望你能幫忙^ - ^
如果你能教我如何改進我的編程,那么請隨時寫信給我如何做! 我開放學習新東西btw抱歉我的英語不好:3(編輯:當我猜對了正確的號碼,它仍然說“不!”而且我不得不猜猜另一個號碼。)
這看起來像Python3。 如果是這樣,請改用guess = int(input("Guess: "))
。
在Python3中, input()
返回一個字符串,你將該字符串與一個永遠不會起作用的整數進行比較。 因此,將input()
的返回值轉換為整數,以確保您將蘋果與蘋果進行比較。
你需要在輸入前放置int,所以:
guess = int(input("Guess: "))
這會將猜測變為整數,因此代碼會識別它。
input()
命令返回一個字符串,字符串不等於數字( "3" == 3
計算結果為false
)。 您可以使用int(...)
函數將字符串(或浮點數)轉換為整數。
我假設您正在使用Python 3.x,因為print
是一個函數。 如果您使用的是Python 2.x,則應該使用raw_input()
,因為input()
會使解釋器將輸入的內容視為Python代碼並執行它(就像eval(...)
函數那樣)。
在99.999%的情況下,您不希望執行用戶輸入。 ;-)
您的程序需要的另一個重要的事情是提示用戶,以便他們知道他們將對您的程序做些什么。 我已相應地添加了提示。
import random
print ("Hello. We are going to be playing a guessing game where you guess a random number from 1-10. You get three guesses.")
number = random.randint(1, 10)
# print (number) #<- To test what number im supposed to write.
guesses = 3
while guesses > 0: # When you have more than 0 guesses -> guess another number
guess = input("Enter your guess: ")
if guess == number : # If guess is equal to number -> end game
print ('Your guess is right!.')
break
if guess != number : # If not number -> -1 guess
print ("Nope!")
guesses -= 1
if guesses == 0: #If all 3 guesses are made -> end game
print("That was it! Sorry.")
print(number, "was the right answer!")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.