How do I spell out each inputted digits in python - python

I need to make a program that takes an integer input and when you enter a number, it types out the spelling of each digit. For example, I inputted 12, the program will print out:
One
Two
I have a little problem with the code, how do I print out the results (or the spellings) vertically and in separate lines? The output should be:
Enter the number: 86
Eight
Six
But my output is:
Enter the number: 86
Eight Six
I just need it to print vertically and in different lines like I said. Thank you! You can alter the code itself too, This is my code:
arr = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine']
def number_2_word(num):
if(num==0):
return ""
else:
small_ans = arr[num%10]
ans = number_2_word(int(num/10)) + small_ans + " "
return ans
num = int(input("Enter the number: "))
print(end="")
print(number_2_word(num))

In this line:
ans = number_2_word(int(num/10)) + small_ans + " "
Use line break rather than space
ans = number_2_word(int(num / 10)) + small_ans + "\n"
I did a few tests, seems work as you expected

Related

I'm trying to create and call a function to reverse a string and remove the integer before the decimal point

So I have been around and around this for ages and I know I am making a newbie error. I just can't figure out what it is. When I think I have it resolved and there are no errors it still doesn't work when I run it. It will ask for the inputs but return nothing.
I did manage to get the string to return it backwards once so I know that the code works there and I tried the float part separately and that worked but I can't figure out how to put them together.
Any help at all would be greatly appreciated. If you could explain where I am going wrong that would be amazing too. Thanks!
def my_function(my_string, my_float):
try:
my_float = float(my_float)
except NameError:
print("That's not a float, try using numbers with a decimal point in the middle of them.")
number = str(my_float)
if 'e-' in number:
my_float = format(float(number),
'.%df' % (len(number.split(".")[1].split("e-")[0]) + int(number.split('e-')[1])))
elif "." in number:
my_float = number.split(".")[1]
return my_float
print("your float minus the integer is: ", my_float)
new_string = ""
i = len(my_string) - 1
while i >= 0:
new_string = new_string + my_string[i]
i = i - 1
print("Your string backwards reads: " + new_string)
print("Please enter a string: ")
mystring = input()
print("Please enter a float number: ")
myfloat = input()
my_function(mystring, myfloat)
Perhaps something like this might do the trick for you:
def my_function(my_string, my_float):
try:
my_float = '.' + ('%f' % float(my_float)).split('.')[1]
print("your float minus the integer is: ", my_float)
except ValueError:
print("That's not a float, try using numbers with a decimal point in the middle of them.")
print("Your string backwards reads: " + ''.join(reversed(my_string)))
Try to remove the return statement inside the function
elif "." in number:
my_float = number.split(".")[1]
return my_float
otherwise, whenever a floating number is passed, that return will be triggered and you won't get any output
maybe I can help you:
string1 = "teststring"
stringReversed = string1[::-1]
floatInput = 12.34
floatStr = str(floatInput)
stuffAfterDecimalPoint = floatStr.split(".")[1]
combinedStrings = stringReversed + stuffAfterDecimalPoint

Creating a Python guessing game

