Python simple loop - python

I am trying to make a simple loop where it prints the output numbers 0-9 on separate lines. What am I doing wrong? I have looked at the examples on here and they don't really help me. If you could explain where I went wrong that would be very helpful.
def singleline(item):
number = 0
while number < 10:
print(number)
number = number + 1

You've defined a function but you haven't called it. Just add
singleline(1)
to the end of the script.

Try using a for loop with range.
for num in range(10):
print(num)
This is more concise than using a while loop.
Also, if you are using a while loop, I would recommend using number+=1. It is the same as number=number+1, but just looks cleaner.

Firstly remember to call the function at the end of your otherwise you have just executed it singleline(). Also you haven't used the item you put into the parameters.
A better way to write this using a while loop would be.
def singleline():
num = 0
while num < 10:
print(num)
num += num
The += just means add one to of the variable on the left to the variable on the right. For example
a = 1
b = 2
a += b
a would not equal 3 because it adds b to it's original value.
However if you wanted something more efficient you could use this:
for num in range(10):
print(num)
for loops work in the same way as a while loop (take a condition and do content until stopped) but does it for the amount of times set. So in simple terms all this code means is print num plus 1.

Woah, your code is way too complicated -
for x in range (0, 10):
print x
Should work perfectly (python), Good Luck!

Related

Is loop "for" prior to "if" statement in Python?

I'm new to a programming language and wanted to start with Python as its the recommendation of most people (as far as i see).
So, im practising on some functions to improve my understanding on loops, and basic statements etc. Though i'm not very good at it yet, i do believe that i'll improve sooner or later.
Here is an example where i'm stuck at:
def L():
List = []
TauS = []
a = 12
for i in range(1,a+1):
if a % i == 0:
List.append(i)
if a % len(List) == 0:
TauS.append(a)
print(List)
print(TauS)
L()
This is the function i want to have and the output is:
[1, 2, 3, 4, 6, 12]
[12]
As i expected.However, the problem is that i want "a" to be a variable instead of a constant.Something like:
def L():
List = []
TauS = []
for a in range(2,20):
for i in range(1,a+1):
if a % i == 0:
List.append(i)
if a % len(List) == 0:
TauS.append(a)
print(List)
print(TauS)
L()
Fails because it seems like for loop is working before the 2nd if statement (if a % len(list)) == 0: TauS.append(a)).I have also tried a "while" loop instead of a "for" loop as:
a = 2
while a <= 20:
for i in range(1,a+1):...(The rest is the same)
It would be a better idea if your help focus on the basic ideas instead of just giving the right function.
Thanks a lot from now!
Regards.
Python uses indention levels to tell whether code is in within a function, loop or condition, the general thing being that if there is a : then all the code indented underneath it is within that statement.
The problem with your code is that the second if statement is on the same indention level as the for loop rather than being on the indention level below the for loop. This means that rather than running in the for loop it runs after it.
So to fix your code all you need to do is select the if statement and press crtl + ] which is pythons keyboard shortcut for indent code section.
edit:
I think what you're asking for is to get all the factors of numbers from 2 to 19 and then print numbers where the number of factors is a factor of that number.
def L():
List = []
TauS = []
for a in range(2,20):
l=[] #this is the list for each individual number
#if i is a factor of a add it to l
for i in range(1,a+1):
if a % i == 0:
l.append(i)
#if length of l is a factor of a add a to TauS
if a % len(l) == 0:
TauS.append(a)
List.append(l)
print(List)
print(TauS)
L()
It fails because of variable scope.
Python uses indention to represent code block. So, here for loop and 2nd if condition has same indention which means they belong to same code block and can access variables defined in the same or the outer code block. "List" & "Taus" in this case.
However, Variable "a" is localize to outer for loop and can be access in the same or inner for loop and cant be access from outside. Similarly variable "i" is specific to inner for loop and cant be access outside of the loops block, not even from outer for loop.
Hope it helps...

deleting sets from a set while iterating in python

I'm trying to implement something similar to Sieve of Eratosthenes. I want to remove all non prime numbers in a given range from the set, and sum up all the prime number to the given number.
number_set = set(list(range(1, given_number)))
sum_number = 0
for num in number_set:
if isPrime(num):
sum_number += num
prime_set = set(list(range(0, big_number, num)))
number_set -= prime_set
print(sum_number)
Obviously I got the error -
Set changed size during iteration
I'm new to python so the syntax is unfamiliar. As far as I understood from other threads, I can use dictionary and use the for loop on number_set.keys() (right?), but I wanted to ask, is it possible to correct this for loop?
You must stop itering over the modified iterator.
My approach is to restart the iteration after the modification, try to modify the set such as every already processed value is not re-processed, and maybe call it a day.
The exception you are having is just a limitation about sets not liking being iterated over and modified at the same time.
number_set = set(list(range(1, given_number)))
sum_number = 0
done = False
while not done:
for num in number_set:
if isPrime(num):
sum_number += num
prime_set = set(list(range(0, big_number, num)))
number_set -= prime_set
break
done = True
print(sum_number)
Disclaimer: Script might need adjustments on you part, I'm just illustrating the logic

Lost: Defining a function which takes a tuple of numbers and returns the sum of only the even numbers in the tuple

