Python:不能分配给文字 [英] Python: can't assign to literal

查看:141
本文介绍了Python:不能分配给文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是编写一个程序,要求用户输入它存储在列表中的 5 个名称.接下来,它随机选择这些名字中的一个,并宣布该人为获胜者.唯一的问题是,当我尝试运行它时,它说 can't assign to literal.

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 winner. The only issue is that when I try to run it, it says can't assign to literal.

这是我的代码:

import random
1=input("Please enter name 1:")
2=int(input('Please enter name 2:'))
3=int(input('Please enter name 3:'))
4=int(input('Please enter name 4:'))
5=int(input('Please enter name 5:'))
name=random.randint(1,6)
print('Well done '+str(name)+'. You are the winner!')

我必须能够生成一个随机名称.

I have to be able to generate a random name.

推荐答案

= 运算符的左侧需要是一个变量.你在这里做的是告诉python:你知道第一名吗?将它设置为输入的字符串.".1 是文字数字,而不是变量.1 始终是 1,您不能将其设置"为其他内容.

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.

变量就像一个盒子,您可以在其中存储值.1 是一个可以存储在变量中的值.input 调用返回一个字符串,另一个可以存储在变量中的值.

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.

改为使用列表:

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]))

使用 for 循环,你可以减少更多:

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]))

这篇关于Python:不能分配给文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