Why does the following code not follow the specified order? - python

I want it to say welcome, ask for the user input (a,b,c), validate the user input and if the validation returns that the input is reasonable then carry out the quadratic formula on a,b,c. I suspect the problem is in the while-loop. The program just welcomes, asks for input then says welcome again and so on.
from math import sqrt
def quadratic_formula(a,b,c):
a=float(a) #The quadratic formula
b=float(b)
c=float(c)
x1_numerator = -1*b + sqrt((b**2)-4*(a*c))
x2_numerator = -1*b - sqrt((b**2)-4*(a*c))
denominator = 2*a
x1_solution = x1_numerator/denominator
x2_solution = x2_numerator/denominator
print("x= "+str(x1_solution)+" , x= "+str(x2_solution))
def number_check(a,b,c,check): #carries out a check
a=float(a)
b=float(b)
c=float(c)
if (b**2)-4*a*c < 0:
print("The values you have entered result in a complex solution. Please check your input.")
check == False
else:
check == True
check = False
while check == False:
print("Welcome to the Quadratic Equation Calculator!")
a = input("Please enter the x^2 coefficient: ")
b = input("Please enter the x coefficient: ")
c = input("Please enter the constant: ")
number_check(a,b,c,check)
else:
quadratic_formula(a,b,c)

You are correct in your suspicion. You have a problem in your while loop. does not work the way your code assumes.
Instead you need to write something like:
def number_check(a,b,c): #carries out a check
a=float(a)
b=float(b)
c=float(c)
if (b**2)-4*a*c < 0:
print("The values you have entered result in a complex solution. Please check your input.")
check = False
else:
check = True
return check
check = False
print("Welcome to the Quadratic Equation Calculator!")
while check == False:
a = input("Please enter the x^2 coefficient: ")
b = input("Please enter the x coefficient: ")
c = input("Please enter the constant: ")
check = number_check(a,b,c)
quadratic_formula(a,b,c)
Note, that in addition to changing the while loop you also need to update number_check as input parameters are not updated in calling scope. Instead the function has to explicitly return the updated value.

Try using return, not attempting to modify a global variable.
There's a way to use global variables (see global statement), but it's not necessary for this code.
The check variable itself isn't really necessary, though
def number_check(a,b,c):
a=float(a)
b=float(b)
c=float(c)
return (b**2)-4*a*c >= 0 # return the check
while True:
print("Welcome to the Quadratic Equation Calculator!")
a = input("Please enter the x^2 coefficient: ")
b = input("Please enter the x coefficient: ")
c = input("Please enter the constant: ")
if not number_check(a,b,c):
print("The values you have entered result in a complex solution. Please check your input.")
else:
break # getting out of the loop

There are two problems with the way you're using the check variable in the number_check function.
First, you're not assigning new values to it, because you're using == (which tests equality) rather than =.
But also, since it's a parameter variable, it's local to the function. So assigning it inside the function does not modify the global variable that you test in the while loop. Rather than use a global variable, you can simply test the result of number_check directly, and use break when you want to end the loop.
If you make this change, you need to move the call to quadratic_formula out of the else: clause, because that's only executed when the while condition fails, not when we end the loop with break.
def number_check(a,b,c): #carries out a check
a=float(a)
b=float(b)
c=float(c)
if (b**2)-4*a*c < 0:
print("The values you have entered result in a complex solution. Please check your input.")
return False
else:
return True
while True:
print("Welcome to the Quadratic Equation Calculator!")
a = input("Please enter the x^2 coefficient: ")
b = input("Please enter the x coefficient: ")
c = input("Please enter the constant: ")
if number_check(a,b,c):
break
quadratic_formula(a,b,c)

Related

Using a While loop in python when asking for something specific

