【问题标题】:How do I convert numbers in a string to complete function in python 2.7?如何将字符串中的数字转换为 python 2.7 中的完整函数?
【发布时间】:2019-08-27 19:01:29
【问题描述】:

我正在尝试使用函数、if/elif 和循环编写一些代码。我基于 Learn Python The Hard Way,练习 35。(Python 2,7)

我目前遇到的问题是 def temp 函数。当我输入数字时,我无法让程序接受用户输入。

我收到以下错误:

Traceback (most recent call last):
  File "ex35_1.py", line 53, in <module>
    temp ()
  File "ex35_1.py", line 11, in temp
    if number in next > 5:
TypeError: 'in <string>' requires string as left operand, not int

from sys import exit

def temp():
    print "Good morning."
    print "Let's get ready to kindergarden!"
    print "How cold is it outside?"

    #I think this is where the first problem is. 
        #The number-command is somehow wrong. 
    next = raw_input("> ")
    number = int(next)
    if number in next > 5:
        wool()
    elif number in next =< 6:
        not_wool()
    else:
        print "Fine, we just go!"

def wool():
    print "OK, so it is pretty cold outside!"
    print "Put on the wool."
    print "But is it raining?"
    rain = True

    while True:
        next = raw_input("> ")

        if next == "Yes":
            print "Put on the rain coat!"
            rain()
        elif next == "No" and rain:
            print "It is raining, but I dont wanna stress with the rain coat!"
            rain = False
        elif next == "No":
            print "You dont need a raincoat."
            march("With wool and no raincoat.")
        else:
            print "You should make a choice."
            exit(0)


def march(wit):
    print wit, "You are out the door!"
    exit (0)

def rain():
    print "Got the wellis?"
    march("With wool and rain stuff!")

def not_wool():
    print "There is no need for all that clothing."
    march("Remember the lunch pack!")

temp ()

任何关于上述错误的提示,以及可能的其他错误将不胜感激。

【问题讨论】:

    标签: string python-2.7 int typeerror operands


    【解决方案1】:

    由于数字已经是一个整数,你可以直接比较它。

    number > 5
    

    【讨论】:

      【解决方案2】:

      您转换了一个 int 并将其分配给变量 number。然后你尝试在原始字符串中找到那个 int。

      为什么需要在字符串中搜索int?你不能只评估 int 吗?

      您还可以在将输入分配给 next 时将输入转换为 int 来剪掉一行。

      还有=

      def temp():
          print "Good morning."
          print "Let's get ready to kindergarden!"
          print "How cold is it outside?"
      
          next = int(raw_input("> "))
      
          if next  > 5:
              wool()
          elif next <= 6:
              not_wool()
          else:
              print "Fine, we just go!"
      

      【讨论】:

        猜你喜欢
        • 2016-06-04
        • 2014-05-05
        • 1970-01-01
        • 2019-07-03
        • 1970-01-01
        • 1970-01-01
        • 2010-12-27
        • 1970-01-01
        • 2014-01-13
        相关资源
        最近更新 更多