i am a complete noob to programming and i got an assignment from the online course where I am learning, mine also gives the output, but it is not same as the instructor's method. This works for me and this method was easy for me. but i am not sure is this the right method or had i done something wrong? could someone help?
I was not allowed to use choice()
**
import random
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
a=len(names)
random_name=random.randint(0,a)
print(f"{names[random_name]} is going to pay the bill")
**
CodePudding user response:
Welcome! First of all you need to describe what exactly your problem and what is the problem you are facing. It looks like you even have not tried to run that code. I will recommend an online interpreter to you to test your code on. You may use that https://www.online-python.com/
Secondly "import" statement must be in lower case not "Import"
Finally the code works only incase of the string (names) is separated by a comma followed by space ", " same as the split string used. for example "a,b,c" is not going to work, but "a, b, c" does
random.randint(0,a) (a is included; may be returned) so it must be a-1 to avoid IndexError: list index out of range
Fixed code
import random
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
a=len(names)
random_name=random.randint(0,a-1)
print(f"{names[random_name]} is going to pay the bill")
CodePudding user response:
no, the code is not right.The error can be solved by replacing "Import" by "import".