How to avoid the semantic error in Python? [duplicate] - python

This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 3 years ago.
My homework is about Fermat's Last Theorem:
1) Write a function named check_fermat that takes four parameters—a, b, c and n—and checks to see if Fermat’s theorem holds.
2) Write a function that prompts the user to input values for a, b, c and n, converts them to
integers, and uses check_fermat to check whether they violate Fermat’s theorem.
Here is my code as follows. It works.
However, there is always a "None" following the correct answer, such as "Correct! None".
It would be appreciated if you could help me with the problem. Thank you so much.
def check_fermat(a,b,c,n):
if n > 2:
print("“Holy smokes, Fermat was wrong!")
if n == 2 and a**n + b**n == c**n:
print("Correct!")
else:
print("No, that doesn’t work")
def check_number():
a = int(input("Choose a number for a: "))
b = int(input("Choose a number for b: "))
c = int(input("Choose a number for c: "))
n = int(input("Choose a number for n: "))
print(check_fermat(a,b,c,n))
check_number()

print(check_fermat(a,b,c,n))
This line is what prints None, this is because the return value of check_fermat is None.
The solution is either:
only print in check_fermat, remove print from print(check_fermat(a,b,c,n))
OR, return a string (or some other sensible return value) from check_fermat, and leave print(check_fermat(a,b,c,n)) as it is.

Related

What is the quick meaning of the terms print and return in Python? [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed last month.
I'm learning some new things, and I cannot figure out the whole return process from reading my texts and looking online. I believe I need it explained to me once for me to wrap my head around it.
The code here works as intended; I would like the user to input a number, then if less than 0, print 0, if greater than or equal to zero print the number.
def positiveNumber():
num = int(input("Please enter a number: "))
if num <= 0:
print("0")
else:
print(num)
positiveNumber()
What isn't working is where I just want the function to return the values, then only give me the answer when I call the function.
def positiveNumber():
num = int(input("Please enter a number: "))
if num <= 0:
return 0
else:
return num
positiveNumber()
print(num)
My shell keeps telling me "name 'num' is not defined".
num is a local variable that only exists in positiveNumber().
You want:
print(positiveNumber())
The variable num is defined within your function. It thus only exists in the "scope" of the function.
When you're calling the function, you should try
a = positiveNumber()
print(a)
The returned value is something that you should assign to a variable in order to use.
Your function is sending back the value of num
So you can either
print(positiveNumber())
Or you can store it somewhere, and then use that.
This happens because the name num only exists inside the function, it's computed and the VALUE is being returned. So you can either directly print this VALUE or you could store it in some variable and then use it.
Here is the code that worked:
def positiveNumber():
num = int(input("Please enter a number: "))
if num <= 0:
return 0
else:
return num
print(positiveNumber())
Thank you so much!

If condition is getting skipped even if the condition is true [duplicate]

This question already has answers here:
Python input does not compare properly [closed]
(2 answers)
Closed 3 years ago.
I am using an If statement inside a for loop but the If statement is getting skipped even after the condition is met
x=raw_input().split(" ")
c=[]
for a in x:
b=1
if a<0:
print "Please enter a number greater than or equal to 0"
else:
if(a==1 or a==0 ):
print "1"
for i in range(1,int(a)+1):
b=b*i
c.append(str(b))
print ",".join(c)
the program is to find factorial, i am getting the result. If someone enters a negative number, it should not return a factorial but this does. I just want to know why is the if and else conditions getting skipped.
Comparing string with number returns False as result
'-2'< 0 ---> False --> if condition will be skipped
Convert the string to integer since factorial are only applied to integer
int('-2') < 0 ---> True --> if condition will be executed
x = raw_input().split(" ") returns strings data type in a list
so you can't use int for the entire list x,
only one string at the time
When invoking the if condition you are considering only one element in the list,
then convert from string to int before comparing to 0 --> int(a) < 0
The second point is related to indentation print (",".join(c))
should be included inside the else loop
Also
if(a==1 or a==0 ):
print "1"
is not needed as it has been take care in the for loop below
The code is as follow
x=raw_input().split(" ")
c=[]
for a in x:
b=1
if int(a) < 0:
print "Please enter a number greater than or equal to 0"
else:
for i in range(1,int(a)+1):
b=b*i
c.append(str(b))
print ",".join(c)
You might want to convert the input into int before doing int operations. Change this
x=raw_input().split(" ")
to
x=map(int, raw_input().split(" "))
x="-2 3 6 -3".split(" ")
c=[]
for a in x:
b=1
if int(a)<0:
print ("Please enter a number greater than or equal to 0" )
continue
else:
if(a==1 or a==0 ):
print ("1" )
for i in range(1,int(a)+1):
b=b*i
c.append(str(b))
print (",".join(c))
o/p:
Please enter a number greater than or equal to 0
Please enter a number greater than or equal to 0
6,720
Two changes, int(a) in if condition and if you wish not to calculate the factorial for negative numbers then add continue

How can I add 1 to the parameter [duplicate]

This question already has answers here:
Why can a function modify some arguments as perceived by the caller, but not others?
(13 answers)
Closed 6 years ago.
Im stuck with this very simple code were I'm trying to create a function that takes a parameter and adds 1 to the result and returns it but somehow this code gives me no results. (I've called the function to see if it works.)
Somebody please help me since I'm very new to python :)
def increment(num):
num += 1
a = int(input("Type a number "))
increment(a)`
I changed it to
def increment(num):
return num + 1
a = int(input("Type a number "))
increment(a)`
but still no results are showing after I enter a number, Does anybody know?
You need to return some value or it never will appear.
def increment(num):
return num + 1
a = int(input("Type a number "))
increment(a)
You need to ensure you return the num in the increment function and assign it to a.
Return:
def increment(num):
return num + 1
Assign:
a = increment(a)

