![](/img/trans.png)
[英]I'm trying to write a Python program to find the number of notes in an integer, but my code isn't working
[英]I'm trying to write a number guessing game in python but my program isn't working
該程序應該隨機生成一個介於1到10(含)之間的數字,並要求用戶猜測該數字。 如果他們弄錯了,他們可以再次猜測,直到正確為止。 如果他們猜對了,該程序應該向他們表示祝賀。
這是我所擁有的,它不起作用。 我輸入的數字介於1到10之間,沒有任何祝賀。 當我輸入一個負數時,什么也沒有發生。
import random
number = random.randint(1,10)
print "The computer will generate a random number between 1 and 10. Try to guess the number!"
guess = int(raw_input("Guess a number: "))
while guess != number:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
guess = int(raw_input("Guess another number: "))
elif guess <= 0 and guess >= 11:
print "That is not an integer between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
elif guess == number:
print "Congratulations! You guessed correctly!"
只需將祝賀消息移到循環外即可。 然后,循環中也只能有一個猜測輸入。 以下應該工作:
while guess != number:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
else:
print "That is not an integer between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
print "Congratulations! You guessed correctly!"
問題是在if / elif鏈中,它從上到下對其進行評估。 向上移動最后一個條件。
if guess == number:
..
elif other conditions.
另外,您需要更改while循環以允許它在第一次進入。 例如。
while True:
guess = int(raw_input("Guess a number: "))
if guess == number:
..
然后在您有條件結束游戲時休息。
問題是,如果正確猜測的條件為true,則退出while循環。 我建議解決此問題的方法是將祝賀移到while循環之外
import random
number = random.randint(1,10)
print "The computer will generate a random number between 1 and 10. Try to guess the number!"
guess = int(raw_input("Guess a number: "))
while guess != number:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
guess = int(raw_input("Guess another number: "))
elif guess <= 0 and guess >= 11:
print "That is not an integer between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
if guess == number:
print "Congratulations! You guessed correctly!"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.