为什么我不能在Python 2.7.14中写"meter"而不是"meter'?

2024-09-27 09:23:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python 2.7.14。。。。。我用python andriod Qpython3版本写了这个代码…但是当我在Python2.7.14中使用它时,程序接受带有“”或“”的字符串…在Qpython3中我只需要写meter…这里我必须写“meter”。。。。。 有什么解决办法吗

代码如下:

import time


print("This is a converter.Here, you have to spell the whole name of a unit otherwise  it wont work")
print(' ')  
def converter():
 a=float(input("Enter a number:"    )) 
 print(" ") 
 x=input("from:"    )  
 print(" ")  
 y=input("to:"    )
 print(" ") 
 if x=="meter" and y=="kilometer" or x=="gram" and y=="kilogram":
    print(a/1000)
 elif x=="kilometer" and y=="meter" or x=="kilogram" and y=="gram":
    print(a*1000)
 #just keep adding more convertions starting with elifs inside the define function
 #and keep the else statement at the end of all elifs...
 #and that converter() function call it at the all end just once...
 #infact dont do anything escept adding elif statements....good luck 
 #dont change that float it accepts both integer and float
 else  :
            print("wrong")


 print(" ")
 print('To continue type "next",Thank you.')
 print(" ")
 print('To exit type "quit",Thank you.')
 print(" ")
 s=input()
 if s=="next":
    print(" ")
    converter()
 elif s=="quit":
    time.sleep(1)
 else:
    print("I Can't understand your command")
converter()

Tags: andtheto代码youinputtimeit
1条回答
网友
1楼 · 发布于 2024-09-27 09:23:08

在python2.x中不能使用input()。您应该使用raw_input(),它返回一个字符串,而不是引用一个变量

因此,您编辑的代码应该如下所示:

import time


print("This is a converter.Here, you have to spell the whole name of a unit otherwise  it wont work")
print(' ')

def converter():
    a=float(raw_input("Enter a number:"    )) 
    print(" ") 
    x=raw_input("from:"    )  
    print(" ")  
    y=raw_input("to:"    )
    print(" ") 
    if x=="meter" and y=="kilometer" or x=="gram" and y=="kilogram":
       print(a/1000)
    elif x=="kilometer" and y=="meter" or x=="kilogram" and y=="gram":
        print(a*1000)
        #just keep adding more convertions starting with elifs inside the define function
        #and keep the else statement at the end of all elifs...
        #and that converter() function call it at the all end just once...
        #infact dont do anything escept adding elif statements....good luck 
        #dont change that float it accepts both integer and float
     else:
          print("wrong")


     print(" ")
     print('To continue type "next",Thank you.')
     print(" ")
     print('To exit type "quit",Thank you.')  
     print(" ")
     s=raw_input()
     if s=="next":
         print(" ")
         converter()
     elif s=="quit":
         time.sleep(1)
     else:
         print("I Can't understand your command")
     converter()

一些改进建议:

1.:最好格式化代码。我为你做的

2.:这里:elif s=="quit":您可以编写:import syssys.exit()退出程序

相关问题 更多 >

    热门问题