Please review my code - python

Hi all I'm new to programming, and trying to understand while loop in Python.
I want to print the following
print 2
print 4
print 6
print 8
print 10
print "Goodbye!"
Here's what I wrote
x = 0
sum = x
while (sum != 10):
x = x + 2
print x
sum = x + 2
Print ('Good bye!')
Can any one please let me know where am I going wrong..

The most direct fix:
x = 0
sum = x
while (sum <= 10):
x = x + 2
print x
sum = x + 2
print ('Good bye!') # <-- lower case, unindented
A shorter solution:
for x in range(2, 12, 2): # start at 2, increment by 2, up to but not including 12
print x
print 'Good bye!'

Related

Is there a way I can compare the same variable and choose the higher one and print it?

The value of y is changing every time the while loops continues, I tried the watchpoints modules but I need a way to find out the highest y has ever been and print it, I'll print the code that I'm trying to get to work.
import random
from watchpoints import watch
def alg(I):
print(I)
x = 1
while i > 1:
if (i % 2) == 0:
i = int(i / 2)
x = x + 1
else:
i = int(3 * i + 1)
x = x + 1
print(I)
y = 1
if i in range(1, 9):
y = 1
if i in range(10, 99):
y = 2
if i in range(100, 999):
y = 3
if i in range(1000, 9999):
y = 4
watch(a)#I want to know when y reachest the highest
print(y, "is the max number of caracters")#then print it
print("numero passaggi = ", str(x))
print("1: choice")
print("2: random")
type = int(input(" 1 or 2: "))
if type == 1:
i = input("Enter a number: ")
alg(int(I))
elif type == 2:
i = random.randint(1, 100) # 10^9
alg(I)
else:
print("Enter 1 or 2")
I want to know when y reaches the highest and print it below.
There are many ways to do this, but since you seem interested in "watching" the values of y as they change, one good option might be to make your alg function a generator that yields the values of y. The caller can then do whatever it wants with those values, including taking the max of them.
Note that instead of doing this kind of thing to figure out how many digits a number has:
if i in range(1, 9):
y = 1
if i in range(10, 99):
y = 2
if i in range(100, 999):
y = 3
if i in range(1000, 9999):
y = 4
you can just do:
y = len(str(i))
i.e. turn it into a string and then count the characters.
def alg(i: int):
x = 1
while i > 1:
if i % 2 == 0:
i = i // 2
x += 1
else:
i = 3 * i + 1
x = x + 1
print(f"i: {i}")
yield len(str(i))
print(f"numero passaggi = {x}")
print(f"Max number of digits: {max(alg(50))}")
i: 25
i: 76
i: 38
i: 19
i: 58
i: 29
i: 88
i: 44
i: 22
i: 11
i: 34
i: 17
i: 52
i: 26
i: 13
i: 40
i: 20
i: 10
i: 5
i: 16
i: 8
i: 4
i: 2
i: 1
numero passaggi = 25
Max number of digits: 2
The simplest method would be to create another variable to store the highest value that y has achieved and run a check each loop to see if the new y value is larger than the previous max.
Here is an example:
def exampleFunc():
i = 0
y = yMax = 0
while i < 20:
y = random.randint(1, 100)
if y > yMax:
yMax = y
i += 1
print(yMax)
The easiest way to approach something like this is to transform your function into one that returns all intermediate values, and then aggregate those (in this case, using the builtin max()).
from math import log10
def collatz_seq(n):
yield n
while n > 1:
if n % 2:
n = 3 * n + 1
else:
n //= 2
yield n
def print_stats(n):
seq = collatz_seq(n)
idx, val = max(enumerate(seq), key=lambda x: x[1])
digits = int(log10(val)) + 1
print(f"{digits} is the max number digits")
print(f"{idx} is the iteration number")
Here I use enumerate() to give me the index of each value, and I use math.log10() to obtain the number of digits in the number (minus one).