Python - Run for loop 3 times [duplicate]

This question already has answers here:
Is it possible to implement a Python for range loop without an iterator variable?
(15 answers)
Closed 3 months ago.
So I have this assignment and I have a question about a part I don't know how to do, can you guys help me?
def main():
# Please see the comments
largest = 0
for index in range(3): # Enter the value(s) in the parenthesis to run the loop 3 times
number1 = int(input("Please enter the first number: "))
number2 = int(input("Please enter the second number: "))
number3 = int(input("Please enter the third number: "))
# insert call to function find_largest after this comment.
# find_largest will take in three parameters and will return the largest of the 3 numbers
result = find_largest(number1, number2, number3)
# insert the statement to print the three numbers entered and the largest number after this comment.
print("The numbers you entered were, \n", [number1, number2, number3])
print ("The largest of the numbers you entered is", result)
def find_largest(a, b, c):
# insert parameters in the parenthesis
# Write the code for this function here.
# find_largest will take in three parameters and will return the largest of the 3 numbers
# These three numbers are passed in as parameters from the main function
# Hint: if and elif - no loop needed here
if (a > b) and (a > c):
largest = a
elif (b > a) and (b > c):
largest = b
else:
largest = c
return largest
main() # this is the call to main() that will make the program run
So, my question is the part:
for index in range(3): # Enter the value(s) in the parenthesis to run the loop 3 times
I don't know what to add so the loop run 2 more times after it has found the largest number
The loop you have makes the first two iterations of the loop pointless, as each time you loop, you are reassigning new numbers to the three number variables. As a result, only the numbers entered in the last iteration of the loop are ever used for anything. I think this would make more sense:
numbers = []
for i in range(3):
input = int(input("Enter number: "))
numbers.append(input)
This will give you a list called numbers with 3 numbers in it entered by the user. Then you can do what you want with them. Having said that, you really don't need a for loop to do this. As Craig Burgler mentioned.
Alternatively(though this doesn't use range...):
number1 = 0
number2 = 0
number3 = 0
for i in (number1, number2, number3):
i = int(input("Enter number: "))
The code as written will ask for three numbers three times, overwriting the first and second set of numbers that the user enters. If the assignment is to get three numbers from the user and tell the user which is largest, then you do not need the for loop. The three input statements will do the trick.

Could anyone help figure out this recursion 2.7 python code? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
a factorial of a positive integer n, written as n!, is defined as:
n*(n-1)(n-2)…*1
if n is 0 n! is defined as 1
if n is negative, n! is undefined
An example is:
12! = 12*11*10*9*8*7*6*5*4*3*2*1
Write a program that
1. Inputs a positive integer from the user. If the integer is not positive, it displays an error message
2. Prompts the user to either have the factorial calculated by sequential programming (Option 1) or by recursion (Option 2)
Option 1:
using one of the top down iterative methods (e.g. while, for) find the factorial of any positive integer (including 0).
Option 2:
using recursion (see text section 6.3), find the factorial of any positive integer (including 0)
prints the factorial
Submit to this assignment a Word document (version 2010 or earlier) that contains the source code of your program and screen shots running it with both options and, for each option, with 0, 9, and -4
Hints:
you will need to define a function to perform this task using recursion
don’t try this with too large a number --- that may generate an error because of the memory it takes to perform
I seem to have figured out how to do the functions; however, I cannot seem to get them to work in the main() function.
When I run my program, the Menu() function executes; however, after I enter 1 or 2, my program returns
(Traceback (most recent call last): File "C:/Users/user/Documents/Prjct4", line 59, in <module> main() File "C:/Users/user/Documents/Prjct4", line 54, in main num = factorial() UnboundLocalError: local variable 'factorial' referenced before assignment)
The following is what I have so far:
def Menu():
print
print ("For Sequential Programming Calculator, Enter 1")
print ("For Recursion Calculator, Enter 2")
print
while True:
choice = input("Enter your choice here: ")
if (choice >= 1) and (choice <=2) and (int(choice)==choice):
return choice
else:
print ("Invalid Choice! Please enter 1 or 2")
def factorial():
num = 1
while n >= 1:
num = num * n
n = n - 1
return num
num = int(input("Enter a number: "))
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print "The factorial of",num,"is",factorial(num)
def recur_factorial():
if n == 1:
return n
else:
factorial= n*recur_factorial(n-1)
return factorial
num = int(input("Enter a number: "))
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print "The factorial of 0 is 1"
else:
print "The factorial of",num,"is",recur_factorial(num)
def main():
print
print("Factorial Calculator")
print
while True:
choice = Menu()
if choice == 1:
num = factorial()
elif choice == 2:
factorial = recur_factorial()
main()
If anyone could help me figure this out, I would greatly appreciate it! Thank you!
You have many bugs in your program.
However, the one that is first caused you a problem is that in your main code, you are assigning a value to a variable called factorial. But factorial is supposed to be a function - as per your earlier definition. Why are you assigning the result to a variable anyhow? You don't do anything with it. Maybe you mean print factorial(num).
The next problem you encountered is that you have uninitialised variables all over the place. I assume, from the traceback in your comment, that you changed the code in main to pass num into factorial - like factorial(num). But where do you expect num to get its value from?
You have some code (twice) that asks the user for a value for num, but it is in a place where it will never be executed - after the returns in your functions.
Perhaps you mean for this code to be in main before you call the factorial functions?

Categories

Resources