Trouble with return between functions [duplicate] - python

This question already has answers here:
Short description of the scoping rules?
(9 answers)
Closed 1 year ago.
I am a beginner to python and coding in general and have not a clue why return in the code below doesn't move across functions. Shouldn't the value for n be stored for use in all functions? print(n) is in there only for my own sake to see if it works, and it is apparently not.
def main():
print("This program tests the Goldbach's conjecture")
get_input()
print(n)
def get_input():
n = 0
while n == 0:
try:
v = int(input("Please enter an even integer larger than 2: "))
if v <= 2:
print("Wrong input!")
continue
if v%2 == 1:
print("Wrong input!")
continue
if v%2 == 0:
n = v
except ValueError:
print("Bad input!")
continue
return n

You are not storing the value returned by get_input anywhere, you should keep it in a variable (or printing it directly), e.g -
def main():
print("This program tests the Goldbach's conjecture")
val = get_input()
print(val)
n is an internal variable that stored only within the scope of get_input.

Related

I used while loop, until the random number that python throws matched the input, why it doesn't work? [duplicate]

This question already has answers here:
Why does assigning to my global variables not work in Python?
(6 answers)
Closed 2 years ago.
I let the user input a 3-digit number, and let python throw a random 3-digit number, try to see when the random number can match the input. However, everytime I run it on cmd, it prints 'Python is too tired', which is a statement I set to prevent it from looping infinitely (I really did so, until I added this limitation of attempt times).
import random
my_num = int(input('Type your 3-digit int number: '))
if my_num >= 100 and my_num < 1000:
attempt = 0
my_lottery = []
my_lottery.append(int(num) for num in str(my_num))
def lottery_throw():
lottery = []
i=0
while i<3:
lottery.append(random.randint(1,9))
i+=1
return(lottery)
def check():
global boo
lottery_throw()
if lottery == my_lottery:
boo = 'true'
else:
boo = 'false'
while attempt < 100000:
check()
attempt += 1
if boo == 'true':
print('you win')
print(attempt)
break
elif attempt >= 100000:
print('python is too tired')
break
else:
print('You must enter a 3-digit number.')
Run it on cmd, everytime I run it, it returns 'Python is too tired'
But the number of possible combinations (9C3) is only 84. It's very unlikely that python really didn't throw a correct number. How can I fix this problem?
Errors
Do not use global variables unless you really need them. As you can see, writting to a global variable doesn't work our of the box
012 is a valid 3 digit number
If you append a list to another list you will get a nested list (list inside another list): [[1, 2, 3]]
Why create a list of each digit when you can create the number itself?
for loops should be used for a fixed number of iterations, while loops when a more complex condition is needed to return from the loop.
return should be used without parenthesis as they are redundant (it is not a function)
True and False are booleans, do not use "true" and "false" (strings) to represent them.
if condition return true else return false (in pseudocode) is the same as return condition
for loops also can have an else clause, which only is executed if no break was found.
Solution
import random
my_num = int(input("Type your 3-digit int number: "))
if 0 <= my_num < 1000:
for attempt in range(1, 100001):
if my_num == random.randint(0, 999):
print(f"You win in {attempt} attempts.")
break
else:
print("Python is too tired.")
else:
print("You must enter a 3-digit number.")
I have no idea what you did, but I wasn't able to fix it.
Here is my version incited:
num = input('Type your 3-digit int number: ')
for i in range(100000):
if (("00"+str(random.randint(0,999)))[-3:]) == num:
print("You win on attempt %i"%i)
did_win = True
break
else:print('python is too tired')

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

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.

i don't know what is wrong with my coding it keeps skip to else statement even i type in integers not float [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 years ago.
def factorial(n):
if isinstance(n,int):
if n == 1:
return 1;
elif n <= 0:
print("Factorial is for positive integer.")
else:
return n*factorial(n-1)
else:
print("It's only for integers")
factorial_number = input("give an integer that you want to factor: ")
print(factorial(factorial_number))
You can handle is as soon as you get the input, see below example:
if factorial_number.isdigit():
factorial_number = int(factorial_number)
else:
print("It's only for integers")
The built-in input() always return a str object. You need to cast it to int.
factorial_number = int(input("give an integer that you want to factor: "))
print(factorial(factorial_number))

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?

inconsistent string to int error and response

I've made a simple program where the users adds as many numbers as they would like then type 'exit' to stop it and print the total but sometimes it says the converting the string to int fails, and sometimes it does convert but then it has the wrong out put e.g I type 1 + 1 but it prints 1
def addition():
x = 0
y = 1
total = 0
while x < y:
total += int(input())
if input() == "exit":
x += 1
print(total)
addition()
I have tryed converting it to a float then to an int but still has inconsistency, I did start learning python today and am finding the syntax hard coming from c++ / c# / Java so please go easy on the errors
Maybe this is what you are looking for:
def addition():
total = 0
while True:
value = input()
if value == "exit":
break
else:
try:
total += int(value)
except:
print('Please enter in a valid integer')
print(total)
EDIT
There are two reasons why the code isn't working properly:
First, the reason why it is failing is because you are trying to cast the word "exit" as an integer.
Second, as user2357112 pointed out, there are two input calls. The second input call was unintentionally skipping every other number being entered in. All you needed to do was one input call and set the entered value into a variable.
You can break the while loop, without using x and y.
def addition():
total = 0
while True:
total += int(input())
if input() == "exit":
break
print(total)
addition()
These are a few ways you can improve your code:
Run the loop forever and break out of it only if the user enters "exit"
To know when the user entered "exit" check if the input has alphabets with isalpha()
Making the above changes:
def addition():
total = 0
while True:
user_input = input()
if user_input.strip().isalpha() and user_input.strip() == 'exit':
break
total += int(user_input)
print(total)
addition()
def safe_float(val):
''' always return a float '''
try:
return float(val)
except ValueError:
return 0.0
def getIntOrQuit():
resp = input("Enter a number or (q)uit:")
if resp == "Q":
return None
return safe_float(resp)
print( sum(iter(getIntOrQuit,None)) )
is another way to do what you want :P

Categories

Resources