I am new to Python, so I decided to start with a numbers game. I have my numbers being input correctly, but I would like it to display the number of correct answers and the correct original, random numbers.
Code as follows:
import random
print('============================')
print('Now try to guess a list of numbers! The range of number is 0-10')
print('How many numbers do you want?')
numberOfNumbers = int(input('Enter the number: '))
counter = 0
answers = [random.randint(0, 10), numberOfNumbers]
values = []
numCorrect = 0
print('Enter your ' + str(numberOfNumbers) + ' numbers.')
while numberOfNumbers != counter:
counter += 1
values.append(int(input("Enter number " + str(counter) + ": ")))
if values == answers:
numCorrect += 1
print('You got' + numCorrect + ' correct!')
print('Original: ' + str(answers))
print('Your guess: ' + str(values))
Current output:
Now try to guess a list of numbers! The range of number is 0-10
How many numbers do you want?
Enter the number: 3
Enter your 3 numbers.
Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
Original: [5, 3]
Your guess: [1, 2, 3]
Target Output:
Now try to guess a list of numbers! The range of number is 0-10
How many numbers do you want?
Enter the number: 3
Enter your 3 numbers.
Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
(Currently not working for print) You got (x) Correct!
(Here prints answers, it's only printing two numbers) Original: [5, 3, x]
(Your input prints here, working as planned) Your guess: [1, 2, 3]
You do this:
values.append(int(input("Enter number " + str(counter) + ": ")))
if values == answers:
numCorrect += 1
But, since you keep appending to values, it will never be equal to (==) answers until all the correct answers are in there, and even then only if they are in the correct order.
If you want numCorrect to have the number of answers in values that is currently correct, you can write something like:
numCorrect = len([v for v in values if v in answers])
Of course, if you only want to print numCorrect if it changes, you have a bit more code to write.
(also note that this goes sideways if you have duplicate correct answers, so it's not quite this simple, but I'm not writing your game, just correcting your code so it does what you appear to want it to do)
You do this:
answers = [random.randint(0, 10), numberOfNumbers]
That creates a list with two numbers, a random number and numberOfNumbers. It looks like you really want a list of length numberOfNumbers with all random numbers:
answers = [random.randint(0, 10) for _ in range(numberOfNumbers)]
This could include duplicates, but you get to figure out how to avoid that.
In general, I would recommend using a free IDE like PyCharm or Spyder to debug your code. They have options that allow you to step through your code one line at a time, so you can see how the values of variables change as your commands execute - that will make a lot more sense.
Since you are pretty new to python I decided to stick to your code and correct them instead of complicating it. So, what you basically did wrong was that you were using print('You got ' + str(numCorrect) + ' correct!') inside the if statement because if the condition wasn't true the print statement wouldn't work.
The next was that you needed to get the random numbers inside while loop to get the x number of random numbers. Or, else what you were doing was that you simply got one random number and the input from numberOfNumbers.
Here's the final code:
import random
print('============================')
print('Now try to guess a list of numbers! The range of number is 0-10')
print('How many numbers do you want?')
numberOfNumbers = int(input('Enter the number: '))
counter = 0
answers = []
values = []
numCorrect = 0
print('Enter your ' + str(numberOfNumbers) + ' numbers.')
while numberOfNumbers != counter:
ans_var = random.randint(0,10)
answers.append(ans_var)
counter += 1
values.append(int(input("Enter number " + str(counter) + ": ")))
if values == answers:
numCorrect += 1
print('You got ' + str(numCorrect) + ' correct!')
print('Original: ' + str(answers))
print('Your guess: ' + str(values))
Hope it helps :)

i have tried many time using for loop but till now i didnt get correct ans so kaindly help to saltout

Ask the user to enter a number x. Use the sep optional argument to print out x, 2x, 3x, 4x, and 5x, each separated by three dashes, like below.
Enter a number: 7
7---14---21---28---35
You're probably running into issues because input() returns a string, not an integer.
Try this:
num = int(input("Choose a number" + "\n"))
output = num
max = 6
for i in range(2, max):
output = str(output) + "---" + str(num * i)
print(output)
def func(param=0):
print(str(param )+ '---'+str(2*param)+'---'+str(3*param)+'---'+str(4*param)+'---'+str(5*param))
n = int(input("Enter a number"))
func(n)
Try this list comprehension
a=int(input())
print("---".join([str((e+1)*a) for e in range(5)]))
def fun():
# Defining default separator
sep = "---"
# Asking user to enter number
x = input("Enter the number: ")
# Asking user for
new_sep = raw_input('Would you like to provide a separator? If yes, please specify. If not, leave blank and press "return key":')
if new_sep:
sep = new_sep
return sep.join(map(str, [x*n for n in range(1,6)]))
Using default separator
fun()
Enter the number: 7
Would you like to provide a separator? If yes, please specify. If not, leave blank and press "return key":
'7---14---21---28---35'
User specifying separator
fun()
Enter the number: 7
Would you like to provide a separator? If yes, please specify. If not, leave blank and press "return key": ***
'7***14***21***28***35'
You could simply use the sep parameter of print
x=eval(input("Enter a number: "))
print(x,2*x,3*x,4*x,5*x, sep='---')
Output:
Enter a number:7
7---14----21---28---35

