因此,我创建了一个程序,该程序将字符串值分配给变量。
这是代码
print("I have information for the following planets:\n");
print(" 1. Venus 2. Mars 3. Jupiter");
print(" 4. Saturn 5. Uranus 6. Neptune\n");
weight = input("Enter your weight: ");
planet = input("Enter planet number: ");
# Write an if statement below:
if planet == 1:
planet_name = 'Venus';
weight = weight * 0.91;
elif planet == 2:
planet_name = 'Mars';
weight = weight * 0.38;
elif planet == 3:
planet_name = 'Jupiter';
weight = weight * 2.34;
elif planet == 4:
planet_name = 'Saturn';
weight = weight * 1.06;
elif planet == 5:
planet_name = 'Uranus';
weight = weight * 0.92;
elif planet == 6:
planet_name = 'Neptune';
weight = weight * 1.19;
else:
print("Planet Not Found");
print("Your weight on " + planet_name + " is: " + weight + "kg");
因此,当我尝试运行该程序时,它说planet_name
未找到并且还会打印else语句
这是有错误的输出
I have information for the following planets:
1. Venus 2. Mars 3. Jupiter
4. Saturn 5. Uranus 6. Neptune
Enter your weight: 55
Enter planet number: 6
Planet Not Found
Traceback (most recent call last):
File "/data/data/com.termux/files/home/python/planet.py", line 28, in <module>
print("Your weight on " + planet_name + " is: " + weight + "kg");
NameError: name 'planet_name' is not defined
我无法找到造成问题的原因。
首先,由于您使用的是python,因此不必;
在每个语句的末尾添加。
现在,默认情况下,doinput('')
返回string
。你必须将类型更改为float
用于weight
与int
供planet
print("I have information for the following planets:\n")
print(" 1. Venus 2. Mars 3. Jupiter")
print(" 4. Saturn 5. Uranus 6. Neptune\n")
weight = float(input("Enter your weight: "))
planet = int(input("Enter planet number: "))
# Write an if statement below:
if planet == 1:
planet_name = 'Venus'
weight = weight * 0.91
elif planet == 2:
planet_name = 'Mars'
weight = weight * 0.38
elif planet == 3:
planet_name = 'Jupiter'
weight = weight * 2.34
elif planet == 4:
planet_name = 'Saturn'
weight = weight * 1.06
elif planet == 5:
planet_name = 'Uranus'
weight = weight * 0.92
elif planet == 6:
planet_name = 'Neptune'
weight = weight * 1.19
else:
print("Planet Not Found")
print("Your weight on " + planet_name + " is: " + str(weight) + "kg")
在最后一条print
语句中,您必须将weight
back的类型转换为string
以打印出该语句
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句