I am a complete beginner at learning python 3. I came across a problem. Please take a look at the code within the three stars:
s = input("Enter the value of N A B with white space in between ")
N, A, B=list(s.split())
def input_for_faces(*args):
NumberOfA=0
NumberOfB=0
for x in args:
if x == int(A):
NumberOfA += 1
for y in args:
if y == int(B):
NumberOfB += 1
listAB=[NumberOfA, NumberOfB]
return listAB
# ***
var=input("Enter the values on the faces of the cube seperated by commas ")
NA, NB=input_for_faces(var)
print(input_for_faces(var))
# ***
print("The probability of the chef winning is "+str((int(NA)/int(N)*(int(NB)/int(N))))
This method of input for *args
didn't give the right output(It worked but gave wrong answer). But when I gave direct values for args, the program worked correctly.
Direct input refers to:
s = input("Enter the value of N A B with white space in between ")
N, A, B=list(s.split())
def input_for_faces(*args):
NumberOfA=0
NumberOfB=0
for x in args:
if x == int(A):
NumberOfA += 1
for y in args:
if y == int(B):
NumberOfB += 1
listAB=[NumberOfA, NumberOfB]
return listAB
# ***
NA, NB=input_for_faces(1,1,1,1,1)
# ***
print("The probability of the chef winning is "+str((int(NA)/int(N))*(int(NB)/int(N))))
Please tell me what I did wrong.
1, In your code in this part in the 'if' condition you are comparing a string to an integer so that condition will become false and does not count 'NumberOfA'
for x in args:
if x == int(A):
NumberOfA += 1
for y in args:
if y == int(B):
NumberOfB += 1
listAB=[NumberOfA, NumberOfB]
output:
Enter the value of N A B with white space in between 1 1 1
Enter the values on the faces of the cube seperated by commas 1,1,1,1,1
[0, 0]
The probability of the chef winning is 0.0
>>>
2, you are passing single string as input for *args so to pass multiple arguments you have convert input as list lvar=var.split(',') and then by using *lvar in function call {NA, NB=input_for_faces(*lvar)}, will pass multiple arguments one by one from the list
s = input("Enter the value of N A B with white space in between ") N, A, B=list(s.split())
def input_for_faces(*args):
NumberOfA=0
NumberOfB=0
for x in args:
if x == A:
NumberOfA += 1
for y in args:
if y == B:
NumberOfB += 1
listAB=[NumberOfA, NumberOfB]
return listAB
# ***
var=input("Enter the values on the faces of the cube seperated by commas ")
lvar=var.split(',')
NA, NB=input_for_faces(*lvar)
print(input_for_faces(*lvar))
# ***
print("The probability of the chef winning is "+str((int(NA)/int(N)*(int(NB)/int(N)))))
output:
Enter the value of N A B with white space in between 1 1 1
Enter the values on the faces of the cube seperated by commas 1,1,1,1,1
[5, 5]
The probability of the chef winning is 25.0