我是python和程序设计的新手,我目前正在使用codecademy来学习本课程,但是我尝试着扩展本课程所学的知识,并提出一些小想法,以帮助我更好地理解。但是,无论何时到达代码的这一部分,它都会给我这个错误。
File "TeamSelector.py", line 12, in <module>
print ("\n You have been asigned to team number: " + str(teamSelection % teams))
TypeError: not all arguments converted during string formatting
PS C:\users\worri\documents\development\python>
这是我的完整代码
import sys
testInt = 64
teams = input("\n How many teams are there? \n")
print ("There are " + teams + " number of teams.")
totalPlayers = input ("\n How many total players are there \n")
print ("There are " + totalPlayers + " players to be selected into teams.")
teamSelection = input ("\n What is your assigned number? \n")
print ("\n You have been asigned to team number: " + str(teamSelection % teams))
我已经尝试了很多事情,甚至有一个单独的变量来进行计算以将其作为字符串的一部分传递到末尾,我在google上寻找了不同的方式,而我尝试过的任何操作都给出了相同的错误。我了解得足够多,我认为typeError在将float / int传递给字符串时遇到问题,但是我似乎无法找到一个.toString()功能,这是我以前尝试学习Java时使用的功能。如果有人可以帮助我,我将不胜感激。谢谢。
答案 0 :(得分:2)
此错误是由于以下事实导致的:您的teamSelection
和teams
变量必须在获取模数之前转换为整数(模数运算符适用于数字,而不适用于字符串)。当您使用input()
函数时,您的输入将被读取为字符串。
这可以通过使用以下命令更改代码的最后一行来解决:
team_assignment = int(teamSelection) % int(teams)
print("\n You have been asigned to team number: " + str(team_assignment)
答案 1 :(得分:0)
始终使用snake_case来命名变量。 Please refer to this article
teams = input("How many teams are there? \n")
print("There are " + teams + " number of teams.")
total_players = input("How many total players are there \n")
print("There are " + total_players + " players to be selected into teams.")
team_selection = input("What is your assigned number? \n")
print("You have been assigned to team number: " + str(int(team_selection) % int(teams)))
print(f"You have been assigned to team number: {str(int(team_selection) % int(teams))}")