How to Separate a Range of Odd and Even Numbers Through Searching the Array While Skipping Numbers

I'd like to challenge myself and develop my programming skills. I would like to create a program that asks for the user to enter a range of numbers where odd and even numbers should be separated (preferably through search) and also separated by a specified jump factor.
Also the user should be allowed to choose whether or not they would like to continue. And if so they can repeat the process of entering a new range.
for example when the program is run a sample input would be:
"Please enter the first number in the range": 11
"Please enter the last number in the range": 20
"Please enter the amount you want to jump by": 3
and the program would output:
"Your odd Numbers are": 11,17
"Your even Numbers are": 14,20
"Would you like to enter more numbers(Y/N)":
So far what I have for code is this but am having trouble putting it together and would appreciate some help.
import sys
print("Hello. Please Proceed to Enter a Range of Numbers")
first = int(input("please enter the first number in the range: "))
last = int(input("please enter the last number in the range: "))
jump = int(input("please enter the amount you want to jump by: "))
def mylist(first,last):
print("your first number is: ",first,"your last number is: ",last,"your jump factor is: ",jump)
def binarySearch (target, mylist):
startIndex = 0
endIndex = len(mylist) – 1
found = False
targetIndex = -1
while (not found and startIndex <= endIndex):
midpoint = (startIndex + endIndex) // 2
if (mylist[midpoint] == target):
found = True
targetIndex = midpoint
else:
if(target<mylist[midpoint]):
endIndex=midpoint-1
else:
startIndex=midpoint+1
return targetIndex
print("your odd Numbers are: ")
print("your even Numbers are: ")
input("Would you like to enter more numbers (Y/N)?")
N = sys.exit()
Y = first = int(input("please enter the first number in the range"))
last = int(input("please enter the last number in the range"))
jump = int(input("please enter the amount you want to jump by: "))
question - "So far what I have for code is this but am having trouble putting it together and would appreciate some help."
answer -
As a start, it seems like a good idea to group your inputs and outputs into functions! Then putting it together is a snap!
def get_inputs():
bar = input('foo')
def process_inputs():
bar = bar + 1
def print_outputs():
print(bar)
if '__name__' == '__main__':
get_inputs()
process_inputs()
print_outputs()
You could even toss in something like if input('more? (Y/N):') == 'Y': in a while loop.
Maybe I'm missing something but couldn't you replace your binary search with the following?
>>> list(filter(lambda x: x%2 == 1, range(11, 20 + 1, 3)))
[11, 17]
>>> list(filter(lambda x: x%2 == 0, range(11, 20 + 1, 3)))
[14, 20]

Flowchart in Python

I need to write a prog in Python that accomplishes the following:
Prompt for and accept the input of a number, either positive or negative.
Using a single alternative "decision" structure print a message only if the number is positive.
It's extremely simply, but I'm new to Python so I have trouble with even the most simple things. The program asks for a user to input a number. If the number is positive it will display a message. If the number is negative it will display nothing.
num = raw_input ("Please enter a number.")
if num >= 0 print "The number you entered is " + num
else:
return num
I'm using Wing IDE
I get the error "if num >= 0 print "The number you entered is " + num"
How do I return to start if the number entered is negative?
What am I doing wrong?
Try this:
def getNumFromUser():
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
else:
getNumFromUser()
getNumFromUser()
The reason you received an error is because you omitted a colon after the condition of your if-statement. To be able to return to the start of the process if the number if negative, I put the code inside a function which calls itself if the if condition is not satisfied. You could also easily use a while loop.
while True:
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
break
Try this:
inputnum = raw_input ("Please enter a number.")
num = int(inputnum)
if num >= 0:
print("The number you entered is " + str(num))
you don't need the else part just because the code is not inside a method/function.
I agree with the other comment - as a beginner you may want to change your IDE to one that will be of more help to you (especially with such easy to fix syntax related errors)
(I was pretty sure, that print should be on a new line and intended, but... I was wrong.)

Categories