【问题标题】:Python – Have a variable be both an int and a strPython – 有一个变量既是 int 又是 str
【发布时间】:2015-05-16 17:15:10
【问题描述】:

这是我的代码:

def retest2():
    print "Type in another chapter title! Or type \"Next\" to move on."
    primenumbers2()
def primenumbers1():
    print "--------------------------------------------------\nChapters in books are usually given the cardinal numbers 1, 2, 3, 4, 5, 6 and so on.\nBut I have decided to give my chapters prime numbers 2, 3, 5, 7, 11, 13 and so on because I like prime numbers.\n\nType in the chapter title of my book (a prime number) and I will tell you what cardinal number the chapter is."
def primenumbers2():
    prime = (str(input("\n")))
    chapter = (2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233)

    if "Next" in prime or "next" in prime:
        print "--------------------------------------------------\nOnto the next thing."
    elif int(prime) in chapter:
        print "Chapter ",chapter.index(int(prime)) + 1
        retest2()
    elif prime.isalpha:
        print "That is not one of my chapter numbers because {0} is not a prime number. Try again.".format(prime)
        primenumbers2()

primenumbers1()
primenumbers2()

所以我要做的是让用户输入一个素数,输出是与该素数相关的基数。但是,我希望用户可以通过输入"Next""next" 来选择进入下一个功能。因此,我的变量输入prime 需要同时适应字符串和整数输入。所以我将其设置为(str(input("\n"))),然后在需要时将其转换为int(prime)

除了"Next""next" 以外的字符串输入时,一切正常。例如,如果我输入“okay”,我会收到错误消息:

File "prime.py", line x, in primenumbers2
    prime = (str(input("\n")))
  File "<string>", line 1, in <module>
NameError: name 'okay' is not defined

但是如果我输入“4”,它不是一个素数,程序就会运行,我得到:

That is not one of my chapter numbers because 4 is not a prime number. Try again.

然后程序循环回到primenumbers2() 以重新启动该功能。

请帮我完成这项工作!

【问题讨论】:

    标签: python string int primes


    【解决方案1】:

    python2 需要使用raw_input,python2 中的input 基本上是eval(raw_input()),并且由于您没有定义变量okay,所以会出现错误。

    In [10]: prime = (str(input("\n")))
    
    foo
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-10-15ff4b8b32ce> in <module>()
    ----> 1 prime = (str(input("\n")))
    
    <string> in <module>()
    
    NameError: name 'foo' is not defined    
    In [11]: foo = 1 
    In [12]: prime = (str(input("\n")))
    foo
    In [13]: prime = (raw_input("\n"))
    next
    In [14]: print prime
    next
    

    你应该很少使用input

    您还应该使用 while 循环,如下所示:

     def primenumbers2():
        chapter = (
            2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107,
            109,
            113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233)
        while True:
            prime = input("Type in another chapter title! Or type \"Next\" to move on.")
            if "next"  == prime.lower():
                print("--------------------------------------------------\nOnto the next thing.")
                break
            try:
                p = int(prime)
                if p in chapter:
                    print("Chapter {}".format(chapter.index(p) + 1))
                else:
                     print("That is not one of my chapter numbers because {0}"
                      " is not a prime number. Try again.".format(prime))
            except ValueError:
                print("Invalid input")
    

    不完全确定你想做什么,但使用一段时间,检查用户输入是否等于next,如果不尝试使用 try/except 强制转换为 int 是一个更好的主意。

    将章节设为字典也是一个更好的主意,通过按键访问章节号:

    def primenumbers2():
        chaps = (
            2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107,
            109,
            113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233)
    
        chapter = dict(zip(chaps, range(1, len(chaps) + 1)))
        while True:
            prime = input("Type in another chapter title! Or type \"Next\" to move on.")
            if "next" == prime.lower():
                print("--------------------------------------------------\nOnto the next thing.")
                break
            try:
                p = int(prime)
                if p in chapter:
                    print("Chapter {}".format(chapter[p]))
                else:
                    print("That is not one of my chapter numbers because {}"
                          " is not a prime number. Try again.".format(prime))
            except ValueError:
                print("Invalid input")
    

    range(1, len(chaps) + 1)) 表示章节中的每个p 都有一个与其在元组中的索引相对应的值。

    【讨论】:

    • 谢谢,我使用了这个的变体,它可以工作。我没有将else 放在try 块之外,而是将elif p not in chapter 放在try 块中。
    • @theo1010,没有问题,我粘贴了错误的代码,您需要在用户输入 next 时中断 while 或调用其他函数(如果这是您的计划)。我不完全确定你的完整想法是什么。
    【解决方案2】:

    您要做的是将用户输入的值转换为字符串或整数。如果您使用 input,正如 Padraic 所说,它等于 eval(raw_input()),您将评估输入,因为它是一个 python 命令:如果您编写任何不存在的名称,这将引发错误。要解决此问题,请使用 raw_input 函数。它将返回一个str 对象,即输入文本。

    然后,您要查找此文本是数字还是字符串。一种解决方案是使用异常:

    try:
        prime = int(prime)
    
        # Here the code assuming prime is a number, an `int`
    except ValueError:
        # here the code assuming prime is a string, `str`, for example
        # 'Next', 'next' or 'okay'
    

    【讨论】:

    • 如果我输入一个非质数,我会收到一条错误消息:AttributeError: 'int' object has no attribute 'isalpha'
    • @theo1010 抱歉,我没有检查就粘贴了您的代码...如果 prime 是一个数字,那么代码的执行将在 prime = int(prime) 之后继续,而 prime 将是一个 int。所以,你必须假设素数是int
    【解决方案3】:

    尝试使用 isdigit 来避免异常:

    def primenumbers2():
    prime = (str(input("\n")))
    chapter = (2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233)
    
    if "Next" in prime or "next" in prime:
        print "--------------------------------------------------\nOnto the next thing."
    elif prime.isdigit() and int(prime) in chapter:
        print "Chapter ",chapter.index(int(prime)) + 1
        retest2()
    else:
        print "That is not one of my chapter numbers because {0} is not a prime number. Try again.".format(prime)
        primenumbers2()
    

    【讨论】: