I'm making an arithmetic progression with python.
After the 10 first terms, I want a question with how many more terms the user wants to see. If it's 0, it will end the program. If it's not the program return the number of terms asked. And repeat until it's 0.
After the first loop, the program works, after that the program returns an empty.
i = int(input('Start of PA: '))
r = int(input('PA Reason: '))
t1 = i
cont = 1
terms = 1
n1 = 0
while cont <= 10:
t1 = t1 + r
cont += 1
print(f'{t1} > ', end='')
while terms != 0 :
terms = int(input('\nHow many terms? '))
if terms!= 0:
while cont <= (10 + terms):
t1 = t1 + r
cont += 1
print(f'{t1} > ', end='')
else:
print('END!')
resolution
Edit: sorry for my english.
while cont <= (10 + terms):
is only the correct condition on the second batch of results. The next batch should be less than 20 + terms, and so on.
Instead of adding to terms, you should just set cont back to 0 before each loop that prints the next batch of terms.
And rather than checking whether terms is zero twice, use while True: and break out of the loop when they enter 0.
while True:
terms = int(input('\nHow many terms? '))
if terms!= 0:
cont = 0
while cont <= terms:
t1 = t1 + r
cont += 1
print(f'{t1} > ', end='')
else:
print('END!')
break
Or instead of using while loops, use for and range()
while True:
terms = int(input('\nHow many terms? '))
if terms != 0:
for _ in range(terms)
t1 = t1 + r
print(f'{t1} > ', end='')
else:
print('END!')
break
Related
this code is supposed to take slope (m) and y-intercept (b) of two lines and checks if these two line hit each other or not.
the problem is my while loop is infinite although I have condition and break statement
print("enter the first m: ")
m = input() # m = slope
print("enter the first b: ")
b = input() # b = y-intercept
print("enter the second m: ")
m1 = input()
print("enter the second b: ")
b1 = input()
sub_m = int(m) - int(m1) #sub = subtract
sub_b = int(b) - int(b1)
if (sub_m == 0):
print("parallel")
x = float(-sub_b / sub_m)
r = round(x, 1)
i = 0.0
while i != r:
print(r, i)
if (i == r):
print("\nhit piont: ", i)
break
if (sub_m > 0 and sub_b > 0):
i -= 0.1
elif (sub_m < 0 and sub_b < 0):
i -= 0.1
else:
i += 0.1
Everyone here seems to be adamant on using some fancy tricks to make floating comparison works. Why not just multiply it all by 10 and get rid of floats altogether? :-)
I don't know if it is the fastest solution but it should have less corner cases.
i = 0
while True: # <- condition removed to allow the "hit point" if to work
print(r, i / 10)
if (i == r * 10):
print("\nhit piont: ", i / 10)
break
if (sub_m > 0 and sub_b > 0):
i -= 1
elif (sub_m < 0 and sub_b < 0):
i -= 1
else:
i += 1
Running this in my debugger showed that you're getting floating point representation errors. This means that although technically you should be getting numbers perfectly rounded to 1 decimal given that you're applying increments of 0.1, in reality this isn't the case:
As you can see, r = -2.0 and i = -2.00...4, thus at no point is r == i.
You can fix this by adding another round statement at the end:
print("enter the first m: ")
m = input() # m = slope
print("enter the first b: ")
b = input() # b = y-intercept
print("enter the second m: ")
m1 = input()
print("enter the second b: ")
b1 = input()
sub_m = int(m) - int(m1) #sub = subtract
sub_b = int(b) - int(b1)
if (sub_m == 0):
print("parallel")
x = float(-sub_b / sub_m)
r = round(x, 1)
i = 0.0
while i != r:
print(r, i)
if (sub_m > 0 and sub_b > 0):
i -= 0.1
elif (sub_m < 0 and sub_b < 0):
i -= 0.1
else:
i += 0.1
i = round(i, 1) # <- this
print(f"Hit pt: {i}")
HOWEVER: This is still error prone, and I recommend finding a way to avoid if i==r altogether in the code. If i is lower than r, exit the loop when it finally becomes bigger, and viceversa. Its best practice to avoid using the == condition when comparing floats, and to find a way to use <= and >=.
This is a question of granularity and floating-point precision. You're incrementing i in steps of 0.1 and then checking, at each step, if i == r. But what if r is not an integer multiple of 0.1? Then i will never exactly equal r, and your break will never be triggered.
By the way, your while condition and your if condition are mutually exclusive; if i and r are equal, you never enter the loop, and consequently won't have to/be able to break out of it. What you want is probably a genuine infinite loop with while True.
First of all, your while loop breaking condition contradicts your if() break condition. so it will never get to match the if condition. So it will never print hit point, because it will break the while loop when l==r, either it will never be l==r because of precision and loop infinite, so in both situations if condition never match. And comparing a floating value to break a loop is not ideal.
I have a double while loop, and it does not seem to be working because of some logic I'm doing incorrectly. I'm not sure what is wrong exactly, but I feel the code may be too complicated and somewhere, there is an error.
enter code here
import math
print("How many numbers am I estimating John?")
count = int(input("COUNT> "))
print("Input each number to estimate.")
better_guess = 0
initial_guess = 10
i = 0
j = 0
t = 1
list = []
for j in range(count):
num = float(input("NUMBER> "))
list.append(num)
j = j + 1
if j == count:
print("The square roots are as follows:")
while i <= len(list):
while t != 0 :
initial_guess = 10
better_guess = (initial_guess + (list[i])/initial_guess) / 2
if initial_guess == better_guess:
print(f"OUTPUT After {t} iterations, {list[i]}^0.5 = {better_guess}")
i = i + 1
break
initial_guess = better_guess
i = i + 1
There are some errors in your code, #x pie has pointed out some of them but not all. The most important is that you are need to initalize t for every number in the list, so you can get the iterations for the numbers separately. Also, t needs to be incremented in the while loop, not inside the if block.
You can also clean up the code considerably, for example the j variable is not being used, list comprehension can be used to shorten the code (pythonic way), and iterating over lists can be done with for num in list.
Putting this altogether produces this:
count = int(input('How many numbers am I estimating John? \nCOUNT> '))
print("Input each number to estimate.")
list = [float(input(f'NUMBER {i+1}> ')) for i in range(count)]
print("The square roots are as follows:")
for num in list:
initial_guess = 10
t = 0
while True:
better_guess = (initial_guess + num/initial_guess) / 2
t += 1
if initial_guess == better_guess:
print(f"OUTPUT After {t} iterations, {num}^0.5 = {better_guess}")
break
initial_guess = better_guess
Sample run:
How many numbers am I estimating John?
COUNT> 4
Input each number to estimate.
NUMBER 1> 1
NUMBER 2> 9
NUMBER 3> 16
NUMBER 4> 4
The square roots are as follows:
OUTPUT After 9 iterations, 1.0^0.5 = 1.0
OUTPUT After 7 iterations, 9.0^0.5 = 3.0
OUTPUT After 7 iterations, 16.0^0.5 = 4.0
OUTPUT After 8 iterations, 4.0^0.5 = 2.0
#viggnah is right, and I just ignored the num of iterations. But I think #viggnah 's num of iterations are 1 bigger than the actual num of iterations. E.g., if input is 4 and initial guess is 2, the iteration should be 0 rather than 1. Also I add except in case of illegal input.
I suppose the following code works as you expect.
import math
print("How many numbers am I estimating John?")
count = int(input("COUNT> "))
print("Input each number to estimate.")
better_guess = 0
initial_guess = 10
i = 0
j = 0
t = 1
list = []
while True:
try:
num = float(input("NUMBER> "))
list.append(num)
j = j + 1
if j == count:
print("The square roots are as follows:")
break
except:
print("Invalid input! Try again.")
while i < len(list):
initial_guess = 10
t = 0
while True:
better_guess = (initial_guess + (list[i])/initial_guess) / 2
if initial_guess == better_guess:
print(f"OUTPUT After {t} iterations, {list[i]}^0.5 = {better_guess}")
break
t = t + 1
initial_guess = better_guess
i = i + 1
You need to understand:
We only need initialize guess once for each number. So do it in the first while loop;
tneeds to be updated when initial_guess==better_guess rather than i, I believe this is a clerical error;
initial_guessneeds to be updated in the second loop;
while i <= T:
T1, T2, R1, R2 = input().split()
T1 = int(T1)
T2 = int(T2)
R1 = int(R1)
R2 = int(R2)
while True:
if T1>10 or T1<1:
print('Enter the value of T1 again, within 1-10 ')
T1 = int(input())
elif T2>10 or T2<1:
print('Enter the value of T2 again, within 1-10 ')
elif R1>10 or R1<1:
print('Enter the value of R1 again, within 1-10 ')
elif R2>10 or R2<1:
print('Enter the value of R2 again, within 1-10 ')
if T1**2/R1**3 != T2**2/R2**3:
print('NO')
else:
print('YES')
i=i+1
The last 5 lines aren't reachable. I'm using nested while to check the inputs. If you can suggest me some other way, that'll be a great help too
while True: creates an infinite loop.
If you want input validation, you can do something like:
while not (1 <= T1 <= 10 and 1 <= T2 <= 10 and 1 <= R1 <= 10 and 1 <= R2 <= 10):
is there a way to keep the counter going without counting the negatives and only to stop when the input is zero?
count = 0
total = 0
n = input()
while n != '0':
count = count + 1
total = total + int(n) ** 2
n = input()
print(total)
Here is an example of execution result.
Input: -1 10 8 4 2 0
Output: 184
Since you want only number to enter the loop you can use isnumeric() built in function to check that.
You need if() : break here.
num = input()
...
while(isnumeric(num)):
...
if(num == "0"):
break;
The response you wait for is:
ignore negative number
count positive numbers
stop when input is 0
count = 0
total = 0
n = int(input())
while (n != 0):
count += 1
if (n > 0):
total = total + n**2
num = int(input())
print(total)
Your code was already OK except that you did not cast the number n into int and you did not test n to take away negative values.
Execution:
When you enter -1 10 8 4 2 0, it should show 184
You can parse your Input to an integer (number) and check if it's larger than zero:
count = 0
total = 0
num = int(input())
while number != 0:
if number < 0:
continue
count += 1
total = total + num**2
num = int(input())
print(total)
The difference between pass, continue, break and return are:
pass = ignore me an just go on, usefull when you create a function that has no purpose yet
continue = ignore everything else in the loop and start a new loop
break = break the loop
return = end of a function - a return statement can be used to give an output to a function but also as a way to break out of the function like the break statement does in loops.
I have a problem with loops and declaring variables. currently I am making a program about Collatz Conjecture, the program should check what is the biggest steps to reach one from certain amount of Collatz Sequence. here's my code :
start_num = int(input("insert a starting Number > "))
how_many = int(input("how many times you want to check? >"))
def even_or_odd(number):
if number % 2 == 0:
return 'isEven'
else:
return 'notEven'
def collatz(n):
z = n
counter = 0
while True:
if n != 1:
if even_or_odd(n) == 'isEven':
n = n/2
counter += 1
continue
if even_or_odd(n) == 'notEven':
n = (n*3)+1
counter += 1
continue
else:
print('number ' + str(z) + ' reached 1 with : ' + str(counter) + ' steps')
return counter
break
def check_biggest_steps(steps_before, steps_after):
if steps_before > steps_after:
return steps_before
if steps_after > steps_before:
return steps_after
if steps_after == steps_before:
return steps_after
def compute_collatz(n_times, collatz_number):
for _ in range(n_times):
before = collatz(collatz_number)
collatz_number += 1
after = collatz(collatz_number)
collatz_number += 1
biggest_steps = check_biggest_steps(before, after)
print('Biggest Steps is :' + str(biggest_steps))
compute_collatz(how_many, start_num)
this biggest_steps variable always return the last 2 steps. I know what causing this problem is that biggest_step variable located inside the loop but I can't get it working anywhere don't know what to do. Thanks
Don't read my code until you have tried it yourself.
Try to make a list that appends every change to a list, then to get the number of moves at the end, just get the length of the list.
.
def collatz(x):
while x != 1:
if x % 2 > 0:
x =((3 * x) + 1)
list_.append(x)
else:
x = (x / 2)
list_.append(x)
return list_
print('Please enter a number: ', end='')
while True:
try:
x = int(input())
list_ = [x]
break
except ValueError:
print('Invaid selection, try again: ', end='')
l = collatz(x)
print('\nList:', l, sep=' ')
print('Number of steps required:', len(l) - 1)
you didn't save your biggest_steps and compared always the last 2 only.
I would suggest following change.
def compute_collatz(n_times, collatz_number):
biggest_steps = 0
for _ in range(n_times):
steps = collatz(collatz_number)
if steps > biggest_steps:
biggest_steps = steps
collatz_number += 1
print('Biggest Steps is :' + str(biggest_steps))