我目前正在做一个项目,想知道是否可以让我的输入接受 int 或 str 值。这是到目前为止的代码:
`NumOfKeys = int(input("你想添加多少个键:"))
for i in range(NumOfKeys):
TypeInput = input("Is your key:value a string or int value? (str/int/both)")
if TypeInput.lower() == "str":
KeyInput = input("Please input your key")
ValueInput = input("Please input your value")
elif TypeInput.lower() == "int":
KeyInput = int(input("Please input your key"))
ValueInput = int(input("Please input your value"))
elif TypeInput.lower() == "both":
# I want the key to be either str or int
# I want the value to be either str or int`
试试这个:
NumOfKeys = int(input("How many keys would you like to add:"))
for i in range(NumOfKeys):
KeyInput = input("Please insert your key")
if KeyInput.isdigit():
TypeInput = int(KeyInput)
ValueInput =input("Please input your value")
if ValueInput.isdigit():
ValueInput = int(ValueInput)
希望是你的意图。让我知道是否可以。 如果键同时包含数字和字符,则必须是字符串。
python 中的输入将返回一个字符串。 将输入存储在变量中后,如果需要,您可以尝试使用 int() 函数将其解析为 int,但它将首先存储为字符串。
I am practicing python at the time I got this idea.It's really helpful for the beginners
Try this:
=========
first_number=(input("Enter the first number: "))
second_number=(input("Enter the second number: "))
if first_number.isdigit() and second_number.isdigit():
conversion_first=int(first_number)
conversion_second=int(second_number)
print(conversion_first*conversion_second)
elif(first_number.isdigit() !=True ):
print(f"Enter the first number correctly '''{first_number}''' !!! that is not a string type, should enter number only: ")
elif(second_number.isdigit()!=True):
print(f"Enter the second number '''{second_number}''' !!! should be number only")
else:
print("No...it is not a number")
是的,可以让您的输入接受 int 或 str 值。一种方法是使用 try-except 块来检查输入是否可以转换为 int,然后相应地设置键输入。这是一个例子:
NumOfKeys = int(input("How many keys would you like to add:"))
for i in range(NumOfKeys):
TypeInput = input("Is your key:value a string or int value? (str/int/both)")
if TypeInput.lower() == "str":
KeyInput = input("Please input your key")
ValueInput = input("Please input your value")
elif TypeInput.lower() == "int":
KeyInput = int(input("Please input your key"))
ValueInput = int(input("Please input your value"))
elif TypeInput.lower() == "both":
KeyInput = input("Please input your key")
try:
KeyInput = int(KeyInput)
except ValueError:
pass
ValueInput = input("Please input your value")
try:
ValueInput = int(ValueInput)
except ValueError:
pass
在此示例中,如果用户为类型输入选择“两者”,则键输入首先设置为字符串输入。然后,使用 try-except 块检查键输入是否可以转换为 int。如果可以,则将键输入设置为 int 值,否则它仍然是一个字符串。然后将相同的过程应用于值输入。
有关更多信息,您可以参考我的页面https://thepythoncoding.blogspot.com