Harmendez St-Juste
Harmendez St-Juste

Reputation: 33

Python - Function to check if user input matches a condition

I'm writing a script that is asking for user to input a number between 1-10, the script will then call the function Size and will return true if the number is greater or equal to 5 and false if not. However, I seem to have run into a bit of a wall, I get an error asking me to define x, this is my code currently.

def Size(x):
    if x >= 5:
        print("True")
    else:
        print("False")
    x = int(input("Please enter a number greater than 5"))
Size(x)

Upvotes: 1

Views: 1281

Answers (4)

mhhabib
mhhabib

Reputation: 3121

You declared user input x in the Size function. X should be an outside size function

def Size(x):
    if x >= 5:
        print("True")
    else:
        print("False")


x = int(input("Please enter a number greater than 5"))
Size(x)

Or if you want to take user input in Size function then initialize x in Size function and pass just Size function then follow the second answer

Upvotes: 3

Harmendez St-Juste
Harmendez St-Juste

Reputation: 33

def Size(x):
    if x >= 5:
        print("True")
    else:
        print("False")
    x = int(input("Please enter a number greater than 5"))
Size(x)

The error occured because I didn't fix my indentation after the false statement.

Upvotes: 0

Irfan wani
Irfan wani

Reputation: 5075

Define x outside the function. Rest of the code is correct.

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133458

You were close, you need to correct 3 things in your code.

  • Ask user for input before doing checks in your function.
  • Remove variable passed in your user defined function.
  • You need to change name of your function for safer side to make it more meaningful, so I changed it to funcSize.

#!/usr/bin/python3
def funcSize():
    x = int(input("Please enter a number greater than 5: "))
    if x >= 5:
        print("True")
    else:
        print("False")

funcSize()

Upvotes: 3

Related Questions