Skipping a value in a range within a for loop - python-3.x

So the course I'm in posted an exercise:
# Modify the code inside this loop to stop when i is exactly divisible by 11
for i in range(0, 100, 7):
print(i)
I added:
if i % 11 == 0:
break
However my code gets stuck on the first value as it is 0 thus ending the program.
What function would I use to skip over the first value and proceed with the rest of the range?
Any help would be greatly appreciated!

To "skip over" a certain value (here 0), you can use python's continue
for i in range(0, 100, 7):
print(i)
if i == 0:
continue
if i % 11 == 0:
break
This is like a break statement, but it returns you to the top of the loop instead of skipping to the end of it.

You could also do as below:
print(0)
for i in range(1, 100, 7):
print(i)
if i % 11 == 0:
break
Print the first value and start the loop from index 1.

Related

fibbonnacci. sequence UnboundLocalError

I've been working on this Fibbonacci sequence function. I am essentially returning a list of the Fibbonacci sequence by growing out a returned list respective to the number sequence that is generated by passing in a particular number. however I'm encountering an error within my for loop at the if statement within that for loop. it states UnboundLocalError: local variable 'new_list' referenced before assignment. Does anyone have a clue how to remedy this? Any help will be appreciated. thanks
def fib_n(num):
if num < 0:
print("You have entered incorrect output")
elif num == 0:
new_list = []
else:
for index in range(1,num):
if index == 1 or index == 2:
new_list.append(1)
continue
new_list.append(new_list[index - 1] + new_list[index - 2])
return new_list

How to 'Write a script that computes and prints all of the positive divisors of a user-inputted positive number from lowest to highest in Python?'

Write a script that computes and prints all of the positive divisors of a user-inputted positive number from lowest to highest.
It was with the help of Pythontutor that I was able to get this far. If someone can suggest a better way than what I've done that is appreciated as well.
print('Please enter a positive number:')
num = int(input())
if num < 0:
print('Please enter a positive number:')
else:
for i in range(1,num+1):
calc = i / 2
if calc==int(calc):
print(i)
else:
continue
I expected for this to be considered correct since factors are being returned, but I think the problem is, for example if I input '4', it only returns 2 and 4, not 1.
The below code will work. The below code runs infinitely, Hit Ctrl + c to quit from below code. Remove while True: to remove infinite loop.
while True:
value = int(input('Please enter a positive number: '))
if value < 0:
continue
for i in range(1, value + 1):
if value % i == 0:
print(i)
Output:
1
2
4

Lucas-Lehmer Mersenne numbers with Python

Writing a Python code that checks Mersenne numbers using Lucas-Lehmer test.
def lucas_lehmer(p):
my_list=[4]
value=2**p-1
lucas=4
for val in range(1, p - 1):
lucas=(lucas*lucas-2)%value
if lucas== 0:
my_list.apprend(lucas)
else:
break
print(my_list)
print(lucas)
The code shown above only show gives the result for the first iteration, regardless of the p value selected. I want to be able to display all the Lehmer test values within the given value of p, in this case 17.
If I understand your question correctly, I think the problem is not doing the append in the loop but only when p is a prime number. Your formatting is somewhat off, so I'm not 100% sure if I'm right. Additionally, you have a typo in append. I added some code to print the actual result of the primality test.
def lucas_lehmer(p):
my_list=[4]
value=2**p-1
lucas=4
for val in range(1, p - 1):
lucas = ((lucas*lucas)-2) % value
my_list.append(lucas)
if lucas == 0:
print("prime")
else:
print("composite")
print(my_list)
print(lucas)
Calling lucas_lehmer(7) leads to the following output:
prime
[4, 14, 67, 42, 111, 0]
0

How to keep the ID the same for a list when appending

Trying to obtain a list without changing the ID of the original list and the list can only contain spaces between each element.
I keep getting this error and I am unable to find a way to keep its ID the same whilst having only spaces in between each element whilst printing it out.
newlist=[array[x] for x in range(len(array)) if x !=0]
array=[]
array.append(newlist)
newlist=[]
print(' '.join(array))
TypeError: sequence item 0: expected str instance, list found
The error message is for the last line
while ans:
ans=input("\nSelect an option?\n")
if ans=="A":
if len(array) < 10:
A = list(input('\nInput string: \n'))
if len(A) == 1 and str(A):
array += A
if len(array) == 10:
print( "Invalid input\n")
elif ans=="P":
print(' '.join(array))
elif ans=="N":
newlist=[array[x] for x in range(len(array)) if x !=0]
array=[]
array.append(newlist)
newlist=[]
print(' '.join(array))
elif ans=="M":
print(id(array))
This is what half the code looks like.
What I intend is that the ID should always stay the same and when N is inputted the first element of the array is removed
No use of pop, del, remove, slicing and index is allowed
What about "clear" then? :) Python 3.3 and higher
elif ans=="N":
newlist=[array[x] for x in range(len(array)) if x !=0]
array.clear()
array.extend(newlist)
print(' '.join(array))

FizzBuzz with commas instead of newlines

def fizz_buzz(i):
if i % 15 == 0:
return ("FizzBuzz")
elif i % 5 == 0:
return ("Buzz")
elif i % 3 == 0:
return ("Fizz")
else:
return (i)
for i in range(1, 21):
print(fizz_buzz(i))
Where and how would do a new line command here with commas?
Trying to get an output like this: 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz,16,17,Fizz,19, Buzz
but sideways and with commas.
Pass end=',' to print()
def fizz_buzz(i):
if i % 15 == 0:
return ("FizzBuzz")
elif i % 5 == 0:
return ("Buzz")
elif i % 3 == 0:
return ("Fizz")
else:
return (i)
for i in range(1, 21):
print(fizz_buzz(i), end=',')
# prints
1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz,16,17,Fizz,19,Buzz,
If you do not want the trailing comma, end the range at 20 and follow with print(fizz_buzz(20))
Consider making a list & joining the elements with a comma. There are some great examples here.
For example:
def fizz_buzz(i):
# your code
my_list = []
for i in range(1,21):
my_list.append( str(fizz_buzz(i)) )
print ",".join(my_list)
There are more elegant ways of doing this -- using generators &c, as in the linked answer --, but this simple code will do what you want. Note that the join() method accepts string only, hence the str() in the list.append(); alternatively you could ensure that your fizz_buzz function returns strings regardless.

Resources