Question is to
Prompt the user for a number from 1 to 100. Using a while loop, if they entered an invalid number, tell them the number entered is invalid and then prompt them again for a number from 1 to 100. If they enter a valid number - thank them for their input.
x = int(input("please enter a number 1-100, inclusive: "))
y = x<0 or x>100
while y is True:
print("invalid.")
int(input("please enter a number 1-100, inclusive: ")
else:
print("thank you for your input")
my code is incorrect. Help me fix it please?
Aren't you missing a parenthesis in the statement before else: ? Looks like it says else: is invalid due to that.
Besides the syntax error (missing ) before the line of else, your code also have logical error, you need to set the y = False when user give proper input to get out from the while loop, like :
x = int(input("please enter a number 1-100, inclusive: "))
y = x<0 or x>100
while y is True:
print("invalid.")
value = int(input("please enter a number 1-100, inclusive: "))
if value >= 0 and value <= 100:
y = False
else:
print("thank you for your input")
Simplification and correction of your code
while True:
x = int(input("please enter a number 1-100, inclusive: "))
if 1 <= x <= 100: # range check
print("thank you for your input")
break # terminates while loop
else:
print("invalid.") # print then continue in while loop
#Krish says a really good answer about how you are missing a second bracket during the line that you prompt inside the while loop. I assume you receive a SyntaxError about it (probably listing the immediately following line--unfortunately common in software).
Solution
However, you have a much more fundamental issue with your code: you never update y so you have an infinite loop that will always think that the input is invalid.
x = int(input("please enter a number 1-100, inclusive: "))
y = x<0 or x>100
while y: # it is unnecessary to check a boolean against a condition
print("invalid.")
x = int(input("please enter a number 1-100, inclusive: ")) # missing bracket
y = x<0 or x>100 # necessary to end the loop
else:
print("thank you for your input")
Improvement
Another option is to use break to exit the loop on the spot. It can make for cleaner code with less duplication because now everything is inside the loop.
while True: # infinite loop...but not because of break
x = int(input("please enter a number 1-100, inclusive: "))
if x<0 or x>100:
print("invalid.")
else:
print("thank you for your input")
break
Advanced
For completeness I will also include a couple more advanced features. You can skip this part since you are starting out, but it may be interesting to come back to once you have become more familiar with the language.
Lambda
Helps make the code cleaner.
user_input = lambda: int(input("please enter a number 1-100, inclusive: "))
condition = lambda x: x<0 or x>100
while condition(user_input()):
print("invalid.")
else:
print("thank you for your input")
Cmd
This one is really advanced and overkill for what you are trying to accomplish. Still, it is good to know about for a later, more advanced problem that it would be appropriate for. Docs found here.
from cmd import Cmd
class ValidNumberPrompter(Cmd):
"""
This is a class for a CLI to prompt users for a valid number.
"""
prompt = "please enter a number 1-100, inclusive: "
def parseline(self, line): # normally would override precmd but this is modifying the way the line is parsed for commands later
command, args, line = super().parseline(line) # superclass behaviour
return (command, args, int(line))
def default(self, line): # don't care about commands
if line<0 or line>100:
print("invalid.")
return False
else:
print("thank you for your input")
return True
"""
Only start if module is being run at the cmdline.
If it is being imported, let the caller decide
what to do and when to run it.
"""
if __name__ = '__main__':
ValidNumberPrompter().cmdloop()

How to recall a function until invalid input?

I'm new to python, and I was wondering how I could recall a function until the user gives invalid input.
Here's a sample of code:
start = input("For sum of squares, type 'squares'. For sum of cubes, type 'cubes'. "
"\nIf you would like to raise a number to something other than 'squares' or 'cubes', type 'power'. "
"\nIf you would like to exit, type 'exit':")
def main_function(start):
while start.lower() != "exit":
if start.lower() in "squares":
initial = input("What is the initial constant for the sum of the squares: ")
terms = input("Number of terms: ")
if start.lower() in "cubes":
initial = input("What is the initial constant for the the sum of the cubes: ")
terms = input("Number of terms: ")
if start.lower() in "power":
initial = input("What is the initial constant for the the sum: ")
terms = input("Number of terms: ")
else:
print("Program halted normally.")
quit()
main_function(start)
What I am trying to get it to do is to reprompt 'start' if the user inputs a proper input, and then get it to run through the function again. I have tried putting 'start' within the function above and below the 'else' statement, but it never accepts the new input.
I would do it like this, define the start input in a method and call it inside the loop, when it's equal to "exit" than break the loop.
Also use elif, this way if the first condition statement is True than you won't check the others, unless that what you want of course.
def get_start_input():
return input("For sum of squares, type 'squares'. For sum of cubes, type 'cubes'. "
"\nIf you would like to raise a number to something other than 'squares' or 'cubes', type 'power'. "
"\nIf you would like to exit, type 'exit':")
def main_function():
while True:
start = get_start_input()
if start.lower() == "squares":
initial = input("What is the initial constant for the sum of the squares: ")
terms = input("Number of terms: ")
elif start.lower() == "cubes":
initial = input("What is the initial constant for the the sum of the cubes: ")
terms = input("Number of terms: ")
elif start.lower() == "power":
initial = input("What is the initial constant for the the sum: ")
terms = input("Number of terms: ")
elif start.lower() == "exit":
print("Program halted normally.")
break
main_function()
EDIT:
As dawg wrote in comment, it's preferred to use here == instead of in because you can have several matches and ambiguous meanings.

Python Calculator Programming Errors

def add(x,y):
y = int( input("Enter First number "))
x = int( input("Enter Second number "))
answer = x + y
print (answer)
def subtract(x,y):
answer = x - y
print (answer)
y = int ( input("Enter First number "))
x = int ( input("Enter Second number "))
operation = input("Subtract or Add ")
if operation == "add":
add(x,y)
else:
subtract(x,y)
I keep getting an error saying variables x and y aren't being used. Please help. I have been stuck on this for a while now.
You have problems with your scope. You can't call x or y before calling the function as those variables are declared inside the function. Do it once at a time. First you ask what function. Then once inside the function you ask for x and y
def add():
x = int( input("Enter First number "))
y = int( input("Enter Second number "))
answer = x + y
print (answer)
def subtract():
x = int ( input("Enter First number "))
y = int ( input("Enter Second number "))
answer = x - y
print (answer)
operation = input("subtract or add ")
if operation == "add":
add()
else:
subtract()
welcome to Stack Overflow and welcome to Python.
As you might know, in Python indents are really important, as they define which code belongs into which block.
Looking at your request, I must assume that this is a reflection of your code. So I think if you go with the following indentation, it might do what you want:
def add(x,y):
answer = x + y
return answer # Please notice how i use RETURN to return a value from the function call
def subtract(x,y):
answer = x - y
return answer
y = int ( input("Enter First number "))
x = int ( input("Enter Second number "))
operation = input("Subtract or Add ")
result = None
if operation == "add":
result = add(x,y) # Please notice how I store what the function returns!
else:
result = subtract(x,y)
if (result != None):
print result
else:
print "There is no result!"
Please read the comments and ask if you have any more questions.
Maybe you want to consider an elaborate introduction to Python
Your code has many problems and it is really confusing.
as ppperry commented, indentation .When writing python, you should use exact 4 space as indentation.
you did not realize the difference between input and raw_input.
If you are using python2, and your input is not a number, input while try to eval your input. written in python doc.
If you are using python3, you do not need to worry about this because in python3 there is no more raw_input, and input equals old raw_input. This was asked here
follow enpenax's answer. you should first define x and y before you call them.

Boolean return value?

def main():
num = int(input('Please enter an odd number: '))
if False:
print('That was not a odd number, please try again.')
else:
print('Congrats, you know your numbers!')
def number():
if (num / 2) == 0:
return True,num
else:
return False,num
main()
I am trying to make it so that if the number entered is odd, it congratulates the user. If not then it should tell them to try again. I am trying to return the Boolean value to main and then when I try to use the code in the main function to prompt the user, it doesn't work.
Your functions are very odd and I'm not talking about numbers that aren't divisible by 2. Try this:
num = int(input('Please enter an odd number: '))
if num % 2 == 0:
print('Better luck next time??') # no really, you should go back to school (;
else:
print('Genius!!!')
Try this:
num_entry = int(input('Please enter an odd number: '))
def number():
return num_entry % 2 == 0
def main():
if number() == True:
print('Sorry, please try again.')
else:
print('Nice! You know your numbers!')
number()
main()
This should work!
Your code does look odd like Malik Brahimi mentioned. This may be because you are trying to write your python code like Java, which requires a main method. There is no such requirement in python.
If you would like to have your check for the "odd-ness" of the number wrapped in a defined function that you can call elsewhere, you should try writing it like this.
def odd_check(number):
if number % 2 == 0:
#This is the check the check formula, which calculates the remainder of dividing number by 2
print('That was not an odd number. Please try again.')
else:
print('Congrats, you know your numbers!')
num = int(input('Please enter an odd number: ')) #where variable is stored.
odd_check(num) #This is where you are calling the previously defined function. You are feeding it the variable that you stored.
If you would like a piece of code that will continue to ask your user to enter a number until they get it right, try something like this:
while True: #This ensures that the code runs until the user picks an odd number
number = int(input('Please enter an odd number: ')) #where variable is stored.
if number % 2 == 0: #the check formula, which calculates the remainder of dividing num by 2
print('That was not an odd number. Please try again.')
else:
print('Congrats, you know your numbers!')
break #This stops the "while" loop when the "else" condition is met.

Integrating a for loop into an if statement

This is kind of a double-barreled question, but it's got me puzzled. I currently have the following code:
from __future__ import division
import math
function = int(raw_input("Type function no.: "))
if function == 1:
a = float(raw_input ("Enter average speed: "))
b = float(raw_input ("Enter length of path: "))
answer= float(b)/a
print "Answer=", float(answer),
elif function == 2:
mass_kg = int(input("What is your mass in kilograms?" ))
mass_stone = mass_kg * 2.2 / 14
print "You weigh", mass_stone, "stone."
else: print "Please enter a function number."
Now, I'd like to have some kind of loop (I'm guessing it's a for loop, but I'm not entirely sure) so that after a function has been completed, it'll return to the top, so the user can enter a new function number and do a different equation. How would I do this? I've been trying to think of ways for the past half hour, but nothing's come up.
Try to ignore any messiness in the code... It needs some cleaning up.
It's better to use a while-loop to control the repetition, rather than a for-loop. This way the users aren't limited to a fixed number of repeats, they can continue as long as they want. In order to quit, users enter a value <= 0.
from __future__ import division
import math
function = int(raw_input("Type function no.: "))
while function > 0:
if function == 1:
a = float(raw_input ("Enter average speed: "))
b = float(raw_input ("Enter length of path: "))
answer = b/a
print "Answer=", float(answer),
elif function == 2:
mass_kg = int(input("What is your mass in kilograms?" ))
mass_stone = mass_kg * 2.2 / 14
print "You weigh", mass_stone, "stone."
print 'Enter a value <= 0 for function number to quit.'
function = int(raw_input("Type function no.: "))
You can tweak this (e.g., the termination condition) as needed. For instance you could specify that 0 be the only termination value etc.
An alternative is a loop that runs "forever", and break if a specific function number is provided (in this example 0). Here's a skeleton/sketch of this approach:
function = int(raw_input("Type function no.: "))
while True:
if function == 1:
...
elif function == 2:
...
elif function == 0:
break # terminate the loop.
print 'Enter 0 for function number to quit.'
function = int(raw_input("Type function no.: "))
Note: A for-loop is most appropriate if you are iterating a known/fixed number of times, for instance over a sequence (like a list), or if you want to limit the repeats in some way. In order to give your users more flexibility a while-loop is a better approach here.
You simply need to wrap your entire script inside a loop, for example:
from __future__ import division
import math
for _ in range(10):
function = int(raw_input("Type function no.: "))
if function == 1:
a = float(raw_input ("Enter average speed: "))
b = float(raw_input ("Enter length of path: "))
answer= float(b)/a
print "Answer=", float(answer),
elif function == 2:
mass_kg = int(input("What is your mass in kilograms?" ))
mass_stone = mass_kg * 2.2 / 14
print "You weigh", mass_stone, "stone."
else: print "Please enter a function number."
This will run your if statement 10 times in a row.
I'd try this:
while True:
function = ...
if function == 0:
break
elif ...

Categories

Resources