python按键退出无限循环,Python-停止无限循环的键盘命令?

I was playing around with some Python code and created an infinite loop:

y = 0

x = -4

itersLeft = x

while(itersLeft<0):

y = y + x

itersLeft = itersLeft - 1

print "y = ",y, "itersLeft = ", itersLeft

print y

Is there a keyboard shortcut that would allow me to stop the looping - allowing me to fix the loop and then restart it?

I've tried Ctrl+C and didn't have any luck. If it helps I'm using a Windows 7 environment.

Thanks.

EDIT

I should have also mentioned that I'm using Aptana Studio 3 and attempted to run the Ctrl+C command within that. It doesn't work there - but trying it within the regular console works fine. I'm assuming it must be because of the Aptana environment.

解决方案

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

### 回答1: 你可以使用 Python 的 `input()` 函数来等待用户输入,然后在循环中使用它来让程序等待用户的下一个输入。下面是一个示例代码: ```python while True: print("等待用户按下回车键...") input() # 等待用户按下回车键 print("用户按下了回车键!") ``` 上面的代码将会不断循环,直到用户按下回车键。每次循环会输出一条消息,告诉用户程序正在等待他们按下回车键。当用户按下回车键后,程序将会输出另一条消息来告诉用户他们按下了回车键。 你可以根据需要修改上面的代码,以便满足你的具体需求。 ### 回答2: 在Python中,可以使用`input()`函数实现等待按键之后循环的功能。 `input()`函数可以让程序等待用户输入,并将用户输入的内容作为字符串返回。我们可以在循环中使用`input()`函数来等待用户按键,然后根据用户的输入来判断是否继续循环。 下面是一个示例代码: ```python while True: key = input("请按下任意键(按下Enter键结束循环):") if key: print("继续循环...") else: print("循环结束") break ``` 以上代码实现了一个无限循环,每次等待用户按下任意键。如果用户按下了任意键(除了Enter键),程序会输出"继续循环..."并继续进行下一次循环;如果用户按下了Enter键(即不输入任何内容),则会输出"循环结束"并跳出循环。 你也可以根据具体需求修改代码,例如根据不同的按键值执行不同的操作。 ### 回答3: 在Python中,可以使用内置的input()函数实现等待键盘按键之后的循环。input()函数会暂停程序的执行,直到用户输入了某个字符并按下回车键。 可以将input()函数放在一个while循环中,使程序不断地等待用户按键并执行相应的操作。例如: ```python while True: key = input("请按下任意键:") print("你按下了:" + key) ``` 上述代码会不断循环,直至用户按下任意键并按下回车键后才会继续执行循环的下一次迭代。在每次迭代中,会打印出用户按下的键。 此外,如果只关心某些特定的按键,可以通过if语句来判断用户的输入,并执行相应的操作。例如,只在用户按下某个特定的键(如“q”)时退出循环: ```python while True: key = input("请按下任意键(按下q退出):") print("你按下了:" + key) if key == "q": break ``` 在上述代码中,如果用户按下的键与字符"q"相等,则通过break语句跳出循环,结束程序的执行。 这样,就可以在Python中实现等待按键之后的循环。注意,在使用input()函数时,应注意对用户输入的数据进行适当的处理,以避免潜在的错误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值