Python: can't assign to literal

后端 未结 8 2259
旧时难觅i
旧时难觅i 2020-11-29 10:43

My task is to write a program that asks the user to enter 5 names which it stores in a list. Next, it picks one of these names at random and declares that person as the winn

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 10:49

    The left hand side of the = operator needs to be a variable. What you're doing here is telling python: "You know the number one? Set it to the inputted string.". 1 is a literal number, not a variable. 1 is always 1, you can't "set" it to something else.

    A variable is like a box in which you can store a value. 1 is a value that can be stored in the variable. The input call returns a string, another value that can be stored in a variable.

    Instead, use lists:

    import random
    
    namelist = []
    namelist.append(input("Please enter name 1:"))  #Stored in namelist[0]
    namelist.append(input('Please enter name 2:'))  #Stored in namelist[1]
    namelist.append(input('Please enter name 3:'))  #Stored in namelist[2]
    namelist.append(input('Please enter name 4:'))  #Stored in namelist[3]
    namelist.append(input('Please enter name 5:'))  #Stored in namelist[4]
    
    nameindex = random.randint(0, 5)
    print('Well done {}. You are the winner!'.format(namelist[nameindex]))
    

    Using a for loop, you can cut down even more:

    import random
    
    namecount = 5
    namelist=[]
    for i in range(0, namecount):
      namelist.append(input("Please enter name %s:" % (i+1))) #Stored in namelist[i]
    
    nameindex = random.randint(0, namecount)
    print('Well done {}. You are the winner!'.format(namelist[nameindex]))
    

提交回复
热议问题