Factorization: What went wrong with d? [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 2 years ago.
Consider:
Enter image description here
Input: 20
17
999997
Output: 2^2 * 5
17
757 * 1321
My code:
a = int(input())
# Find the factors first
for i in range(2, a+1):
s = 0
b = a
d = 0
# See if it is a prime number
if a%i == 0:
for x in range(1, i+1):
if a%x == 0:
d = d + x
if (d-1)/i == 1:
d = 0
print(i)
else:
s = 0
b = a
d = 0
continue
d = 0
# I will see how many prime numbers
while(b>0):
if (b/i)%1 == 0:
s = s + 1
b = b/i
else:
b = 0
if b == 1:
b = 0
print(s)
I will find the factors first, and then see if it is a prime number. If so, I will see how many prime numbers it is
if i input 12, it outputs 2 2
Enter link description here
I believe you need the output of the following.
import math
a = int(input())
while (a % 2 == 0):
print(2)
a = int(a/2)
while (a % 3 == 0):
print(3)
a = int(a/3)
for i in range(5, math.ceil(math.sqrt(a)), 6):
while (a % i == 0):
print(i)
a = int(a / i)
while (a % (i + 2) == 0):
print(i + 2)
a = int(a / (i + 2))
if (a > 3):
print(a)
This will give you the prime factors for a given number. As I can understand, it is what you are looking for.
a = int(input("Enter a number:"))
for i in range(2, a + 1):
if a % i != 0:
continue
# SETTING THE DEFAULT VALUES AT THE BEGINNING OF EVERY ITERATION OF THE LOOP
s = 0
b = a
d = 0
for x in range(1, i + 1):
if b % x == 0:
d = d + x
if (d - 1) / i == 1:
d = 0
print(i)
else:
# s = 0 # NO LONGER NEEDED, AS WE RESET THEM AT THE BEGINNING OF THE LOOP
# b = a
# d = 0
continue
while b > 0:
if (b / i) % 1 == 0:
s = s + 1
b = b / i
else:
b = 0
if b == 1:
b = 0
print(s)
a /= i**s # THIS LINE IS IMPORTANT
You were close. You forgot to set the default values at the beginning of every iteration of the loop, so they sometimes didn't have the right values ; and you should set a to a different value by dividing it by the factor you found (i**s, so i to the power of s).
As has been mentioned, your code also follows an odd coding style. I suggest you stop putting newlines between each statement, and start separating operators with spaces (example: range(3+5) is bad, range(3 + 5) is more readable)
You are using too many loops here and that's why you are getting too much confused. Here is the code which serve the same purpose (if I understand your problem correctly)
a = int(input("Enter a number: "))
i = 2
factors = []
while i <= a:
if (a%i) == 0:
factors.append(i)
a = a/i
else:
i = i + 1
print(factors)
here I am returning a list, if you want you can change the type accordingly.
Here are the inputs/outputs:
Enter a number: 17
[17]
Enter a number: 100
[2, 2, 5, 5]
Enter a number: 12
[2, 2, 3]

How can you sum these outputs in Python?

I made this code about a number and it's power. It will ask a number and it's power and show the output like a horizontal list.. Like
Number = 2
Power = 3.... then output will be like=
1
2
4
Number and power can be +/-.
But I want to sum those numbers like Sum = 7 after it shows
1
2
4
I have no idea how to do it after the output. I am new to programming maybe that's why can't figure out this problem.
Here is the code in Python :
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
while i < B:
print(A**i)
i = i + 1
while i >= B:
print(A**i)
i = i - 1
You could simplify this with numpy as follows
import numpy as np
A =float(input("Number:"))
B =int(input("Power:"))
print("Result of Powers:")
power = np.arange(B)
power_result = A ** power
sum_result = np.sum(power_result)
print(power_result)
print(sum_result)
I made B into an int, since I guess it makes sense. Have a look into the numpy documentation to see, what individual functions do.
You can create another variable to store the sum
and to print values on the same line use end=" " argument in the print function
a = float(input("Number:"))
b = int(input("Power:"))
sum = 0.0
i = 0
while b < 0:
ans = a**i
i = i - 1
print(ans, end=" ")
sum = sum + ans
b += 1
while b >= 0:
ans = a**i
i = i + 1
print(ans, end=" ")
sum = sum + ans
b -= 1
print("\nSum = " + str(sum))
I'm not sure what you want to achieve with the second loop. This works:
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
n_sum = 0
while i < B:
n_sum += A**i
print(A**i)
i = i + 1
while i >= B:
n_sum += A**i
print(A**i)
i = i - 1
print(n_sum)

How to get back to start of loop from else

x=0
y=0
while 1==1:
while y!=5:
y=y+1
print(str(x) + str(y))
else:
x=x+1
#NOW GO TO WHILE 1==1 AND DO THAT AGAIN
This code should print 01; 02; 03; 04; 05 and then it should print 11; 12; 13; 14; 15. But in reality it does only the first five prints because I don't know how to get to the start again after else:.
EDIT: I am so sorry, i tried to make the code easier to understand and i made few mistakes instead, that werent really a problem.
Here's a working code with a similar structure than yours :
x = 0
y = 0
while x != 2:
while y != 5:
y = y + 1
print(str(x) + str(y))
else:
y = 0
x = x + 1
But please don't do that. Instead :
for x in range(2):
for y in range(5):
print '%d%d' % (x,y+1)
I would say a better approach is to do a nested for loop.
from itertools import count
for x in count():
[print('{}{}'.format(x, y)) for y in range(1, 6)]
and it's Pythonic (hope that wasn't your homework).
Just remove else: and use formatted print to avoid printing the sum.
A better version of your code is:
x = 0
while 1 == 1:
y = 1
while y <= 5:
print '%d%d' % (x,y)
y = y+1
x = x+1
First of all your code outputs:
1
2
3
4
5
and then stops. What you are asking for is this:
01
02
03
04
05
11
12
13
[...]
To get this output you need an infinite loop which continuously increments x to do this start off with this piece of code:
x = -1
while True:
x += 1
You then need a loop which will increment y from 1 to 5 and print the string concatenation of x and y:
for y in range(5):
print(str(x) + str(y+1))
Nest the for loop in the while loop and voila!
x = -1
while True:
x += 1
for y in range(5):
print(str(x) + str(y+1))

