Reputation: 89
I am trying to write a code for squaring the user input number in Python. I've created function my1() ...
What I want to do is to make Python to take user input of a number and square it but if user added no value it gives a print statement and by default give the square of a default number for e.g 2
Here is what I've tried so far
def my1(a=4):
if my1() is None:
print('You have not entered anything')
else:
b=a**2
print (b)
my1(input("Enter a Number"))
Upvotes: 1
Views: 389
Reputation: 9
In your second line, it should be if a is None:
I think what you want to do is something like the following:
def m1(user_input=None):
if user_input is None or isinstance(user_input, int):
print("Input error!")
return 4
else:
return int(user_input)**2
print(my1(input("Input a number")))
Upvotes: 0
Reputation: 3306
When I read your code, I can see that you are very confused about what you are writing. Try to organize your mind around the tasks you'll need to perform. Here, you want to :
First, take your input.
user_choice = input("Enter a number :")
Then, compute the data you received.
my1(user_choice)
You want your function, as of now, to print an error message if your type data is not good
, else print the squared number.
def my1(user_choice): # Always give meaning to the name of your variables.
if not user_choice:
print 'Error'
else:
print user_choice ** 2
Here, you are basically saying "If my user_choice doesn't exists...". Meaning it equals False
(it is a bit more complicated than this, but in short, you need to remember this). An empty string doesn't contain anything for instance. The other choice, else
, is if you handled your error case, then your input must be right, so you compute your data accordingly.
Upvotes: 0
Reputation: 433
You're getting an infinite loop by calling my1() within my1(). I would make the following edits:
def my1(a):
if a is '':
print('You have not entered anything')
else:
b=int(a)**2
print (b)
my1(input("Enter a Number"))
Upvotes: 0
Reputation: 164803
This is a better solution:
def my1(a=4):
if not a:
return 'You have not entered anything'
else:
try:
return int(a)**2
except ValueError:
return 'Invalid input provided'
my1(input("Enter a Number"))
Explanation
return
values, instead of simply printing. This is good practice.if not a
to test if your string is empty. This is a Pythonic idiom.int
.ValueError
and return an appropriate message in case the user input is invalid.Upvotes: 2