除了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'
如果这是Python2…原始输入对字符串有效,那么您甚至不需要所有列出命令的函数。你知道吗
在这里,问题不在于使用函数,而在于变量管理。你知道吗
例如,在
posInteger
中读取的变量posInt
是此函数的局部变量。因此,您无法在getValues
中获得它的值,因为它在posInt
返回时就被遗忘了。你知道吗所以你至少可以走两条路中的一条。你知道吗
第一种方法,最简单:停止使用函数,将所有代码放在
main
函数中。工作,但不是一个好的思考方式。你知道吗第二种更好的方法:返回相应函数末尾的
posInt
&co.变量,并将它们作为参数提供给getValues
函数。您可以在处理函数的教程(如this one)中获得有关如何执行此操作的更多详细信息。你知道吗默认情况下,Python函数中的变量是函数的local。所以这不起作用:
为了使
a
在函数外部可用,必须使用global
:注意:你的语法错误在这一行(你有一个多余的左括号):
相关问题 更多 >
编程相关推荐