I'm a beginer in Python and I do not succeed to figure out how to solde the issues in my code. As my lecture do not provide any assistance, according to the online module that became mandatory because of the corona, I really need your help !
Before to go on the issues, there is the goals of my code :
The first function take as arguments 2 integers, and returns a random number between those integers. We will call this function get_rand_int. If the two integers are equals, this is an error and we will return None. (Hint: just put return None as your line for these cases.) We can test for the result of None in the second function and report that it was an error there.
The second function, called print_random, asks for user input for one integer greater than 0, and if it receives good input, calls the first function. It converts the user input to an integer and calls the first function with 0 as the first argument and the user input as the second argument. We capture the output from the first function in a variable (e.g., rand = get_rand_int(0, input)). Our second function then prints out the number returned by the first function in a sentence: "Your random number is " and then the number.
For now, I think my code is in line with the goal ( just need to add something in the case of the first functiun would return "none") but I'm stuck with a small error which is making me stuck ! This error occurs when I'm trying to run the second function !
File "<ipython-input-83-f6b07c49d323>", line 2
def print_random():
^
SyntaxError: unexpected EOF while parsing
My code
import random
def get_rand_int(arg1, arg2):
rand = random.randint(arg1, arg2)
if float(rand) == float(arg1):
return None
elif float(rand) == float(arg1):
return None
else:
print(rand)
def print_random():
try :
prompt = int(input("Please enter an integer greater than 0:"))
assert(prompt > 0)
except:
print("Invalid input: You must input an integer greater than 0 for your input.")
rand = get_rand_int(0, input)
print( "Your random number is ",rand)
Thanks for your help !
You had two mistakes that were not terribly obvious. You tried passed the input function to your get_rand_int method and you forgot to return the rand value. Complete working code below:
import random
def get_rand_int(arg1, arg2):
rand = random.randint(arg1, arg2)
if float(rand) == float(arg1):
return None
elif float(rand) == float(arg1):
return None
else:
print(rand)
return rand # You need to return the random value
def print_random():
try :
prompt = int(input("Please enter an integer greater than 0:"))
assert(prompt > 0)
except:
print("Invalid input: You must input an integer greater than 0 for your input.")
rand = get_rand_int(0, prompt) # You need to pass in the value return from input, not input func
print( "Your random number is ", rand)
Related
When running the program i get exit code 0 but it doesnt execute the whole function/code. It seems it just runs the first line...any ideas on how to solve this? many thanks in advance!
import random
def mastermind():
#asking for length
length=int(input("chain length of 2 to 9: "))
#generating random chain of 2 to 9 numbers according to user's demand:
chain=[]
for number in range(length+1):
chain_nr=random.randint(1,9)
chain.append(chain_nr)
return chain
#guessed chain
guessed_chain = int(input("guessed chain: "))
guessed_count = 0
for nr in guessed_chain:
if nr in chain and nr == chain[0]:
guessed_count +=1
print(f'"you\'ve guessed" {guessed_count}"numbers of the chain"')
else:
print("you haven't guessed any number")
mastermind()
As other answers replied, the error is in the return clause, where it should be removed (as it temrinates the execution), as well as the need to cast the second input to str in order to iterate and compare. However, the input clause already returns a string, so you could either cast the first input to str or cast each value of the second input to int when comparing.
Also, if you wanted to compare each chain of numbers character-wise (first one to first one, and so on), the logic of your program is wrong (it's comparing each element of the second chain to only the first value of the first random chain!).
Here is the code, with a print statement of the first chain in order to debug.
import random
def mastermind():
#asking for length
length=int(input("chain length of 2 to 9: "))
#generating random chain of 2 to 9 numbers according to user's demand:
chain=[]
for number in range(length+1):
chain_nr=random.randint(1,9)
chain.append(chain_nr)
print(chain)
#guessed chain
guessed_chain = input("guessed chain: ")
guessed_count = 0
for i, nr in enumerate(guessed_chain):
if int(nr) in chain and int(nr) == chain[i]:
guessed_count +=1
print(f'"you\'ve guessed" {guessed_count}"numbers of the chain"')
else:
print("you haven't guessed any number")
mastermind()
EDIT: here is a more pythonic way to construct the random chain of integers, using list comprehension.
chain=[random.randint(1,9) for i in range(length+1)]
You simply need to remove the return statement from the middle of your code. Calling a return statement makes your code exit the function, and return the chain that you generated. There is no need for that.
If you run this without the return statement you will encounter another error. The next user input should be of type string and not int, hence you will need to parse it as such with str() rather than int() as something of type int is not iterable.
import random
def mastermind():
#asking for length
length=int(input("chain length of 2 to 9: "))
#generating random chain of 2 to 9 numbers according to user's demand:
chain=[]
for number in range(length+1):
chain_nr=random.randint(1,9)
chain.append(chain_nr)
# no need for the return statement here
#guessed chain
guessed_chain = str(input("guessed chain: "))
guessed_count = 0
for nr in guessed_chain:
if nr in chain and nr == chain[0]:
guessed_count +=1
print(f'"you\'ve guessed" {guessed_count}"numbers of the chain"')
else:
print("you haven't guessed any number")
mastermind()
Also for the future, try to provide a minimal reproducible example of your code, and explain why you think it is showing you an error, what you did and not just the what the error is.
this is what i see in the console:
I imported
mastermind will be called
chain length of 2 to 9: 5
guessed chain: 456
Traceback (most recent call last):
File "E:/Python/Part3ej2.py", line 28, in <module>
mastermind()
File "E:/Python/Part3ej2.py", line 21, in mastermind
for nr in guessed_chain:
TypeError: 'int' object is not iterable
Process finished with exit code 1
If the given number is less than the 2, it asks to reenter the number by using recursion.
I've first given 2 and then after recursion, I gave 3, but the output is still 2.
How to output 3?
def inexpno():
exp = int(input("Enter the Experiment n.o : ")) # Takes a exp number
if exp<=2: # Enter your completed experiment here
print("It is completed Correction for both Record and Observation\n\n")
print("Do you want to select another experiment")
we = input("")
if we == "yes" or we == "YES":
inexpno() # TO CHANGE
else:
exit()
return exp
print(inexpno())
Currently you don't save the return value from inexpno() in the recursive call on line 8. You simply need to save it as exp:
exp = inexpno()
Just change your recursive line to
return inexpno()
I am a new learner for Python. I have a question about while loop.
I wrote a program below to look for square roots.
When I input anything but integers, the message "is not an integer" shows up and it repeats itself until I input correct data(integers).
My question is, why does it end loop when it return value on line 5, return(int(val))?
Thank you for your attention.
def readInt():
while True:
val = input('Enter an integer: ')
try:
return(int(val))
except ValueError:
print(val, "is not an integer")
g = readInt()
print("The square of the number you entered is", g**2)
To answer your original question, 'return' effectively exits the loop and provide the result that follows the 'return' statement, but you have to explicity print it like so:
def read_int(num1, num2):
while True:
return num1 + num2
print(read_int(12, 15))
If you simply put 'read_int(12, 14)' instead of 'print(read_int(12, 15))' in this scenario, you won't print anything but you will exit the loop.
If you allow me, here are some modifications to your original code:
def read_int(): # functions must be lowercase (Python convention)
while True:
val = input('Enter an integer: ')
try:
val = int(val) # converts the value entered to an integer
minimum_value = 0 # There is no need to evaluate a negative number as it will be positive anyway
maximum_value = 1000000 # Also, a number above 1 million would be pretty big
if minimum_value <= val <= maximum_value:
result = val ** 2
print(f'The square of the number you entered is {result}.')
# This print statement is equivalent to the following:
# print('The square of the number you entered is {}.'.format(result))
break # exits the loop: else you input an integer forever.
else:
print(f'Value must be between {minimum_value} and {maximum_value}.')
except ValueError: # If input is not an integer, print this message and go back to the beginning of the loop.
print(val, 'is not an integer.')
# There must be 2 blank lines before and after a function block
read_int()
With the final 'print' that you actually have at the end of your code, entering a string of text in the program generates an error. Now it doesn't ;). Hope this is useful in some way. Have a great day!
I am making an area calculator to help me understand the basics of Python, but I want to do some type of validation on it - if a length is less than zero, then ask again.
I've managed to do this with the 'validation' code inside the function for the shape (e.g. inside the 'square' function) but when I put the validation code in a separate function - 'negativeLength,' it doesn't work. This is my code in the separate function:
def negativeLength(whichOne):
while whichOne < 1:
whichOne = int(input('Please enter a valid length!'))
When I run this by calling 'negativeLength(Length)' it will ask me for the length again (as it should) but when I enter the positive length, the condition is met and so the actual loop does not run.
I have also tried (after following Emulate a do-while loop in Python?)
def negativeLength(whichOne):
while True:
whichOne = int(input('Please enter a valid length!'))
if whichOne < 1:
break
... but that doesn't work either.
I've put the parameter as 'whichOne' because the circle's 'length' is called Radius, so I'd call it as negativeLength(Radius) instead of negativeLength(Length) for a square.
So is there any way to make the while loop finish after the 'whichOne = int(input...)'?
Edit: I'm using Python 3.3.3
The code you've written works, as far as it goes. However, it won't actually do anything useful, because whichOne is never returned to the caller of the function. Note that
def f(x):
x = 2
x = 1
f(x)
print(x)
will print 1, not 2. You want to do something like this:
def negative_length(x):
while x < 0:
x = int(input('That was negative. Please input a non-negative length:'))
return x
x = input('Enter a length:')
x = negative_length(x)
I'm going to assume you're using Python 3. If not, you need to use raw_input() rather than input().
The code that I usually use for this would look like:
def negativeLength():
user_input = raw_input('Please enter a length greater than 1: ')
if int(user_input) > 1:
return user_input
input_chk = False
while not input_chk:
user_input = raw_input('Entry not valid. Please enter a valid length: ')
if int(user_input) > 1:
input_chk = True
return user_input
Which should do what you want.
I simply cannot understand what is happening here. The problem is important for my homework (studying programming so I'm a beginner... also my English is not that good, sorry).
I am trying to read a string... it can be either a number or a set number of commands.
I'll just give a very small example of what I'm trying to do and what is going wrong.
def validate():
choice = str(input(">>> "))
if (choice == "exit"):
return 0 # should exit validate
else:
try:
aux = int(choice) # Tries converting to integer
except:
print("Insert integer or exit")
validate() # If it can't convert, prompts me to try again through
# recursivity
else:
return aux
rezult = validate()
print (rezult)
Problem is that this small script returns totally random stuff.
If "exit", returns "None".
If first input is correct, it returns correct number.
If first input is an "error" and second input is correct, it's "None" again and I simply can't understand what is going wrong... Why it doesn't want to work or what should I do (alternatively).
In case you enter the except block, the function validate() uses a recursive call to call itself. When this call returns, it returns to the place where the function was called, i.e. into the except block. The return value of validate() is ignored at this point, and control reaches the end of the outer call without hitting a return statement, so None is implicitly returned.
Don't use recursion here. Use a loop.
Use raw_input instead of input (unless you are on Python 3.x):
choice = raw_input(">>> ")
And you are missing a return here:
except:
print ("Insert integer or exit")
return validate () # <<< here
Also, don't use recursion for this. Use a loop instead.
Ok, decided to listen and changed the recursive part into a loop, thank you for your help. (Works now)
def validateChoice():
condition = False
while (condition == False):
choice = str (input (">>> "))
if (choice == "exit"):
return 0
else:
try:
aux = int (choice)
except:
print ("Insert integer or 'exit'")
else:
condition = True
return aux