Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python While/for/if语句_Python_Loops_Printing_While Loop - Fatal编程技术网

Python While/for/if语句

Python While/for/if语句,python,loops,printing,while-loop,Python,Loops,Printing,While Loop,我写了一个程序,将输入的数字乘以127。输入不接受alpha和数字9 除了数字9,它不允许任何包含9的数字,例如99、19等。我们能克服这个问题吗 另外,如果我输入“99”,它会打印两次“禁止号码”。这与第一句话有关吗 banned_number = "9" while True: number = input("number ") for items in number: if items in banned_number: print

我写了一个程序,将输入的数字乘以127。输入不接受alpha和数字9

除了数字9,它不允许任何包含9的数字,例如99、19等。我们能克服这个问题吗

另外,如果我输入“99”,它会打印两次“禁止号码”。这与第一句话有关吗

banned_number = "9"
while True:
    number = input("number ")

    for items in number:
        if items in banned_number:
            print ("Banned number.")
        elif number.isalpha():
            print ("Sorry, numbers only.")
        elif number.isdigit():
            a = int(number)
            print(a* 127)
我知道这个程序是无用的,它显然是-我在练习循环时偏离了轨道,这是最终的形状。有没有办法缩短代码?我们能用一个简单的代码使这两个elif都过时吗


我非常感谢您的耐心,因为我上周才开始使用Python,谢谢。

将逻辑从循环中去掉,并反转成员检查:

banned_number = "9"
while True:
    number = input("number ")
    if banned_number in number:
        print ("Banned number.")
    elif number.isalpha():
        print ("Sorry, numbers only.")
    elif number.isdigit():
        a = int(number)
        print(a* 127)

首先,词法比较将获取数字作为字符串的错误结果

因此,如果您对要检查的特定类型感兴趣,则需要将
int
int
str
进行比较,以获得正确的结果

您可以使用
isinstance(a,type)
检查值的数据类型,这是执行此操作的
标准方法。您可以这样做:

banned_number = [9, 1]

while True:
    input_num = input("number ")
    # This will work for both Python 2.x and Python 3.x
    try : 
        number = int(input_num)
    except :
        number = input_num

    if number in banned_number:
        print ("Banned number.")
    elif isinstance(number, str):
        print ("Sorry, numbers only.")
    elif (isinstance(number, int) or isinstance(number, float)):
        a = int(number)
        print(a* 127)
这将导致:

# for input 9
Banned number. 

# for input 'a'
Sorry, numbers only.

# for input 99
12573

另外,它之所以要为输入打印两次,是因为这将被视为两个字符串,即
'9'和'9'
,因此在循环时打印了
禁止的数字。
两次。

假设我们有两个不同的禁止的数字,9和1。那我们怎么办呢?如果我们将其恢复为for循环,那么如果我们键入11、99等,是否有任何方法可以使其停止打印“禁止编号”两次?谢谢。@Ramon-这将是
禁止的\u编号不在编号中,而其他\u编号不在编号中
,或者更一般的
不在编号中(n在编号中表示n在禁止的\u编号)
,或者
设置(编号)-设置(禁止的\u编号)=设置(编号)
。没有理由使用循环。###elif isinstance(数字,str):##让我们失望。“数字”来源于输入,即str,因此我们不能超出这一行?谢谢。这个答案似乎使用的是Python2.x,因为它需要
input()
返回一个数字。经过编辑以支持Python2和Python3。我在使用Python2,而您似乎在使用Python3。感谢您的支持-非常好用。我将做一些关于try/except&isinstance的练习,以完全理解它们。您可以参考此链接获得帮助-