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.
Related
This question already has answers here:
Why is this printing 'None' in the output? [duplicate]
(2 answers)
Closed 1 year ago.
str = input("Please enter y to start the program: ")
while str == 'y':
def printNTimes(s, n):
for i in range(n):
print(s)
phrase = input("Enter a string: ")
number = int(input("Enter a positive number: "))
allTogether = printNTimes(phrase, number)
print(allTogether)
print()
str = input("Please enter y if you want to continue: ")
print("DONE")
Output:
Please enter y to start the program: y
Enter a string: Hi
Enter a positive number: 3
Hi
Hi
Hi
None
Please enter y if you want to continue:
You don't need print(allTogether), or the variable itself, because when you print it, you get an extra None (because the function returns None i.e, it does not return anything).
Also, put the function outside the while loop so that it is easier to read.
def printNTimes(s, n):
for i in range(n):
print(s)
str = input("Please enter y to start the program: ")
while str == 'y':
phrase = input("Enter a string: ")
number = int(input("Enter a positive number: "))
printNTimes(phrase, number)
print()
str = input("Please enter y if you want to continue: ")
print("DONE")
Just call the function. You could use return and then print the function, but this might be easier.
The problem is the function printNtime is actually being used as a subroutine, meaning it doesn't RETURN any values.
I am not sure what you want as a final output so here's two solution.
IF USED AS SUBROUTINE: just remove the print(allTogether)
IF USED AS A FUNCTION: you need to create a string variable in the function and return it.
def printNTimes(s, n):
mystring = ""
for i in range(n):
mystring = mystring + s + "\n"
return mystring
The issue you're seeing is because your routine, printNTimes(), returns a None value. You say:
allTogether = printNTimes(phrase, number)
print(allTogether)
allTogether is set to None because printNTimes does not return a value. When you call print(allTogether), that's what is printing the None.
It sounds like you intended your printNTimes() routine to assemble one big string of all the output and return it, which you would then print out via the print(allTogether) call. But your printNTimes() routine is calling the print() method and outputing the text then. So, you need to rewrite your printNTimes() method. Also, note that defining that function inside the loop is not necessary. Once is sufficient. So something like this should suffice:
def printNTimes(s, n):
s_out = ""
for i in range(n):
s_out += s + '\n'
return s_out
str_ = input("Please enter y to start the program: ")
while str_ == 'y':
phrase = input("Enter a string: ")
number = int(input("Enter a positive number: "))
allTogether = printNTimes(phrase, number)
print(allTogether)
print()
str_ = input("Please enter y if you want to continue: ")
print("DONE")
Also note that I renamed your str variable to str_. str is a Python type, a reserved word that should not be reused.
so I am doing my first project which is a triangle identifier through sides, I came across this issue where if someone wrote a letter the program would crash since you can't float the input when it's a string so I tried a few methods (try: except I tried:
if x == str and x != int and x != float:
print("please choose a viable unit ")
but it now displays that even when I have normal numbers like (4,6,6 )
I only did the x input to know if it works in the first place
my final code :
print("please input the sides of the triangle")
x = input("the first side = ")
y = input(" the second side = ")
z = input("the third side = ")
if str(x) == x and int(x) != x and float(x) != x:
print("please choose a viable unit ")
elif x == y == z:
print("the triangle is equilateral ")
elif x == y or y == z or x == z:
print("the triangle is isosceles")
elif x != y or x != z or y != z:
print("the triangle is scalene")
elif(x*x) + (y*y) == (z*z) or (z*z) + (y*y) == (x*x) or (z*z) + (x*x) == (y*y):
print("the triangle is also right")
This line:
if str(x) == x and int(x) != x and float(x) != x:
does not actually turn x into either an int or a float; it can also never be true, because it's not possible for x to be all of those types at once. x is always going to be a str because input always returns a str. The only thing this line can do is raise a ValueError (which will cause your script to exit since you haven't caught it) if x is a value that can't be converted into an int.
What you want to do is turn x, y, and z into floats as soon as you read them:
try:
x = float(input("the first side = "))
y = float(input(" the second side = "))
z = float(input("the third side = "))
except ValueError:
print("please choose a viable unit ")
exit()
After this point, if the script hasn't exited, x, y, and z are guaranteed to be float values, and you can perform math operations on them without encountering TypeErrors.
First: Do everyone a favor and change your title to something along the lines of "Help with Python Input and Ints"
Second:
When you use a python input, it reads that input as a string. So, in order to do any math with that string, it needs to NOT be a string, and instead considered a number.
That being said the inputs will have to be along the lines of
foo = float(input("bar"))
Edit: You also mentioned that you were having issues if the user inputs a string. You can use this answer for reference on how to implement a try except case for that instance
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)
I'm having an issue with the following code. It's currently in progress but a large problem that I'm running into is that my input of a function returns an error no matter what type of input I have tried. It either returns with an issue with the error type, or an issue of x not being defined if I enter a function such as x.
f = raw_input("Please enter function: y' = ")
x0 = float(raw_input("Please enter the initial x value: "))
y0 = float(raw_input("Please enter the initial y value: "))
xmax = float(raw_input("Please enter the value of x at which to approximate the solution: "))
h = float(raw_input("Please enter the step size: "))
showall = int(raw_input("Would you like to see all steps (1) or only the approximate solution (2)? "))
def f(x,y):
value = f
return (value)
def euler(x0,y0,h,xmax):
x=x0; y=y0; xd=[x0]; yd=[y0];
while x<xmax:
y = y + h*f(x,y)
yd.append(y)
x=x+h
xd.append(x)
return(xd,yd)
(xvals,yvals) = euler(x0,y0,h,xmax)
if showall == 1:
print ""
print "x_n y_n"
for uv in zip(xvals, yvals):
print uv[0],uv[1]
elif showall == 2:
print ""
print "x_n y_n"
print xvals, yvals
else:
print ""
print "There has been an error with your choice of what to see; showing all steps."
print ""
print "x_n y_n"
for uv in zip(xvals, yvals):
print uv[0],uv[1]
print " "
plotask = int(raw_input("Would you like to see a plot of the data? Yes (1); No (2) "))
if plotask == 1:
print "1"
elif plotask == 2:
pass
else:
print ""
print "Could not understand answer; showing plot."
Any help would be appreciated.
The error and trace is the following:
File "C:\Users\Daniel\Desktop\euler.py", line 25, in <module>
(xvals,yvals) = euler(x0,y0,h,xmax)
File "C:\Users\Daniel\Desktop\euler.py", line 19, in euler
y = y + h*f(x,y)
TypeError: unsupported operand type(s) for *: 'float' and 'function'
This function:
def f(x,y):
value = f
return (value)
Can be seen to return a function. In particular, it does nothing except return itself, f. (note that f is different from f() or f(x,y)
y = y + h*f(x,y)
evaluates to
y = y + h*f
which is an error, as f is a function and you cannot multiply a function by a number (as opposed to the RESULT of evaluating a function call - e.g. if f(x,y) returns a number, then your code will work)
The issue you're having is that your function f is using the same name as the formula string you're collecting in the first line of your code. However, just fixing the name won't do what you want, I don't think.
Your f function will need to evaluate the formula, in order to get a numeric result. I think you want this:
formula = raw_input("Please enter function: y' = ")
def f(x, y):
return eval(formula)
While this works, I do want to point out that using eval is generally not recommended practice, especially when the string you're evaluating comes from a user. That's because it can include arbitrary Python code, which will be run. eval('__import__(os).system("rm -Rf *")') could really ruin your day (don't run this code!).
I'm running the following code from the command line (python filename.py) and it wont terminate. I've tried the code outside of a procedure and have tried the procedure in an online interpreter, so I don't think it's the the algorithm. What am I doing wrong?
n = raw_input("Enter a number: ")
def print_multiplication_table(n):
x = 1
while x <= n:
y = 1
while y <= n:
z = x * y
print x, " * ", y, " = ", z
y += 1
x += 1
print_multiplication_table(n)
You should convert the number received from raw_input into an integer. Right now it's being compared as a string.
An easy (but probably bad) way to do this:
n = int(raw_input("Enter a number: "))
There is a problem with the raw_input command. I have a similar code myself (guess we're both following the Udacity course). I tried to add the raw_input line to my code, and it ended up in an infinite loop too.