如何获得打印以重新打印输入,但使用abs、chr、len函数?

2024-04-26 03:36:42 发布

您现在位置:Python中文网/ 问答频道 /正文

除了getValue函数我什么都做了。系统提示我输入正整数、负整数、48-122之间的整数和字符串。一旦我把它们全部输入,我希望它能重新打印它们,除了显示的abs、chr和len函数。这是我得到一个语法错误。你知道吗

def main():
    posInteger()
    negInteger()
    myChar()
    myString()
    getValues()

def posInteger():
    #Declaring positive integer value
    posInt = (input('Enter a positive integer: ')


def negInteger():
    #Declaring negative integer value
    negInt = input('Enter a negative integer:')

def myChar():
    #Declaring integer
    myCh = input('Enter an integer between 48 and 122 incluseive: ')

def myString():
    #Declaring string 
    myStr = input('Enter a string: ')

def getValues():
        #Prints the variables back out to user
    print ('The positive int is,', abs(posInt))
    print('textbody', abs(negInt))
    print('textbody', chr(myCh))
    print('textbody', len(myStr))
#raiser posInt by power 4

main()

编辑:

这是我的程序运行时的样子(w/error)

Enter a positive integer: 45
Enter a negative integer:-1
Enter an integer between 48 and 122 incluseive: 90
Enter a string: daf
Traceback (most recent call last):
  File "D:\.Drexel Affil\info\info108\W3\scrap.py", line 38, in <module>
    main()
  File "D:\.Drexel Affil\info\info108\W3\scrap.py", line 7, in main
    getValues()
  File "D:\.Drexel Affil\info\info108\W3\scrap.py", line 32, in getValues
    print('The positive int is,', abs(posInt))
TypeError: bad operand type for abs(): 'str'

Tags: inputstringmaindefintegerabsfileprint
3条回答

如果这是Python2…原始输入对字符串有效,那么您甚至不需要所有列出命令的函数。你知道吗

posInt = (input('Enter a positive integer: '))
negInt = input('Enter a negative integer:')
myCh = input('Enter an integer between 48 and 122 incluseive: ')
myStr = raw_input('Enter a string: ')
print ('The positive int is,', abs(posInt))
print('textbody', abs(negInt))
print('textbody', chr(myCh))
print('textbody', len(myStr))
#raiser posInt by power 4

在这里,问题不在于使用函数,而在于变量管理。你知道吗

例如,在posInteger中读取的变量posInt是此函数的局部变量。因此,您无法在getValues中获得它的值,因为它在posInt返回时就被遗忘了。你知道吗

所以你至少可以走两条路中的一条。你知道吗

第一种方法,最简单:停止使用函数,将所有代码放在main函数中。工作,但不是一个好的思考方式。你知道吗

第二种更好的方法:返回相应函数末尾的posInt&co.变量,并将它们作为参数提供给getValues函数。您可以在处理函数的教程(如this one)中获得有关如何执行此操作的更多详细信息。你知道吗

默认情况下,Python函数中的变量是函数的local。所以这不起作用:

def f():
    a = 1

f()
print(a)

为了使a在函数外部可用,必须使用global

def f():
    global a
    a = 1

注意:你的语法错误在这一行(你有一个多余的左括号):

osInt = (input('Enter a positive integer: ')

相关问题 更多 >