需要帮助制作一个“python”程序 - 如何让我的选择菜单在输入(1或2)时启动不同的转换
我一直在做一个温度转换器,但在把两个程序(摄氏度转华氏度和华氏度转摄氏度)结合在一起时遇到了麻烦。我可以让菜单显示出来,但不知道怎么选择一个转换器。
# Tempeture Converter
def convert():
print 'Conversions Menu';
print '(1) Celsius to Fahrenheit';
print '(2) Fahrenheit to Celsius';
def select():
convert();
choice = input ('Enter Choice Number:')
if (input == '1'):
C2F();
elif (input == '2'):
F2C();
def F2C():
Fahrenheit = input('enter degrees in Fahrenheit: ');
Celsius = ( 5.0 / 9.0) * (Fahrenheit -32);
print Fahrenheit, 'Fahrenheit =', Celsius, 'Celsius';
def C2F():
Celsius = input('enter degrees in Celsius: ');
Fahrenheit = (9.0 / 5.0) * Celsius +32;
print Celsius, 'Celsius =', Fahrenheit, 'Fahrenheit';
*更正*
# Tempeture Converter
def convert():
print 'Conversions Menu';
print '(1) Celsius to Fahrenheit';
print '(2) Fahrenheit to Celsius';
def select():
convert();
choice = input ('Enter Choice Number:')
if (choice == '1'):
C2F();
elif (choice == '2'):
F2C();
def F2C():
Fahrenheit = input('enter degrees in Fahrenheit: ');
Celsius = ( 5.0 / 9.0) * (Fahrenheit -32);
print Fahrenheit, 'Fahrenheit =', Celsius, 'Celsius';
def C2F():
Celsius = input('enter degrees in Celsius: ');
Fahrenheit = (9.0 / 5.0) * Celsius +32;
print Celsius, 'Celsius =', Fahrenheit, 'Fahrenheit';
3 个回答
1
有没有办法让程序在我使用转换器后重新运行...也就是说,一旦我把华氏温度转换成摄氏温度后,可以再次看到菜单吗?
最简单的方法是把 select()
函数放在一个循环里:
if __name__ == '__main__':
while True:
select()
然后在 select()
函数里可以加一个退出的选项:
elif choice == '3':
exit()
2
在 select
函数中,你有
choice = input('...')
但是接下来你检查
if (input == '1'):
...
第二个 input
应该是 choice
。同样的道理也适用于 elif(input == '2'):
这条语句。这里的 input
也应该换成 choice
。或者,你可以像 J.F. 建议的那样,使用 raw_input
,并传入 '1'
和 '2'
。
此外,input
函数会自动把 1
和 2
转换成整数,所以你应该检查 if (choice == 1)
,对于 2
也是一样。
最后,你需要有某种形式来实际运行 select()
函数,比如
if __name__ == '__main__':
select()
1
你应该使用 raw_input
而不是 input
。因为 input
会把你输入的内容用 eval
包裹起来,试图把它转换成 Python 代码。所以当你输入 '1' 或 '2' 时,它会被转换成整数,但你实际上是想比较字符串。
再加上 Paul 提到的使用 choice
而不是 input
,这样你就能找到一个有效的解决方案。
另外,在你的条件语句中去掉所有的分号和括号,因为在 Python 中这些都是不必要的:
def select():
convert()
choice = raw_input('Enter Choice Number:')
if choice == '1':
C2F()
elif choice == '2':
F2C()