【问题标题】:python seems to skip a line for no reasonpython似乎无缘无故地跳过了一行
【发布时间】:2014-12-12 21:56:26
【问题描述】:

我正在编写一些代码,但我遇到了问题。我编写的函数工作正常,但主循环(应该无限工作)只能正常工作一次。这是代码:

while 1==1:
    choice=int(raw_input("press 1 for encrypt, 2 for decrypt"))
    if choice==1:
        string=raw_input("please enter plaintext here\n")
        print('cipher-text follows and was copied to clipboard "'+encrypt_string(string))+'"'
    elif choice==2:
        string=raw_input("please enter cipher-text here\n")
        print('plaintext follows : "'+decrypt_string(string))+'"'
    else:
        print("please enter a valid option")

问题在于整个循环运行一次,但随后它继续跳过 raw_Input 命令并引发值错误。我不明白为什么它会这样做。有什么想法吗?

编辑,错误:

Traceback (most recent call last):
  File "C:\Users\Raffi\Documents\python\encryptor.py", line 37, in <module>
    choice=int(raw_input("press 1 for encrypt, 2 for decrypt"))
ValueError: invalid literal for int() with base 10: ''

【问题讨论】:

  • edit 提供您遇到的任何错误的全文
  • 哪一行会抛出值错误? decrypt_string() 是做什么的?
  • 您使用的是 Python 2 还是 Python 3?还是您使用from __future__ import print_function? (注意,在 3 中,raw_input 被替换为 inputprint 是一个函数,而不是一个语句。)
  • 鉴于该回溯,看起来您连续按了两次 Enter,第二次击键为 Python 提供了一个空输入行。
  • @MAttDMo decrypt_string 接受一个字符串,编辑它,然后输出一个字符串。

标签: python


【解决方案1】:

似乎(根据 jme 的评论)当您将文本粘贴到终端时,有多个换行符会导致您的程序继续为下一个 raw_input 命令输入任何内容。 earlier question 有几个可能的解决方案:

(1) 使用sys.stdin.read():

print("please enter plaintext here\n")
text = sys.stdin.read()

但是,您必须按下 Ctrl Z / Ctrl D 来表示您已完成输入文本。

(2) 使用Tk.clipboard_get 或类似命令直接从剪贴板读取。

from Tkinter import Tk
root = Tk()
root.withdraw()
...
text = raw_input('Please enter plain text or just press enter to copy from the clipboard\n')
if not text:
    text = root.clipboard_get()

(3) 您也可以继续允许输入,直到输入空行或其他标记文本结尾的方式。

print('Please enter plain text. Enter "stop" when you are finished')
text = ''
while True:
    inp = raw_input()
    if inp == 'stop':
        break
    text += inp

当然,这是假设您要复制的文本中没有“停止”的行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    相关资源
    最近更新 更多