Python repeat function two times when memorize a variable - python

I'm creating a function in python that is repeated two times when it ends even if it doesn't have to do it.
def first ():
numuser = int(input("Write a number"))
if(0 < numuser < 26):
print("Ok")
else:
print("Wrong!, restart it!")
first() #If the number is out of the range it restart the function
return numuser
first()
def second():
numuserfirst = first() #retrive the number choosen in the first function
second()
Repetition is caused by the variable call numuserfirst = first(), how can I solve it?
Thanks

Don't use recursion to implement a simple loop; use a while statement. One possible implementation:
def first():
while True:
numuser = int(input("Write a number"))
if 0 < numuser < 26
break
print("Wrong!, try again")
print("OK")
return numuser

Related

My friend told me to make an program on Fault_in_Calculator which calculated user entered digit but closes off on wrong output

a=int(input("Enter 1st number: ")) b=int(input("Enter 2nd number: ")) c=input("Enter the operator: ") n=0
def plus(a,b): n=a+b print(n)
def minus(a,b): n=a-b print(n)
def multiply(a,b): n=a*b print(n)
def divide(a,b): n=a/b print(n)
if a%2==0: pass else: a+=1
if b%2==0: b+=1
if c=="+": d=a+b plus(a,b) elif c=="-": d=a-b minus(a,b) elif c=="x" or "X": d=a*b multiply(a,b) elif c=="/": d=a/b divide(a,b) else: print("Input correct operator.")
print(d) if d==n: pass else: print("Oops, I didn't got right answer. Sorry for that, I am closing off.")
Problems:
Divide operator doesn't works properly.
Calculator last sentence is printed all time no matter if it's calculation is right.
There are two Problems in the code (ok the formatting of the code is also a problem. Hopefully you only put it in that format for the question if not pls try to indent the code right and don't put multiple statements in one line)
For the Problems: It always runs the multiply option because the if Statement is wrong.
Instead of elif c=="x" or "X": you have to write elif c=="x" or c=="X": so you missed the variable to check against in the or clause.
The second thing your variable n will not be changed inside the function. Inside the Function it defines a new local (local to the function) variable n if you want to change the outside variable n you have to define it as global inside each of the functions who changes the value of n.
Here is the Code:
a=int(input("Enter 1st number: "))
b=int(input("Enter 2nd number: "))
c=input("Enter the operator: ")
n=0
def plus(a,b):
global n
n=a+b
print(n)
def minus(a,b):
global n
n=a-b
print(n)
def multiply(a,b):
global n
n=a*b
print(n)
def divide(a,b):
global n
n=a/b
print(n)
if a%2==0:
pass
else:
a+=1
if b%2==0:
b+=1
print(a)
print(b)
if c=="+":
print("Plus")
d=a+b
plus(a,b)
elif c=="-":
print("Minus")
d=a-b
minus(a,b)
elif c=="x" or "X":
print("Multiply")
d=a*b
multiply(a,b)
elif c=="/":
print("Divide")
d=a/b
divide(a,b)
else:
print("Input correct operator.")
if d==n:
pass
else:
print("Oops, I didn't got right answer. Sorry for that, I am closing off.")
If you debug once, you will notice that the value of the variable n does not change until the end of the program. The reason is that n only changes in the scope of each function, but the change to the global variable n is not done!
To change a global variable in a function, do the following:
n=0
def plus(a,b):
global n
n=a+b
print(n)
At the beginning of each function, declare that n is the global variable n.

Passing Variables/lists through Functions

Im having trouble with sorting Variables/lists and then being able to transfer them across functions. Im still quite new to python and am probably missing something very basic. but ive been going over this for hours.
I need to create a program which generates 20 random integers and indicates whether each number is odd or even. I need to sort the two original integers into ascending order and transfer them to random.randint function but am having trouble, any help would be appreciated.
This is what i have so far.
import random
def userinput():
global number1
global number2
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
userinput()
def numbersorting():
global both
both = [(number1),(number2)]
sorted(both)
numbersorting()
def random_gen():
global num
i = 0
for i in range(20):
num = random.randint(number1,number2)
def get_num():
return values.pop
def odd_even():
if num % 2 == 0:
print("Random Number", num, "is even")
else:
print("Random Number", num, "is odd")
odd_even()
random_gen()
Well it doesn't seems so clear on the question what actually you want to do but the use of global is a really bad practice in general.
However you can use the methods that returns the values you need for instace:
If you need a user input that returns 2 numbers it is better to use this approach:
def get_numeric_input(label):
try:
return int(input(label))
except NameError:
print "Please enter a number"
return get_numeric_input(label)
With this function you can get a numeric value from a user.
Using it you can the 2 next values like
def get_user_input():
n = get_numeric_input("Enter First Integer: ")
m = get_numeric_input("Enter First Integer: ")
return [n, m]
Now you have a function that returns the 2 values from the user and using the sort method for list you have those values sorted
def get_sorted_values(l):
return l.sort()
Check this information about sorting in python https://wiki.python.org/moin/HowTo/Sorting
Using the random numbers as you have described is ok, but also try to use the is_odd and is_even function outside of any other function and you will be able to reuse them more times.
Are you looking for something like this?
I edited your code to work with what I understand your problem to be...
You want the user to input 2 numbers to set the upper and lower bound of each random number. Then you want to generate 20 random numbers within that range and find out whether each number of even or odd?
import random
def random_gen(number1, number2):
for i in range(20):
num = random.randint(number1,number2)
if num % 2 == 0:
print("Random Number", num, "is even")
else:
print("Random Number", num, "is odd")
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
random_gen(number1, number2)
You have a few problems with your current code:
Indentation (fixed in the edit)
Unnecessary use of global variables. If you need that type of functionality you should consider passing the variables into each function as you need it instead
A number of functions are unnecessary too. For example, you dont need the get_num() and odd_even() functions as you can just perform those actions within the loop that you have. Even in the case I just posted you dont even really need the random_gen() function - you can just move all of that code to after user input. I just left it there to show what I mean with point #2 above
from random import randint
def user_input():
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
if number1 > number2:
number1, number2 = number2, number1
return number1, number2
def odd_even(num):
if num % 2 == 0:
print("Random Number " + str(num) + " is even")
else:
print("Random Number " + str(num) + " is odd")
def random_gen():
number1, number2 = user_input()
for i in range(20):
num = randint(number1, number2)
odd_even(num)
random_gen()
You generally want to try to avoid using global variables when possible. It's just good programming practice, as they can get rather messy and cause problems if you don't keep careful track of them. As far as sorting your two integers, I think that that one if statement is a much more pythonic way of doing things. Well, I think it's easier at least. Also, in Python, you don't need to declare your for loop variables, so the line i=0 is unnecessary. Also, I'm sure this is an assignment, but in real life you're going to want to run an exception clause, in which you would say something like
while True:
try:
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
break
except ValueError:
print("Oops! Try entering an integer!")
Hope that helps!
Avoid globals by passing the variables to functions and returning the new values from functions.
import random
def userinput():
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
return number1, number2
def numbersorting(nums):
return sorted(nums)
def random_gen(hi, lo):
return random.sample(range(hi, lo), 20)
def odd_even(num):
if num % 2 == 0:
print("Random Number %d is even" % num)
else:
print("Random Number %d is odd" % num)
nums = userinput()
sortnum = numbersorting(nums)
randoms = random_gen(*sortnum)
[odd_even(n) for n in randoms]
In keeping with your original function names.
You should be aware of the difference between list.sort and sorted. If you have a list li then li.sort() sorts in place, that is it alters the original list and returns None. So return li.sort() is always wrong. on the other hand return sorted(li) is ok, but just sorted(li) is a wasted sort since the result is thrown away.
Try both.sort()
sorted returns a new list.
sort() is done in place.

Generating a prime number bigger than a number found in a list

What isn't working below: I can't make the genPrim function work, as I get the "TypeError: 'int' object is not subscriptable".
A few observations:
1. What my program should do is first input a number into a list and then apply the other functions on that number.
2. The problem is that I can't seem to use that number from the list to do so. How can I do it? I was first thinking about asking for its position, but when going for the genPrim, both genPrim and Prim work because they are interdependent but they ask for the same thing.
def Adauga(L):
n = int(input("Give number:"))
L = L + [n]
return L
#Verify if number is prime
def Prim(L):
poz = int(input("Position of number: "))
n = L[poz]
if n<2 :
return False
NrDiv=0
for a in range (2,int(n/2+1)):
if n%a==0:
NrDiv=NrDiv+1
if (NrDiv==0):
return True
else:
return False
#Generate prime number
def genPrim(L):
poz = int(input("Give number: "))
a = L[poz]
b=a+1
while Prim(b)==False:
b=b+1
return b
#Display menu
def AfisMeniu():
print()
print("1.Add number")
print("2.Check if number is prime")
print("3.Generate prime number")
print("0.End of program")
i = int(input("Your option: "))
return i
def Main():
"""
Start the program
"""
L = []
Opt = AfisMeniu()
while (Opt != 0):
if Opt == 1:
L=Adauga(L)
elif Opt ==2:
L=Prim(L)
print (L)
elif Opt ==3:
L=genPrim(L)
print (L)
else:
print ("Wrong!")
Opt = AfisMeniu()
print()
print("End of program")
Main()
You are getting that error because genPrim returns an int, but Main() assigns that result to L, so L no longer contains a list of numbers, just that single int.
Similarly, Prim() returns a boolean (True or False) but Main() assigns that to L, too.
FWIW, the basic logic of your Prim() function is correct, but it's a very inefficient way to test if a number is prime. At the very least you should change it to return False as soon as it has found one divisor, i.e. when n%a==0.
I've managed to make the third option work, as in generating a prime number. However, what I would also like is to make the second option work as well, the prime verification.
My idea is modifying the code in the Main() function, by taking the len of the position, however I can't really make it work.
elif Opt ==2:
L=Prim(L)
poz1=int(len(L))
print (L[poz1])
Or perhaps, should I attempt a different method?

Regarding passing variables to an argument

I am working in python 2.7.8.
I'm currently learning about parameters and methods. What I'm trying to accomplish is have a user enter two different variables then pass them to an argument within different methods, sum() and difference().
My following code is something like this:
def computeSum(x, t):
x = int(raw_input('Please enter an integer: '))
t = int(raw_input('Please enter a second integer: '))
x+t
return Sum
def computeDif(y, j):
y = int(raw_input('Please enter an integer: '))
j = int(raw_input('Please enter a second integer: '))
y+j
return Dif
def main():
raw_input('Would you like to find the sum of two numbers or the difference of two numbers?: ')
answer = 'sum'
while True:
computeSum()
else:
computeDif()
For some reason my compiler (pyScriptor) isn't running and I cannot see any output nor error messages, its just blank. Can anyone possibly help me with any syntax/logic errors?
There are a few problems with your code
Your indentation is way off
computeSum and computeDif expect the two numbers as parameters, but then also ask for them from the terminal
You return the variables Sum and Dif, but never assign values to them
You call either computeSum or computeDif, but never do anything with the returned value
You never call main. Do you know that you don't need a main function? You can just put the code in line after the function definitions
This is probably a little closer to what you had in mind
def computeSum(x, t):
return x + t
def computeDif(y, j):
return y - j
def main():
while True:
answer = raw_input('Would you like to find the "sum" of two numbers or the "dif"ference of two numbers? ')
a = int(raw_input('Please enter an integer: '))
b = int(raw_input('Please enter a second integer: '))
if answer == 'sum':
print(computeSum(a, b))
elif answer == 'dif':
print(computeDif(a, b))
else:
print('Please enter "sum" or "dif"')
main()
The problem is that you don't need a main() function. Just put the code, unindented, by itself, and it will run when you run the program.

How do I check a value entered?? Python 3.4 [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
def p_parameter(p):
if p < 10 or p > 100:
int(input("Please try again: "))
newp = p
return newp
else:
newp <10 or newp >100
input("Good bye")
bye()
def main():
speed(0)
R=100
r=4
p=int(input("Please enter a number between 10 and 100: "))
p_parameter(p)
t_iter(R,r,p)
Xcord(R,r,p,t_iter(R,r,p))
Ycord(R,r,p,t_iter(R,r,p))
input("Hit enter to close porgram")
bye()
main()
Here is my code for a program which draws a spirograph. The program runs fine but what I have posted here is my attempt to have the user enter a value between 10-100 for p.
What I want to do is check to see if p is < 10 or p > 100. If it is, then give the user a chance to re-enter a new value of p and use that value as long as it fits the allowed limits. After the second check if the user still has entered an incorrect value of p I want the program to close.
The problem is that it checks for 'p' then asks for p again but it only take the first value of 'p', and does not preform the second check or give p its new value.
You should probably just prompt in the function. This is the standard idiom for writing these kinds of validations:
def validate():
while True:
# begin inf. loop
p = input("some prompt goes here")
if some_validation:
break
# end inf. loop
# therefore if the validation fails, it reprompts
# once you're out of the inf. loop...
return p
This is one of those things you could build a pretty good decorator for
def validate(validation, not_valid_warning=None):
if not hasattr(validation, '__call__'):
raise TypeError("validation must be callable")
def wrapper(f):
def wrapped(*args):
while True:
p = f(*args)
if validation(p):
break
if not_valid_warning:
print(not_valid_warning)
return p
return wrapped
return wrapper
#validate(lambda x: x < 10 or x > 100)
def v_input(*args):
return __builtins__.input(*args)
# Example..........
if __name__ == "__main__":
v_input("Enter a number less than 10 or more than 100: ")
Problems with your solution & Corrections:
it only take the first value of p and does not give p its new value.
you ask the user for p again, but do not assign this new value to newp variable, like so:
newp = int(input("Please try again: "))
does not preform the second check.
your else statement is checking for condition on newp outside the scope of the newp variable, which is inside the if statement. You should encapsulate your check on newp variable inside the if statement, like so:
def p_parameter(p):
if p < 10 or p > 100:
newp = int(input("Please try again: "))
if newp <10 or newp >100:
you don't have return statements inside the p_parameter() function for the instances when the program does not enter the if statement. So it should instead be like this:
def p_parameter(p):
if p < 10 or p > 100:
newp = int(input("Please try again: "))
if newp <10 or newp >100:
print( "Good Bye")
bye()
else:
return newp # need return statements like this
else:
return p # need return statements like this
Suggested Solution to your questions:
What I want to do is check to see if 'p' is < 10 or 'p' > 100, if it is then give the user a chance to reenter a new value of 'p' and use that value as long as it fits within the allowed parameters.
use a while True: infinite loop with the break statement to exit if the correct answer is received.
use try, except and else block with the ValueError
to catch any errors due to inputs that are not integers.
to detect any inputs that are out of the allowed range.
After the second check if the user still has entered an incorrect value of 'p' I want the program to close.
In order to close the program, you can either:
let the user hit ctrl+c (my personal preference), or
put a counter of how many times the while loop should be run to check for new input, and then force the program to exit if a limit is reached by using sys.exit(0) (Note: First You'll need to import sys to use it; I think your bye() is doing just that).
Putting it all together:
In your main() function, remove the input() statement and only have a call to p_parameter() function, like so:
p = p_parameter()
Define p_parameter() function as follows:
import sys
def p_parameter():
exit_counter = 1 # counter to exit after 2 tries
while True:
try:
p = int( input( "Please enter a number between 10 and 100: ") )
except ValueError:
print( "Not a number, Try Again" )
else:
if 10 < p < 100: # this is much faster than your approach
break # exit the loop
else:
print( "Value not in range")
# increment counter to exit when 2 tries are over
exit_counter+=1
if ( counter > 2 ):
print( "Good Bye" )
sys.exit(0) # bye()
return p

Categories