While Loop Print List formatting

I wanted to create a list of factors from any given number only using the formula below. I am not allowed to use list therefore, I have imitate using strings as follows:
for example and lets say we choose num=12:
def factors(num):
i=1
while i <= num :
if num % i == 0:
print i
i = i + 1
this code prints:
1
2
3
4
6
12
Without using lists, for loops, int, function and can only use strings,
how do i format the loop outputs to make it look like this?:
[1, 2, 3, 4 ,6 ,12]
I tried doing this first:
num = 12
i = 1
while i <= num :
if num % i == 0:
a=str("[")+str(i)+", "+str("]")
print a
i = i + 1
This prints:
[1, ]
[2, ]
[3, ]
[4, ]
[6, ]
[12, ]
Can anyone help or suggest where I can put that print state or how do i modify it? Thanks!
def factors(num):
i=1
result="["
while i <= num :
if num % i == 0:
result=result+str(i)+","
i+=i
result=result[:-1]+"]"
print result
factors(12)
Output > [1,2,4]
you can use use a print statement that ends with a comma to not insert a new line when a second print statement is used then you just need to make sure the first time in prints "[" and the last time it prints "]"
for example
print "hello ",
print "world"
would return >>>hello world
the code would look something like this
def factors(num):
i=1
while i <= num :
if i == 1:
if num % i == 0:
print "[",
else:
print "[",
if i == num:
print "%s]"%(i)
elif num % i == 0:
if i == num:
print i,"]"
else:
print "%s,"%(i),
i = i + 1
You can concatenate each str(i) to string a by +=,
def factors(num):
i = 1
a = "["
while i < num :
if num % i == 0:
a+=str(i)+", "
i = i + 1
print(a + str(num) + str("]"))
factors(12)
Output:
[1, 2, 3, 4, 6, 12]
def factors(num):
i = 1
factors = []
while i <= num:
if num % i == 0:
factors.append(i)
i += 1
print factors
factors(12)
This adds all the factors to a table called factors, and then when all the factors are added, the table factors is printed out.

Categories