Python – 让一个变量既是 int 又是 str

标签 python string int primes

这是我的代码:

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() 以重新启动该函数。

请帮我完成这项工作!

最佳答案

对于 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

您应该很少使用输入

您还应该使用 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)) 意味着 Chapter 中的每个 p 都会有一个与其在元组中的索引相对应的值。

关于Python – 让一个变量既是 int 又是 str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30278556/

相关文章:

python - 从python中的嵌套字典创建层次树

c++ - 使用字符串函数将文件中的数据读入结构?

javascript - 如何将速度数组 [x, y, z] 转换为要存储在数据库中的字符串?

java - 是否可以使 System.out.print 以相反的顺序对变量进行排序?

ios - 在 sprite kit Xcode 中创建一个整数数组

python - 更新 PyGTK 组合框时如何保留选择?

python - 谁能解释一下Python中的函数闭包?

python - Django - 信号。简单的例子开始

python - 从python文件中获取字符串

C# 浮点表达式 : strange behavior when casting the result float to int