简体   繁体   中英

String and Integer input Python

I need it so that I can input both integer and string values. This is because i need a 'quit' function, which enables to quit the program.

   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

If you're using python, what i suppose by your sintax you could do the following:

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

For python3 just use input instead of raw_input :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM