Reputation: 23
I have written the code in the following format.When i entered the age 21 then i should get -0.4.similarly when i entered the age 22 then i should get -0.3,and so on.But i do not want these much line of code.How can i improve this code.can anyone please suggest me
age=int(input("\nEnter the age :"))
a=[-0.4,-0.3,-0.2]
if age==21:
print("beta coefficient is ",a[0])
elif age==22:
print("beta coefficient is",a[1])
elif age==23:
print("beta coefficient is ",a[2])
Upvotes: 1
Views: 71
Reputation:
Heres an efficient way.
print("beta co-efficient is", a[age-21])
It's hard coded that the first value is 21, and that they increment by one, but for your case it will work.
Upvotes: 0
Reputation: 18208
May be you can use dictionary
instead and use key to get the corresponding value as following:
a={21:-0.4, 22:-0.3, 23:-0.2}
print("beta coefficient is ",a[age])
If entered value or key
does not exist in the dictionary, it will raise KeyError
. In that case .get
can be used with default value of None
(or other value) to return when key is not found:
print("beta coefficient is ",a.get(age, None))
Upvotes: 4