Title pretty much says it all. This is the code I wrote that I've been tinkering around with.
def sum_evens(tup):
for num in tup:
if num % 2 ==0:
total = num+num
print(total)
I'm pretty lost here, any ideas on what I can do?
Thank you in advance!
you need to start total at 0 and add to it when you find matching numbers
def sum_evens(tup):
total = 0
for num in tup:
if num % 2 ==0:
total = total+num
return total
finally you need to return the total to whatever called it so it can be used
there are lots of better ways to do this ... but I just edited your function to work
print sum_evens([1,2,3,4,5,6,7]) # 2+4+6 = 12
You need to learn about list comprehensions. Basically, they are backwards for loops such that you can define a new list by iterating over an old list. You can also add a conditional clause to pick and choose.
In this scenario, we loop through an existing tuple and look for the individual members with a remainder of zero when divided by two. We then construct a list with these members and find a sum.
print sum([x for x in my_tuple if x % 2 == 0])

How to change for-loop iterator variable in the loop in Python?

I want to know if is it possible to change the value of the iterator in its for-loop?
For example I want to write a program to calculate prime factor of a number in the below way :
def primeFactors(number):
for i in range(2,number+1):
if (number%i==0)
print(i,end=',')
number=number/i
i=i-1 #to check that factor again!
My question : Is it possible to change the last two line in a way that when I change i and number in the if block, their value change in the for loop!
Update: Defining the iterator as a global variable, could help me? Why?
Short answer (like Daniel Roseman's): No
Long answer: No, but this does what you want:
def redo_range(start, end):
while start < end:
start += 1
redo = (yield start)
if redo:
start -= 2
redone_5 = False
r = redo_range(2, 10)
for i in r:
print(i)
if i == 5 and not redone_5:
r.send(True)
redone_5 = True
Output:
3
4
5
5
6
7
8
9
10
As you can see, 5 gets repeated. It used a generator function which allows the last value of the index variable to be repeated. There are simpler methods (while loops, list of values to check, etc.) but this one matches you code the closest.
No.
Python's for loop is like other languages' foreach loops. Your i variable is not a counter, it is the value of each element in a list, in this case the list of numbers between 2 and number+1. Even if you changed the value, that would not change what was the next element in that list.
The standard way of dealing with this is to completely exhaust the divisions by i in the body of the for loop itself:
def primeFactors(number):
for i in range(2,number+1):
while number % i == 0:
print(i, end=',')
number /= i
It's slightly more efficient to do the division and remainder in one step:
def primeFactors(number):
for i in range(2, number+1):
while True:
q, r = divmod(number, i)
if r != 0:
break
print(i, end=',')
number = q
The only way to change the next value yielded is to somehow tell the iterable what the next value to yield should be. With a lot of standard iterables, this isn't possible. however, you can do it with a specially coded generator:
def crazy_iter(iterable):
iterable = iter(iterable)
for item in iterable:
sent = yield item
if sent is not None:
yield None # Return value of `iterable.send(...)`
yield sent
num = 10
iterable = crazy_iter(range(2, 11))
for i in iterable:
if not num%i:
print i
num /= i
if i > 2:
iterable.send(i-1)
I would definitely not argue that this is easier to read than the equivalent while loop, but it does demonstrate sending stuff to a generator which may gain your team points at your next local programming trivia night.
It is not possible the way you are doing it. The for loop variable can be changed inside each loop iteration, like this:
for a in range (1, 6):
print a
a = a + 1
print a
print
The resulting output is:
1
2
2
3
3
4
4
5
5
6
It does get modified inside each for loop iteration.
The reason for the behavior displayed by Python's for loop is that, at the beginning of each iteration, the for loop variable is assinged the next unused value from the specified iterator. Therefore, whatever changes you make to the for loop variable get effectively destroyed at the beginning of each iteration.
To achieve what I think you may be needing, you should probably use a while loop, providing your own counter variable, your own increment code and any special case modifications for it you may need inside your loop. Example:
a = 1
while a <= 5:
print a
if a == 3:
a = a + 1
a = a + 1
print a
print
The resulting output is:
1
2
2
3
3
5
5
6
Yes, we can only if we dont change the reference of the object that we are using. If we can edit the number by accessing the reference of number variable, then what you asked is possible.
A simple example:
a=[1,2,3]
a=a+[4]==>here, a new object is created which plots to different address.
a+=[4]==>here , the same object is getting updated which give us the desired result.
number=10
list1=list(range(2,number+1))
# list1
for i in list1:
print(list1,i)
if (number%i==0):
print(i,end=',')
number=number//i #we can simply replace it with number//=i to edit the number without changing the reference or without creating a new object.
try:
[list1.pop() for i in range(10,0,-1) if(i>number)]
#here pop() method is working on the same object which list created by number refers. so, we can able to change the iterable in the forloop.
except:
continue
i=i-1 #to check that factor again!

Function running way too slow

I am practicing Python with Project Euler, question 1, but the function I wrote to solve it is taking way too long.
I figure it's because the way I coded it not the actual method itself.
When I run this function with 10 or 15 iterations it spits out an answer instantly, but as soon as I jump it up to even 20, it doesn't show me anything for even minutes.
This is obviously a big problem if I need to go to 1000 iterations.
def pe1(n):
counter = 1
total = 0
while counter < n:
if counter%3==0:
total=total+counter
if counter%5==0:
if counter%3==0:
continue
total=total+counter
if counter % 25 == 0:
print (total)
counter=counter+1
return (total)
Because as soon as counter hits 15, your loop goes into an infinite continue - it's always going to hit the second if statement's case.
You need to move your counter = counter + 1 line before the continue, or better yet, use something like for counter in range(1,n).
Consider the case if counter equals 15 and look at what happens where counter%5==0 and counter%3==0, which will first occur at that time.
Consider also what will not happen for that value of counter, specifically, the line counter=counter+1 won't be executed.
To avoid traps like this one, consider using
if ...
elif ...
elif ...
else ...
You can use table-driven. Like this.
counter_map = {3:fun1, 5:func2, 25:fun3} # key is remainder.Of course,fun can be replaced with lambda.

Categories