i am learning classes in python and when i was reading the documentation i found this example that i didn't understand :
class MyClass:
"""A simple example class"""
def __init__(self):
self.data = []
i = 12345
def f(self):
return 'hello world'
then if we assign :
x = MyClass()
x.counter = 1
now if we implement while loop :
while x.counter < 10:
x.counter = x.counter * 2
so the value of x.counter will be :
16
while for example if we have a variable y :
y = 1
while y < 1 :
y = y *2
then if we look for the value of y we find it
1
so i don't know how is the value of counter became 16 .
thanks
this doesn't really have anything to do with classes in particular, but here is what is happening...
x == 1 # x is less than 10, so it is doubled
x == 2 # x is less than 10, so it is doubled
x == 4 # x is less than 10, so it is doubled
x == 8 # x is less than 10, so it is doubled
x == 16 # now x is greater than 10, so it is not doubled again
y = 1
while y < 1 :
y = y *2
Always give same input, if you want same output.
You see that you are checking y < 1 which would fail on first run. Make it y < 10, as you are having in your x.counter case.
y = 1
while y < 10:
y = y *2
Related
In the below code, the loops don't seem to be working.
powers = []
x = 0
y = 0
z = 1
for x in powers:
powers.append([])
for y in powers[x]:
powers[x].append(z ** y)
z = z + 1
if z < 1001:
continue
else:
break
x = x + 1
y = y + 1
z = 1
print(powers)
However, when I run this in the terminal, it simply returns an empty list for powers. It doesn't show an error message.
Please help.
your code is badly formatted, so please consider formatting, anyway some of your errors are code-comments.
powers = []
x = 0
y = 0
z = 1
for x in powers: #here you're overriding former declaration of x, also powers is empty so for doesn't have a single run
powers.append([]) ##code is not indented so this istruction execute only once
for y in powers[x]: ##powers[x] is an empty list
powers[x].append(z ** y)
z = z + 1
if z < 1001:
continue
else:
break
z = 1 ## this is outside the cycle
x = x + 1
y = y + 1
print(powers)
I'm just wondering what the most "pythonic" way to increment a varible x all the way from 0 to 100, then when x reaches 100, deincrement back to 0 then back again to 100 in a loop over and over...
Something like this:
x = 0
while True:
if x < 100:
x += 1
elif x == 100:
x -= 1
NB: Above code is broken, hence my question. :)
What is the simplest way to do this - not necessarily the shortest code, not looking for a one liner, just a really nice bit of code.
I find one-liners simple... so what about this:
Python 2:
from itertools import *
ups_and_downs = cycle(chain(xrange(100), xrange(100, 0, -1)))
Python 3:
from itertools import *
ups_and_downs = cycle(chain(range(100), range(100, 0, -1)))
(edited to remove the one-off error)
First of all your code does not work: it will count to 100, and then swap between 99 and 100. So: 1,2,3,..,99,100,99,100,99,...
Actually the most Pythonic way is probably not to increment/decrement at all, but use two ranges:
while True:
for x in range(101):
pass
#do something with x
for x in range(99,0,-1):
pass
#do something with x
Or construct an infinite generator with itertools:
generator = itertools.cycle(itertools.chain(range(101),range(99,0,-1)))
and then you can use it as:
for x in generator:
pass
#do something with x
Fr instance (I here use 2 because it makes the answer more compact):
for x in itertools.cycle(itertools.chain(range(3),range(1,0,-1))):
print(x)
will produce:
0
1
2
1
0
1
2
1
0
the loop will be repeated infinitely.
A way to fix your code however would be to add a direction, but this is probably not very Pythonic:
x = 0
dr = True
while True:
if dr:
x += 1
if x >= 100:
dr = False
else:
x -= 1
if x <= 0:
dr = True
#do something with x
How about trying this?
x = 0
inc = 1
while True:
# do your job here
if x == 0:
inc = 1
elif x == 100:
inc = -1
x += inc
There's nothing wrong with using two loops!
while True:
for x in range(100):
do_something(x)
for x in range(98, 0, -1):
do_something(x)
Or you could use a variable to keep track of which direction you're going:
delta = 1
x = 0
while True:
do_something(x)
x += delta
if x < 1 or x > 99:
delta = -delta
Well, your current solution won't exactly work - you'll deincrement back to 99, then cycle between 99 and 100.
The simplest might be to add a direction flag, for example:
x = 0
isIncreasing = True
while True:
if isIncreasing = True:
x += 1
if x == 100:
isIncreasing = False
else:
x -= 1
if x == 0:
isIncreasing = True
I'm there's a more "one line" way to do this with itertools (see above posts), but this would be the most "direct" solution in your current case. Of course, what you're really looking for is a generator.
well since no one else is doing it, why not some generator fun!
def lazy_forever_and_ever(hi, lo, start=0, step=1):
x = start
vals = {hi: lo, lo: hi}
target=lo
while True:
if x == target:
target = vals[target]
if x >= target:
yield x
x -= step
elif x <= target:
yield x
x += step
if __name__ == '__main__':
_4eva = lazy_forever_and_ever(0, 10, 0, 1)
print([next(_4eva) for _ in range(20)])
# output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
(Python 3.x)
z=[]
x=0
while 1==1:
x=x+1
y=1
z.append(x)
while y==1:
a = 0
b = 0
if z(a)==x:
print(x)
y = 2
elif x%z(a)!= 0:
a = a+1
elif b == 2:
y = 2
else:
b = b+1
So, I made a code to find all the prime numbers until python crashes. However, it relies on z(a) for it to work. The idea is that as "a" changes, it moves on in the list.
"z(a)" is where the error lies, so does anyone know a way to fix this?
z is a list. You can approach values inside it by indexes using the z[a] operator (and not z(a) which assumes a function call with a as parameter).
I've taken the liberty of using boolean variables, += operators and unpacking values:
z = []
x = 0
while True:
x += 1
y = True
z.append(x)
while y:
a, b = 0, 0
if z[a] == x:
print(x)
y = False
elif x % z[a]: a += 1
elif b == 2: y = False
else: b += 1
I believe that's what you want to achieve (infinitely incrementing prime generator):
def prime (n): return not any([n % i == 0 for i in range(2, n)])
x = 0
while True:
if prime(x): print(x)
x += 1
To simplify my scenario, I am redefining my question here.
I want to add numbers from 1 to 5 in loop. X should be 1,2,3,4,5. and start with Y as 0. Y = X + Y should give the sum of 1 through 5.
Requirement: I want to start y as 0 and want y to hold latest add_sum value.
Expected output:
1st iteration: y = 1 (x = 1, y = 0)
2st iteration: y = 3 (x = 2, y = 1)
3st iteration: y = 6 (x = 3, y = 3)
...
...
so on
I am new to python coding, Can anyone help me for this?
Use reduce
reduce(lambda x, y: x + y, range(6))
As mentioned in the comments, fixing your syntax and running your code seems to work just fine.
def read_num():
for num in range (1,5):
x = num
add_sum(x)
def add_sum(x):
global y
y = x + y
print ("y =", y)
y = 0
read_num()
If you want x to be 1 thru 5 inclusive, you have to use range(1,6) instead
y = 0 # Assign value 0 to variable 'y'
for x in xrange(1, 6): # Cycle from 1 to 5 and assign it to variable x using iterator as we need just 1 value at a time
print '(x=%s, y=%s)' % (x, y) # Display value of 'x' & 'y' variables to user for debug & learning purpose
y += x # Adding x to the y.
print 'y=%s' % y # Display result of sum accumulated in variable 'y'
Edit: added comments to the code as requested in comments.
I am trying to write the simplest code possible that will continuously print out Perfect Squares. My code so far reads this
x = 1
y = 1
while True:
final = x * y
print final
x = x + 1
y = y + 1
When I run it, I get a syntax error. The red bit is on the "final" in "print final"
Apologies if it is a really basic error, but I'm stumped.
Thanks for taking the time to read this
I assume you're using Python 3. print is now a function in Python 3.
Do print(final) instead of print final.
Also, it seems like your x and y values are holding the same thing. Why not discard one of them and use just one?
x = 1
while True:
final = x * x
print(final)
x = x + 1
Or better yet, use the builtin exponentiation operator **.
x = 1
while True:
final = x **2
print(final)
x += 1
Also, your code seems to be going into an infinite loop. You may need a condition to break it.
For example, if you want to break when x reaches 10, just add a condition in the while loop, like follows:
x = 1
while True:
final = x **2
print(final)
x += 1
if x == 10:
break
OR Specify a condition in the whilestatement, like follows:
x = 1
while x < 10:
final = x **2
print(final)
x += 1
OR Use a for loop.
for i in range(10):
print(i**2)
In Python 3, print is no longer a statement but a function, so you must enclose what you want to print in parentheses:
print(final)
Here's a link about the function.
You also have an IndentationError, y = y + 1 should be given a space.
And you can simplify that to y += 1 (which is the same thing, in regards to integers)
You can also add a condition to the while-loop:
x = 0
while x < 5:
print x ** 2
x += 1
Prints:
0
1
4
9
16
I would reccomend using Python 3 if you're not already. Also, as x and y are the same value at all times you only need one of them. So instead of reading:
x = 1
y = 1
while True:
final = x * y
print final
x = x + 1
y = y + 1
You should write:
x = 1
while True:
final = x * x
print(final)
x = x + 1
Hope this helped!
Jake.