String和Integer输入Python

时间:2016-03-27 12:22:10

标签: python string input integer exit

我需要它,以便我可以输入整数和字符串值。这是因为我需要退出'功能,可以退出程序。

   movex = int(input("\nDesired X position, or quit >> "))
    if movey == "q" or movex == "q":
        break
    if movex < gsize and movex >= 0:
        #Do stuff
    movey = int(input("Desired Y position, or quit >> "))
    if movey < gsize and movey >= 0:
        #Do stuff

1 个答案:

答案 0 :(得分:0)

如果您正在使用python,我认为您的sintax可以执行以下操作:

import sys # if you want this what i said in later text...`
movex = raw_input("\nDesired X position, or quit >> ")
if movex == "q":
    break 
# don't really know what you want to do with this but i think you want to use sys.exit() to quit your porgram

movey = raw_input("\nDesired Y position, or quit >> ")
if movey == "q":
    break #same as in first...
try:
    movex_int = int(movex)
    movey_int = int(movey)
    if movex_int < gsize and movex_int >= 0:
          #Do stuff
    if movey_int < gsize and movey_int >= 0:
          #Do stuff

except ValueError: #if not an int the user didn't enter "q" but not either a number
    sys.exit() #this will exit program because parameters aren't expected, but you can do what you want

对于python3,只需使用input而不是raw_input:)