For my program I must enter a positive number, but if I enter a negative number I need the program to error with a message saying, "Please use a positive number and try again", then go back to the part where you input a number. It's stuck in a loop. Here's my code:
import math
# Receive the input number from the user
x = float(input("Enter a positive number: "))
#Initialize the tolerance and estimate
tolerance = 0.000001
estimate = 1.0
#Perform the successive approximations
while True:
estimate = (estimate + x / estimate) / 2
diference = abs(x - estimate ** 2)
if diference <= tolerance:
break
elif x < 0:
print("Please enter a positive number")
#Output the result
print("The program's estimate:", estimate)
print("Python's estimate: ", math.sqrt(x))
You can fix it by put your input() into while loop
import math
#Initialize the tolerance and estimate
tolerance = 0.000001
estimate = 1.0
while True:
# Receive the input number from the user
x = float(input("Enter a positive number: "))
estimate = (estimate + x / estimate) / 2
diference = abs(x - estimate ** 2)
if diference <= tolerance:
break
elif x < 0:
print("Please enter a positive number")
--snip--
The issue is that you need to re-request the user input inside of the while loop as others have already mentioned.
A more thorough version of this answer would also be to refactor the order of operations inside of the while loop. In the code you are running the math operations on x before you validate that it is greater than zero. If the math is known to fail without a positive integer you would have a bug in your code that could lead to an unhandled exception. Here is another version with switches the if statement so we check the input before doing anything else - which makes the program less likely to throw an exception based on the input.
import math
#Initialize the tolerance and estimate
tolerance = 0.000001
estimate = 1.0
#Perform the successive approximations
while True:
# Receive the input number from the user
x = float(input("Please enter a positive number:"))
if x <= tolerance:
print("Invalid input.")
continue
else:
estimate = (estimate + x / estimate) / 2
diference = abs(x - estimate ** 2)
break
#Output the result
print("The program's estimate:", estimate)
print("Python's estimate: ", math.sqrt(x))
elif x < 0:
print("Please enter a positive number")
# Receive the input number from the user
x = float(input("Enter a positive number: "))
add the 4th line in your code. it will work. you were not receiving the input again after the fail attempt.
Related
Question:
Write a program that implements Newton’s method to compute and display the square
root of a number entered by the user. The algorithm for Newton’s method follows:
Read x from the user
Initialize guess to x/2
While guess is not good enough do
Update guess to be the average of guess and x/guess
When this algorithm completes, guess contains an approximation of the square root. The quality of the approximation depends on how you define “good enough”. In the author’s solution, guess was considered good enough when the absolute value of the difference between guess ∗ guess and x was less than or equal to 10−12.
Solution:
x = int(input("Enter x: "))
guess = x/2
while guess != (abs(guess * guess - x <= 10 ** -12)):
guess = (guess + x/guess)/2
print(guess)
Note: if I add a break statement, it changes the value.
Ex: square root of 9 = 3 using the above solution.
but If I add a BREAK statement...
while guess != (abs(guess * guess - x <= 10 ** -12)):
guess = (guess + x/guess)/2
print(guess)
break
Enter x: 9
3.25
why does adding a break statement change the value of the guess variable? How do I terminate this loop without changing the value and simply print guess and exit loop?
endloop is not working and exit() seems to have the same effect. Any help will be greatly appreciated. Thank you !
if type(guess) != str:
break
I have also tried placing such a condition. same effect. prints incorrect value for guess.
This demonstrates the correct while condition:
x = int(input("Enter x: "))
guess = x/2
while abs(guess * guess - x) >= 10 ** -12:
guess = (guess + x/guess)/2
print(guess)
Output:
C:\tmp>python x.py
Enter x: 9
3.25
3.0096153846153846
3.000015360039322
3.0000000000393214
3.0
Here's a slightly different approach that uses an extra variable and thus a less complicated conditional expression. Also use a variable to determine the level of accuracy and also use that same variable to the presentation of the result.
x = float(input('X: '))
guess = x / 2
prev = x
DP = 4 # no. of decimal places accuracy
MARGIN = 10 ** -DP
while abs(guess - prev) > MARGIN:
prev = guess
guess = (guess + x / guess) / 2
print(f'{guess:.{DP}f}')
Example:
X: 17
4.1231
Write a program in Python that reads a sequence of integer inputs (data) from the user and then prints the following results:
the total of all the inputs
the smallest of the inputs
the largest of the inputs
the number of even inputs
the number of odd inputs
the average of all of the inputs
You do not know how many numbers the user will want to type in, so you must ask her each time if she has another number to add to the sequence.
So far this is my code but I want to know if there's a way without using the sys module
import sys
# declare a variable largest which has smallest integer value
# -sys.maxsize gives the smallest integer value,you can also use any smallest value
largest = -sys.maxsize
# declare a variable smallest, that is assigned with maximum integer value
smallest = sys.maxsize
# declare variables total to store the sum of all numbers
total = 0
# option variable is to store the user option Y or N
option = 'y'
# declare variables to count odd, even and totalCount
evenCount = 0
oddCount = 0
totalCount = 0
print("This program will calculate statistics for your integer data.")
# run the loop when the user enters y or Y
while option == 'y' or option == 'Y':
# take input of number
number = int(input("Please type a number: "))
# add the number to total
total = total + number
# increase totalCount
totalCount = totalCount + 1
# calculate smallest
if number < smallest:
smallest = number
# calculate largest
if number > largest:
largest = number
# calculate count of even and odd numbers
if number % 2 == 0:
evenCount = evenCount + 1
else:
oddCount = oddCount + 1
option = input("Do you have another number to enter? ")
# calculate average
average = total / totalCount
# print the output
print("\nThe total of your numbers is:", total)
print("The smallest of your numbers is:", smallest)
print("The largest nof yout numbers is:", largest)
print("The number of even numbers is:", evenCount)
print("The number of odd numbers is:", oddCount)
print("The average of your numbers is:", average)
The answer to "can it be done?" when it comes to programming is almost always "yes."
In this case, you can test if you're on the first loop iteration and set smallest and largest accordingly.
E.g.
option = 'y'
first_loop = True
while option.lower() == 'y':
x = int(input("Please type a number: "))
if first_loop:
smallest = x
first_loop = False
elif x < smallest:
smallest = x
option = input("Do you have another number to enter? ")
print(f"Smallest number entered is {smallest}")
You might also collect the input numbers into a list.
option = 'y'
inputs = []
while option.lower() == 'y':
x = int(input("Please type a number: "))
inputs.append(x)
option = input("Do you have another number to enter? ")
Now if you have all of the input numbers in inputs, then calculating a minimum and maximum is just min(inputs) and max(inputs).
Interesting approach, when I have problems like this I use float('inf') or float('-inf'). Can easily be worked into your approach.
I want to calculate the sum of the natural numbers from 1 up to an input number. I wrote this code:
number=int(input("enter a natural number"))
if number<0:
print("The number is not positive")
else:
n=0
for i in range (1,number+1):
n+=i
print(n)
But it prints multiple numbers instead. For example, if the user puts five, the program should print 15, but I get this:
1
3
6
10
15
How can I fix the code so that only 15 appears?
You have all the steps because your print statement is in your for loop.
Change it like this:
number = int(input("Enter a positive natural number: "))
if number < 0:
print("The number needs to be positive")
exit() # Stops the program
result = 0
for i in range(1, number + 1):
result += i
print(result) # We print after the calculations
There's also a mathematical alternative (see here):
number = int(input("Enter a positive natural number: "))
if number < 0:
print("The number needs to be positive")
exit() # Stops the program
print(number * (number + 1) / 2)
As I've pointed out and suggested earlier in comments, you could move the print statement out of for-loop to print the final sum.
Or you could try to use generator expression to get all number's total (sum), because we don't care the intermediate sums.
This simple sum of all up to the number in one shot.
number=int(input("enter a natural number"))
if number < 0:
print("The number is not positive")
# exit or try again <---------
else:
print(sum(range(1, number + 1))) # given 5 -> print 15
Something like this?
number = int(input("enter a natural number"))
if number < 0:
print("The number is not positive")
else:
n = 0
for i in range (1,number + 1):
n += i
print(n)
The answer to your question is that you are printing the n every time you change it. You are looking for the last answer when you run the code. This code should solve it.
number = int(input("enter a natural number"))
if number < 0:
print("The num < 0")
else:
n = 0
l = []
for i in range (0, number+1):
n+=i
l.append(n)
print(l[len(l)-1])
I'm trying to get the userinput for a,b,c using a function and it doesn't seems to work
import math
def equationroots():
try:
a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))
except ValueError:
print("Not a number!")
my = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(my))
quadratic = (-b + sqrt_val)/(2 * a)
return quadratic
print("The equation root of the numbers is" quadratic)
equationroots()
You have not used the proper intents, This is what your code supposed to be.
import math
def equationroots():
try:
a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))
except ValueError:
print("Not a number!")
my = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(my))
quadratic = (-b + sqrt_val)/(2 * a)
return quadratic
quadratic = equationroots()
print("The equation root of the numbers is", quadratic)
Indentation is very important in Python to separate block statements. It appears your indentation is off, leading to some lines not being executed when you intend.
For example, the variables my, sqrt_val, and quadratic are only calculated if the except label is reached. This means they are only attempted to be calculated if there is an input error, which wouldn't work anyways.
It's possible you also pasted in your code and the formatting was adjusted, and that isn't the issue. If that is the case, please edit the question to reflect the formatting and indentation you are using.
You need to fix your indentations from the except portion. Indentations are very important in python
fix this portion:
except ValueError:
print("Not a number!")
my = (b*b)-(4*a*c)
sqrt_val = math.sqrt(abs(my))
quadratic = ((-b)+sqrt_val)/(2*a)
return quadratic
then call your function first then use that to print your statement. Like,
quadratic = equationroots()
print(f"The equation root of the numbers is {quadratic}")
I need help with a square root calculator.
The directions are as follows:
"You need to implement the Babylonian Method for computing square roots. Based on that core functionality, you are to write an interactive program that:
Prompts the user to enter an integer value above zero.
Checks to ensure that the value is indeed above zero. If not, the program displays an error message and asks for the input again.
Computes the square root of the value using the Babylonian Method outlined above.
Displays the square root to the user formatted to show exactly 3 decimal places (no more than 3, and no less than 3)."
I can't use the sqrt function. I'm getting really close but can't quite get to the right loop. Here's what I have so far
# Ask user if they would like to calculate a square root for a single number or range.
single = input("Enter 'single' or 'range' to solve for a single square root or a range of values, respectively: ")
# Set error message to let the user know 'range' calculation are not currently available.
if single == 'single' or 'Single':
# Ask user to enter a positive integer.
number = int(input("Enter a positive integer value: "))
# Set error message asking for valid number if user enters something other than a positive integer.
while number < 0:
print("Please enter a valid number.")
else:
# Choose epsilon
epsilon = .0001
# Choose estimate for the square root of x
estimate = 4
# Evaluate the estimate
while number - estimate > epsilon:
# Calculate the square root using the Babylonian Method.
estimate = (number + 1.0) / 2.0
second_estimate = (estimate + number / estimate) / 2.0
# Print the users selected value and its square root.
print("Value", " ", "Square Root")
print(" ", number, " ", format(second_estimate, '.3f'))
else:
# Tell user 'range' calculation are not currently available.
print("That function is not currently available.")
The condition for the while loop is wrong. number is 9 and estimate goes to 3. So you have to check number - estimate*estimate (take the absolute value because estimate converges to 3 from above for a starting value of 4). You dont need the first estimate according to Babylonian method on wikipedia.
Also estimate is always 5 in your code. (estimate = (number + 1.0) / 2.0 where number is always 9)
number = 9
epsilon = .0001
estimate = 4
while abs(number - estimate*estimate) > epsilon:
estimate = (estimate + number/estimate) / 2.0
print("Value", " ", "Square Root")
print(" ", number, " ", format(estimate, '.4f'))
Result:
Value Square Root
9 3.1250
Value Square Root
9 3.0025
Value Square Root
9 3.0000