Reputation: 1
I am very new to Python (and using Python 3). Apologies---I know I must be making a very basic mistake.
Here is the structure of the mistake and then I'll give an example: I wrote a function func(x)
. To test that it does the "right" things, I plugged in value x1
, i.e. print(func(x1))
. The output was y1
which was correct. Then I tried print(func(x2))
. That again gave me y1
and not the correct y2
. And similarly with other values of x
. At first I thought it was a mistake with that specific function, but then I had similar issues with other functions. Am I making a mistake common to all the functions?
Below is one example; I've tried this (and other functions) with several different variations and still had the problem. I can give other examples, if that would help.
def num_to_day(x):
if 0:
return "Sunday"
elif 1:
return "Monday"
elif 2:
return "Tuesday"
elif 3:
return "Wednesday"
elif 4:
return "Thursday"
elif 5:
return "Friday"
elif 6:
return "Saturday"
else:
return "Not Valid"
print(num_to_day(5))
Upvotes: 0
Views: 3024
Reputation: 40878
With your if
statements, you need to specify x equals each number--for example, if x == 0:
.
Currently, you're testing the truth value of a number itself, with no relation to what x
you have specified. To see this, try:
if 1:
print('Monday')
Monday
You might find it useful to know that in Python, 0
evaluates to False while other integers return True
:
print([bool(num) for num in range(7)])
[False, True, True, True, True, True, True]
bool
tests the truth value of its argument.
Lastly, one alternative of many would be to lookup your weekday from a dict. .get
allows you to specify a value that gets returned if an error is thrown.
def num_to_day(x):
days = {
0 : 'Sunday',
1 : 'Monday',
2 : 'Tuesday',
3 : 'Wednesday',
4 : 'Thursday',
5 : 'Friday',
6 : 'Saturday'
}
return days.get(x, 'Not Valid')
num_to_day(0)
Out[54]: 'Sunday'
num_to_day(10)
Out[55]: 'Not Valid'
Upvotes: 4
Reputation: 675
You're not using your argument inside your function at all.
def num_to_day(x):
if x == 0: # <-- Now x gets evaluated
return "Sunday"
elif x == 1:
return "Monday"
elif x == 2:
return "Tuesday"
elif x == 3:
return "Wednesday"
elif x == 4:
return "Thursday"
elif x == 5:
return "Friday"
elif x == 6:
return "Saturday"
else:
return "Not Valid"
print(num_to_day(5))
Upvotes: 2
Reputation: 12927
You're passing an argument to your function and then not using it at all. To make if work, you must actually compare x
to all those numbers, simple if 0:
is equivalent to if False:
, not to if x == 0:
.
And anyway, this cascade of elif
s is a prime example of how not to code. A much better solution would be to use a list or a dictionary:
def num_to_day(x):
days_of_week = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]
return days_of_week[x]
Upvotes: 0