Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Function to convert
#1
How to write a function that takes a single parameter ( for example numbers from 1-10) then returns a string like "one" to number 1 and "two" to number 2.

def numberconvert(x):
    if x== 1;
    return "one"
somehow it doesn't look to be alright.
Should a try to use a list=["one,"two",...]?
Reply
#2
i would use a dictionary to associate the number with the text. In this wa yyou wouldnt even really need a function as there wouldnt be much code. Just return dict[NUM_AS_INT] to get the text num
Recommended Tutorials:
Reply
#3
The task is to write a function which will associate the number with a text, so have to make one.
Reply
#4
Watch your typing, the end of your "if" statement should be a colon, not a semi-colon. Also, please get away from using single letter variables and use descriptive names instead. Metulburr is not saying you can't use a dictionary in a function, just that you could. That is, if you are allowed to use dictionary's. Did the instruction say how large a number your function should handle? Would it be 10? If so, a list or dictionary could be used. How would do it with a list?
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#5
Yes, I did mistype the semicolon, The instruction is to write a function which asks for a single parameter, in my case a number and it will return a string( for number 1="one") it should handle numbers from 1-10.
After that, i have to use this function in another function what I have made already

def count(numOne, numTwo):
for i in range (numOne,numTwo+1):
print i


print count(2,8)

and the results should be instead of 2,3,4,5,6,7,8, one two three...
Reply
#6
Please repost your code using the the code tags so we can see your indentation. See the link in your first post. Also you say you function can only take a single argument, you are providing 2. Where is the list?
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#7
def numberToText(x):
if x==1:
return "one"
elif x==2:
return "two"
elif x==3:
return "three"

def count(numOne,numTwo):
numberToText()
for i in range (numOne,numTwo):
print i


print count(1,3)
Reply
#8
You won't be asked again to use the code tags.

You now have two functions, the primary one still using two arguments.
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020