我刚刚完成(开玩笑的,我是在查看旧代码时发现的),但这次是真的,这是最终代码。最终更新:现在一切都很好,感谢这个奇数公式。n个奇数的和是n^2。我们是如何得出这个公式的?
- 第一个奇数 = 1 和 = 1 = 1^2
- 前两个奇数 = 1,3 和 = 4 = 2^2
- 前三个奇数 = 1,3,5 和 = 9 = 3^2
- 前四个奇数 = 1,3,5,7 和 = 16 = 4^2
- 前五个奇数 = 1,3,5,7,9 和 = 25 = 5^2
- 因此,n个奇数的和 = n^2
import random,osuserI =Trueos.system("cls")def randomOddNumber(a,b): a = a // 2 b = b // 2 - 1 number = random.randint(a,b) number = (number * 2) + 1 return numberwhile userI==True: userInput = int(input("Please input a 4 digit number: ")) compNumber = random.randint(1000, 9999) count = 0 while userInput != compNumber: if (userInput % 2) == 0: compNumber= random.randrange(0, 10000, 2) count=count+1 else: compNumber = randomOddNumber(0,9999) count =count+1 print("Match was created on the", count, "attempt.") ex = False while ex == False: userAwnser = input("Would you like to play again?: ") if userAwnser == "no"or userAwnser=="No": userI = False ex = True elif userAwnser == "yes"or userAwnser=="Yes": userI = True ex = True os.system("cls") else: print("Error Not a valid awnser") ex = False
回答:
这里的主要问题是你试图强制input()将你的字符串输入分割成四个变量。即使你想将其转换为整数,你也需要使用for循环或等效方法将其分成一个列表。此外,将每个数字分开在你的情况下是多余的,你可以直接将整数与一个4位随机整数进行比较(例如:randint(1000, 9999))。下面是一个更简单、更有效的方法:
import randomuserInput = int(input("Please input a 4 digit number: "))compNumber = random.randint(1000, 9999)count = 0while userInput != compNumber: compNumber = random.randint(1000, 9999) count += 1print("Match was created on the", count, "attempt.")
请在评论中提出任何问题!
注意:这没有用户输入验证,如果输入的是字符串会崩溃,如果输入的数字大于9999或小于1000,会陷入无限循环。