意外错误在print()functuon中添加字符串时

时间:2018-01-06 09:35:27

标签: python-3.6

我有一个简单的函数 fact()来打印要在运行时输入的数字的阶乘。 在下面给出的代码中,一切正常。

# Find factorial of a number...

def fact():
    number = int(input('Please enter a number: '))
    tmp = 1
    while number > 0:
        tmp *= number
        number -= 1
    print(tmp)
    ask = input('Do you want to try again... [y/n]: ')
    if ('y' or 'Y') in ask:
        fact()
    else:
    print('Thank you for using my tool. Good bye')

fact()

但是如果我在第一个print()函数中添加一些字符串,我会得到“ask = input ...”这一行的语法错误。这是下面的代码。

# Find factorial of a number...

def fact():
    number = int(input('Please enter a number: '))
    tmp = 1
    while number > 0:
        tmp *= number
        number -= 1
    print("Factorial of %d is %d" %(number, tmp)
    ask = input('Do you want to try again... [y/n]: ')
    if ('y' or 'Y') in ask:
        fact()
    else:
        print('Thank you for using my tool. Good bye')

fact()

我有最后一个问题。我的程序问我是否想再试一次。如果我键入y并输入,则应该按原样运行。但是,如果我输入Y,它会显示 else 语句。

我在Debian中使用python3.6.4rc1。

2 个答案:

答案 0 :(得分:1)

这应该有用!

def fact():
    number = int(input("Please enter a number: "))
    tmp = 1
    while number > 0:
        tmp *= number
        number -= 1
    print("Factorial of %d is %d" %(number, tmp))
    ask = input("Do you want to try again... [y/n]: ")
    if ask in ['y','Y']:
        fact()
    else:
        print('Thank you for using my tool. Good bye')


fact()

答案 1 :(得分:0)

我必须保留 number 变量的值,因为它将在循环结束时变为0。否则我的程序将打印 0的Modulas是' some_number 。现在我有正确的代码......

def fact(): 
    number = int(input("Please enter a number: "))
    preserve_number = number
    tmp = 1 
    while number > 0: 
        tmp *= number 
        number -= 1 
    print("Factorial of %d is %d" %(preserve_number, tmp)) 
    ask = input("Do you want to try again... [y/n]: ") 
    if ask in ['y','Y']: 
        fact() 
    else: 
        print('Thank you for using my tool. Good bye') 
fact()