Python不太难,只是在变量上挣扎

时间:2014-04-11 20:06:51

标签: python random tags

代码:

loop = 0

def main():
  while loop == 0:
    Num = input("Please Enter The Number Of People That Need The Cocktails ")
    print()
    print(" Type END if you want to end the program ")
    print()
    for count in range (Num):
      with open("Cocktails.txt",mode="w",encoding="utf-8") as myFile:
          print()
          User = input("Please Enter What Cocktails You Would Like ")
          if User == "END":
            print(Num, "Has Been Written To The File ")
            exit()
          else:
            myFile.write(User+"/n")
            myFile.write(Num+"/n")
            print()
            print(User, "Has Been Written To The File ")

错误:

  

第9行,主要用于范围内的计数(Num):TypeError:' str'宾语   不能解释为整数

我试图将变量设置为重复多少鸡尾酒的次数。

示例:

How many cocktails ?  6 

然后脚本应该要求用户输入他想要的六次鸡尾酒。

2 个答案:

答案 0 :(得分:1)

int()上投放input,使Num成为可行的整数。必须这样做,因为在Python 3中,input总是返回一个字符串:

Num = int(input("Please Enter The Number Of People That Need The Cocktails "))

当你的代码处于当前状态时,你正试图从一个字符串构造一个range,由于range()需要一个整数,所以它根本不起作用。


修改

现在你必须替换:

myFile.write(Num+"/n")

使用:

myFile.write(str(Num)+"/n")
此时

Num是一个整数,因此您必须显式创建一个字符串以将其与换行符连接起来。

答案 1 :(得分:1)

在Python中,input()默认返回一个字符串。将Num更改为:

Num = int(input("Please Enter The Number Of People That Need The Cocktails ")) 

另外

MyFile.write(Num + "\n")  

应为:

MyFile.write(str(Num) + "\n")

只是为了记录,你可以替换:

loop = 0
while (loop == 0):

使用:

while True: