gpt4 book ai didi

python - python中的输入只能是字符串

转载 作者:行者123 更新时间:2023-12-01 01:28:03 24 4
gpt4 key购买 nike

我是 Python 初学者,所以请不要使用复杂或高级的代码。

我有三个 if 条件,我希望得到某些响应,并且我希望我的代码只给出一个响应。

  1. 首先,我希望输入仅以字符串形式回答,而不是整数或浮点形式

    f = input("Please enter your name :")
  2. 如果给出整数或 float ,它应该给出错误

    if type (f)== int or float :
    print("Invalid entry")
  3. 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

<小时/>PS。当涉及到名称时,请注意验证输入的严格程度。宁可接受不寻常的输入。否则,您可能会收到诸如“John Smith the 3rd”、“Steve O'Reilley”或“田中太郎”等名字的人的投诉。相关阅读: Falsehoods Programmers Believe About Names

关于python - python中的输入只能是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53173087/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com