从右到左获取输入

时间:2014-06-14 20:15:25

标签: python input

我正在编写一个计算随机加法数学问题的简单程序,并要求用户输入答案。

当用户输入答案时,计算机从左向右输入输入的键。我希望输入执行相反的操作:从右到左。

img

http://euclidmagazine.com/2010/12/why-do-we-carry-in-addition/

当然,添加的方式是首先在最右边添加列 - 单个数字,然后是10和100,等等。

例如,如果我输入上面这个添加问题的答案(635),然后我按照那个顺序键入它(6然后是3然后是5),我希望6出现在9 + 6之下,然后当我类型3我希望它在5 + 7下移动6(向左),3将出现在9 + 6下面,然后当我输入5时它移动6下3 + 2,移动3在5 + 7下,然后将5放在9 + 6下。

我可以使用替代输入功能或模块吗?或者你有一个超级秘密的技术?感谢。

这是我的代码:

# MAIN
def main():

    keepGoing = "Y"
    while keepGoing == "Y":
        keepGoing = "N"
        entranceMessage()
        number1, number2 = calculateProblem()
        userInput = getInput(number1, number2)
        calculateResults(userInput, number1, number2)
        keepGoing = input("Would you like to try another problem? \
(Enter \"Y\" for \"Yes\", or any other key for \"No\".): ")
    exitMessage()

# DISPLAY OPENING MESSAGE
def entranceMessage():

    print()
    print("2. Math Quiz (Page 235)")
    print("This program will prompt you to answer a series of random mathematical problems.")

# INPUT
def getInput(number1, number2):

        print("Answer the following math problem: ")
        print("")
        if (number1 < 10):
            print("  ", number1)
        else:
            print(" ", number1)
        if (number2 < 10):
            print("+ ", number2)
        else:
            print("+", number2)
        print("_____")
        print("          ")
        result = (number1 + number2)
        if (result >= 100):
            userInput = float(input(" "))
        elif ((result >= 10) and (result < 100)):
            userInput = float(input("  "))
        elif ((result >= 0) and (result < 10)):
            userInput = float(input("   "))
        return userInput


# PROCESS
def calculateProblem():

    import random
    number1 = random.randint(1, 100)
    number2 = random.randint(1, 100)
    return number1, number2

# OUTPUT
def calculateResults(userInput, number1, number2):

    result = (number1 + number2)
    if (userInput == result):
        print()
        print("Correct!")
    else:
        print()
        print("Sorry, the answer is:", result)


# DISPLAY CLOSING MESSAGE
def exitMessage():

    print("Thank you. Exiting the program..")

# CALL THE MAIN FUNCTION    
main()

如果您在我的代码中注意到函数&#34; getInput&#34; (最后一个If-elif),在最后我有一个方法将初始光标放在与答案相关的正确对齐方式上,但是(A)这种方式给出了答案是什么的线索,(B)它不是我想要的。

2 个答案:

答案 0 :(得分:1)

如果您使用的是基于Unix的系统,一种方法是使用curses库。 Curses通常用于高级终端操作,并且可以在终端中的任何地方写入文本,更改字体颜色等,并且还可以使用除Python之外的语言(包括C)的变体。它也常用于像Rogue这样的基于文本的游戏。

Here's a link to the official documentation

Here's a good tutorial

答案 1 :(得分:0)

这适用于UNIX系统,使用this answer中的getch从输入中读取单个字符。

import sys

def cursor_left():
    """Print control characters to move the cursor left one column."""
    sys.stdout.write(chr(27) + '[D')  # 27 is ESC

def print_blank(number):
    """Print blank character a given number of times."""
    for i in range(0, number):
    sys.stdout.write(" ")

def right_to_left_input(number_of_digits):
    """Have user input a number from right to left, digit by digit."""
    print_blank(number_of_digits)
    digits = ""
    while (1):
    cursor_left()
        userInput = getch()
    sys.stdout.write(userInput)
    digits = userInput + digits  # string concatenation, not addition
        if (len(digits) >= number_of_digits):
        break
    cursor_left()
    return(digits)

有关在xterm上移动光标的控制序列,请参阅this page

或者,根据您使用的操作系统或shell,您可以在最后几个字符上退格并每次重新打印它们吗?

另见this chart of control characters。尝试ASCII 8(退格); ASCII 127(删除);或ASCII 10(换行;如果你换行但没有换页,它可能允许你在某些系统上再次重新输入同一行。)

例如,您可以打印chr(8)来打印ASCII字符8(退格)。

有关如何从用户一次读取单个字符的信息,请参阅this answer

如果尝试运行getch时出错,则以下代码可能仍然有效;它在UNIX系统上对我有用;但它要求用户在每个数字后按Enter键。它假设用户一次只输入一个数字。

def cursor_up():
    """Print control characters to move the cursor up one line."""
    sys.stdout.write(chr(27))  # ESC
    sys.stdout.write(chr(91))  # [
    sys.stdout.write(chr(65))  # A

def backspace(number):
    """Print backspace character a given number of times."""
    for i in range(0, number):
        sys.stdout.write(chr(8))  

def print_blank(number):
    """Print blank character a given number of times."""
    for i in range(0, number):
        sys.stdout.write(" ")

def print_cursor():
    sys.stdout.write("_")  # use as cursor

def right_to_left_input(number_of_digits):
    digits = ""
    print ""
    cursor_up()
    while(1):
        have_digits = len(digits)
        if(have_digits >= number_of_digits):
            break
        print_blank(number_of_digits - have_digits)
        print_cursor()
        sys.stdout.write(digits)
        print_blank(1)   # overwrite the user's previous input
        backspace(have_digits + 2)   # move back to cursor position
        userInput = sys.stdin.readline()
        cursor_up()  # undo the carriage-return entered by the user.
        digit = userInput[0]    # first character in string
        digits = digit + digits  # string concatenation, not addition
    return(digits)