简体   繁体   English

在while循环中使用raw_input并将其分配给变量?

[英]using raw_input in a while loop and assigning it to a variable?

is42= False
while(raw_input()):
    d = _
    if d == 42:
      is42 = True
    if not is42:
      print d

for this python block of code I want to use outside of the interactive prompt mode. 对于此python代码块,我想在交互式提示模式之外使用。 So I can't use _ as the last output. 所以我不能使用_作为最后的输出。 How do I assign raw_input to a variable? 如何将raw_input分配给变量? I'm doing an exercise off a site. 我正在一个站点外锻炼。 about 5 values is the input and I'm suppose to spit some output out for each corresponding input value. 输入是大约5个值,我想为每个对应的输入值吐出一些输出。 What's the best way to take in this input to do that? 接受此输入的最佳方法是什么?

This appears to be very inefficient logic. 这似乎是非常低效的逻辑。 Do you really need the is42 status flag as well? 您还真的需要is42状态标志吗? If not, you might want something like 如果没有,您可能想要类似

stuff = raw_input()
while stuff:
    if stuff != "42":
         print stuff
    stuff = raw_input()

Does that fix enough of your troubles? 这样足以解决您的麻烦吗?

is42=False
while(!is42):
    d = int(raw_input("Enter a number: "))
    is42 = d==42
    print "d = ", d

That should do it if I understand the requirements of your problem correctly. 如果我正确理解了您的问题的要求,就应该这样做。

Hi and welcome to Python! 嗨,欢迎来到Python!

The raw_input() function returns the input read as a string. raw_input()函数以字符串形式返回输入。 So where you have d = _ , you can replace that with d = raw_input() . 因此,在d = _ ,可以将其替换为d = raw_input() A question I have for you is why you had it inside the while condition? 我要问你的一个问题是,为什么你在while条件下拥有它? If you wanted it to keep asking the user for a number over and over, then replace while(raw_input()): with while True: . 如果您希望它不断询问用户一个数字,则将while(raw_input()):替换为while True: while(raw_input()):

One more thing, raw_input() always returns a string. 还有一件事, raw_input()总是返回一个字符串。 So if you run print '30' == 30 , you'll see that a string representation of 30 is not equal to the number representation of 30. But that's not a problem! 因此,如果您运行print '30' == 30 ,您将看到字符串表示形式30与数字表示形式30不相等。但这不是问题! You can turn the return value of raw_input() into an integer type by replacing d = raw_input() with d = int(raw_input()) . 通过将d = raw_input()替换为d = int(raw_input())可以将raw_input()的返回值转换为整数类型。

Now there will be another problem when the user gives you an input that can't be converted to an integer, but handling that can be an exercise for you. 现在,当用户为您提供无法转换为整数的输入,但是处理可能对您来说是一个练习时,就会出现另一个问题。 :) :)

Final code: 最终代码:

is42= False
while True:
    d = int(raw_input())
    if d == 42:
      is42 = True
    if not is42:
      print d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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