如何在输入函数中引用变量?

时间:2018-10-14 21:30:15

标签: python python-3.x input formatting

我知道这是错误的,因为'input()'只能接受1个参数,但是我想在要求用户输入更多数字的同时在输入中包含这些变量:

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.esprit.jaxrs.hello</groupId>
  <artifactId>JAXRS_Hello_GL</artifactId>
  <version>1.0</version>
  <packaging>war</packaging>

  <properties>
    <failOnMissingWebXml>false</failOnMissingWebXml>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
  </properties>
  <!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-jaxrs -->
<dependencies>

<!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-jaxrs -->
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxrs</artifactId>
    <version>3.1.4.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-jaxrs -->
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-client</artifactId>
    <version>3.1.4.Final</version>
</dependency>

  </dependencies>

</project>

2 个答案:

答案 0 :(得分:2)

您可以使用字符串格式和F字符串(仅适用于Python 3.6 +)

字符串格式

n = 5
average = 0
for i in range(n):
    numbers = int(input('Please enter number {} of {} to average:'.format(i+1, n)))
    average = average+numbers/n

F字符串(适用于Python 3.6 +):

n = 5
average = 0
for i in range(n):
    numbers = int(input(f'Please enter number {i+1} of {n} to average:'))
    average = average+numbers/n

答案 1 :(得分:0)

您可以在将变量转换为字符串[str(x)]后尝试连接它们

n = 5
average = 0
for i in range(n):
    numbers = eval(input('Please enter number '+str(i+1)+' of '+str(n)+' to average:'))
    average = average+numbers/n

这是一种幼稚的方法,但是效果很好。