def b_function(low, high):
g = []
for i in range(low,high):
if i % 3 ==0 or i % 7 ==0 or i % 15 ==0:
#print(str(g) +" ",end = " ")
g.insert(len(g),i)
#i.replace("15","boo")
#if i % 15 ==0:
#g.append("Boo")
print(g)
if __name__ == "__main__":
num_1 = int(input("Please input the lower limit:\n"))
num_2 = int(input("Please input the upper limit:\n"))
c = b_function(num_1,num_2)
I am letting the user input the range and how would I replace all the numbers that are divisible by 15 with string "go".
An easy way to modify a list is to use a comprehension that creates another list:
>>> numbers = [5, 10, 15, 20, 25, 30, 35, 40, 45]
>>> [n if n % 15 else "go" for n in numbers]
[5, 10, 'go', 20, 25, 'go', 35, 40, 'go']
Have you run your code once? It raises error and may not work like you expected.
# there are more conditions than number divisible by 15,
# the if statement execute for the first condition that is True,
# in this case, all number divisible by 3
if i % 3 ==0 or i % 7 ==0 or i % 15 ==0:
# so you will have a list of numbers divisible by 3, even if it is a list of numbers
# divisible by 15, and you successfully replace, you only get a list full of "go"
# as there are no other numbers inserted under if statement
g.insert(len(g),i)
# raise AttributeError here because integer input doesn't have replace function,
# even it works, you only replace 15 not 30 or 45 etc. and the word will be "boo"
i.replace("15","boo")
# your print function is in the for-loop, so if there are 6 numbers divisible by 15,
# the list will be printed 6 times, is that what you want?
print(g)
Please also aware in range(a,b), b is exclusive, for example, range(0,100) have number from 0 to 99 not include 100.
May be you want something like this?
def b_function(low, high):
g = []
# high+1 to include the num_2
for i in range(low,high+1):
# directly append "go" to the list when the number is divisible by 15
# so no need to replace
if i % 15 == 0:
g.append("go")
# regular print out for numbers divisible by 3 or 7
elif i % 3 == 0 or i % 7 ==0:
g.append(i)
# only print the list once after the for-loop
print(g)
if __name__ == "__main__":
num_1 = int(input("Please input the lower limit:\n"))
num_2 = int(input("Please input the upper limit:\n"))
c = b_function(num_1,num_2)
The output will be:
[3, 6, 7, 9, 12, 14, 'go', 18, 21, 24, 27, 28, 'go']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.