开发者

How do I get around "ValueError: not enough values to unpack"?

开发者 https://www.devze.com 2022-12-07 20:31 出处:网络
I\'m working on a program that works like so: It asks for 2 inputs at once from the user, both of them are strings.

I'm working on a program that works like so:

It asks for 2 inputs at once from the user, both of them are strings. If 2 strings are given, it prints "Yes". If only one string is given, it assumes the other one as "1" and prints "Maybe". If nothing is given, it prints "No".

The problem is that it doesn't accept nothing for an answer. If I type in only one string or nothing at all, it returns an error.

"ValueError: not enough values to unpack (expected 2, got 1/0)" How do I get around this?

Here is my code:

str1, str开发者_高级运维2 = input("Enter two values: ").split()
if str1 == "" and str2 == "":
    print("No")
elif str1 == str() and str2 == "":
    str2 = "1"
    print("Maybe")
else: print("Yes")


Note- This will work only if some input is given if someone hit the enter without input the error raises

Code:-

str1, *str2 = input("Enter two values: ").split()
if str1 and str2:
    print("Yes")
elif str1 and str2==[]:
    str2="1"
    print("str2 Maybe: "+str2)
else:
    print("No")

Output:-

#Testcase1 when str1 and str2 both input given

Enter two values: 3 7
Yes

#Tescase2 when str1 input given

Enter two values: 5
str2 Maybe: 1

#Testcase3 when no input given

Enter two values: 
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ValueError: not enough values to unpack (expected at least 1, got 0)

To resolve this error ->

(1)Try to take both inputs individually.
(2)Just assign to a single name and check it's length later. credit to ~wwii
0

精彩评论

暂无评论...
验证码 换一张
取 消