python中的“如果条件”未设置按“ Enter”时为其赋予的值

时间:2019-06-02 07:27:38

标签: python-3.x

两个输入足以使程序运行,但在极少数情况下,会使用第三个输入C,但其他时间取决于C和A的长度。

A = int(input("Enter A:"))
B = int(input("Enter B:"))
tempC = input("Enter C:(If None press Enter)")
C = ""

counter1 = len(str(A))
counter2 = len(str(B))

print("counter value is:" + str(counter1)+ " and " + str(counter2))
print("temp value is:" + str(tempC))

if counter1 == counter2:
    if tempC and (counter1 == 1):
        C = "10"
    elif tempC and (counter1 == 2):
        C = "100"
    elif tempC and (counter1 == 3):
        C = "1000"
else:
    print("Lengths are not same")

print("Value of C is: " + str(C))

期望的输出-当按下enter键并且counter1 = 2

Enter A:45
Enter B:54
Enter C:(If None press Enter)
counter value is:2 and 2
temp value is:
Value of C is: 100

获得的输出

Enter A:45
Enter B:45
Enter C:(If None press Enter)
counter value is:2 and 2
temp value is:
Value of C is:

1 个答案:

答案 0 :(得分:0)

我认为您应该尝试:

if tempC=="" and (counter1 == 2):

这应该可以解决您的问题。

此外,C已经是一个字符串,因此您可以简单地使用C而不是str(C)

因此,根据您的修改,您的代码是:

A = int(input("Enter A:"))
B = int(input("Enter B:"))
tempC = input("Enter C:(If None press Enter)")
C = ""

counter1 = len(str(A))
counter2 = len(str(B))

print("counter value is:" + str(counter1)+ " and " + str(counter2))
print("temp value is:" + str(tempC))

if counter1 == counter2:
    if tempC=="" and (counter1 == 1):
        C = "10"
    elif tempC=="" and (counter1 == 2):
        C = "100"
    elif tempC=="" and (counter1 == 3):
        C = "1000"
    elif tempC=="" and (counter1 == 4):
        C = "10000"
else:
    print("Lengths are not same")


print("Value of C is: " + str(C))