![](/img/trans.png)
[英]In Python, is there a way to create a function that will accept both an integer and/or string input?
[英]Can you use input to accept both an integer and a string?
我有一个正在使用Python练习的小脚本。 我在让输入接受if语句的数字以及接受字符串为小写字母方面遇到麻烦。
如果用户输入“ 99”,我想告诉我的脚本任何输入,然后关闭程序。 到目前为止,它在我有int(input())
地方工作,但在我有input()
地方却无法工作。 我在做错什么还是我不能做的事情?
现在我的if
语句看起来像:
if choice1 == 99:
break
我应该通过引用将99变成字符串吗?
也许是这样的:
if choice1 == "99":
break
这是脚本:
global flip
flip = True
global prun
prun = False
def note_finder(word):
prun = True
while prun == True:
print ('\n','\n','Type one of the following keywords: ','\n','\n', keywords,)
choice2 = input('--> ').lower()
if choice2 == 'exit':
print ('Exiting Function')
prun = False
start_over(input)
elif choice2 == 99: # this is where the scrip doesnt work
break # for some reason it skips this elif
elif choice2 in notes:
print (notes[choice2],'\n')
else:
print ('\n',"Not a Keyword",'\n')
def start_over(word):
flip = True
while flip == True:
print ('# Type one of the following options:\n# 1 \n# Type "99" to exit the program')
choice1 = int(input('--> '))
if choice1 == 99:
break
elif choice1 < 1 or choice1 > 1:
print ("Not an option")
else:
flip = False
note_finder(input)
while flip == True:
print ('# Type one of the following options:\n# 1 \n# Type "99" to exit the program')
choice1 = int(input('--> '))
if choice1 == 99:
break
elif choice1 < 1 or choice1 > 1:
print ("Not an option")
else:
flip = False
note_finder(input)
所以input()
总是返回一个字符串。 您可以在此处查看文档:
https://docs.python.org/3/library/functions.html#input
您可以做的是这样的:
choice2 = input('--> ')
if choice2.isnumeric() and (int(choice2) == 99):
break
这样可以避免您键入检查并捕获不重要的错误。
请参见以下有关等数字如何与不同数字类型一起使用的信息:
In [12]: a='1'
In [13]: a.isnumeric()
Out[13]: True
In [14]: a='1.0'
In [15]: a.isnumeric()
Out[15]: False
In [16]: a='a'
In [17]: a.isnumeric()
Out[17]: False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.