- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 Python 初学者,所以请不要使用复杂或高级的代码。
我有三个 if
条件,我希望得到某些响应,并且我希望我的代码只给出一个响应。
首先,我希望输入仅以字符串形式回答,而不是整数或浮点形式
f = input("Please enter your name :")
如果给出整数或 float ,它应该给出错误
if type (f)== int or float :
print("Invalid entry")
if f=="" :
print("Invalid input. Your name cannot be blank. ")
我已经尝试过
f = str(input("Please enter your name :"))
它不起作用,我的代码仍然接受整数和字符串中的 ans。
如果我输入字符串,它会给出以下响应:
if type (f)== int or float :
print("Invalid entry")
我是一个初学者,所以我可能犯了很多错误。我们将不胜感激您的耐心等待。
最佳答案
如果您使用的是 Python 3.X,input()
始终返回一个字符串。请注意,有一些字符串,例如 "1"
,它们仍然是字符串,尽管它们看起来很像数字。
我认为您实际上想要的是验证字符串仅包含字母字符,在这种情况下您可以这样做:
s = input("Enter your name: ")
if not s.isalpha():
print("Please enter only alphabetical characters for your name.")
或者您可能想接受除仅由数字组成的字符串之外的所有字符串。
s = input("Enter your name: ")
if s.isdigit():
print("Your name cannot be a number.")
或者您只想接受根本不包含任何数字的字符串?
s = input("Enter your name: ")
if any(char.isdigit() for char in s):
print("Please do not include digits in your name.")
如果您使用的是 Python 2.7 或更低版本,input()
可以返回字符串、整数或任何其他类型的对象。这通常比其值(value)更令人头痛,因此我建议切换到 raw_input()
,此时上述所有建议都适用。
一旦您获得了验证条件的正确逻辑,您可能会想“好吧,但是我如何让程序返回到第一个 input()
调用,以便用户得到还有一次输入正确输入的机会吗?”。如果是这样,您可能会发现这很有用:Asking the user for input until they give a valid response
关于python - python中的输入只能是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53173087/
有一条(相对)众所周知的 Perl 公理:“只有 Perl 可以解析 Perl”。我想知道 Perl 6 是否仍然如此? 扩大讨论...考虑到 PyPy 最近的更新,我想到了这个问题。 Perl 独特
这是设置。在上一个问题中,我发现我可以通过子组件中的状态传递对象属性,然后使用 componentDidUpdate 获取该对象属性。在这种情况下,状态和属性都称为到达。 这是基本代码... expo
我运行的是 10.5.2 社区版。我已经标记了 源/主要/资源 作为源目录。我可以右键单击并“编译”某些文件,据我所知,这意味着 IDE 将文件复制到与发送类文件的“com.mydomain.pack
我是一名优秀的程序员,十分优秀!