def main():
Need the code to ask the user a number and print out number in words digit by digit.
Ex. Input: 473
Output: four seven three
numbers = ["zero","one","two","three","four","five","six","seven","eight","nine"]
n = eval(input('Please input a number: '))
print('You typed a number: ',n)
print('The number in words: ', numbers[n])
Cannot get code here to print out more than one digit. I have tried a few for loops and always get the error message with my index
main()
Because your list has 10 items and it can not find index for example 324
so you should split your number into digits and try it for each digit.
numbers = ["zero","one","two","three","four","five","six","seven","eight","nine"]
n = int(input('Please input a number: '))
print('You typed a number: ',n)
print('The number in words: ', end="")
for char in str(n):
print(numbers[int(char)], end=" ")
print()
You are basically trying to access an eleent in an array(your array only have 10 elements, so works fine for n<=10) that doesn't exist. You need to extract the digits, and try for every digit.
you can put numbers in a dictionary
numbers = {'0': 'zero', '1': 'one', '2': 'two', etc...}
then loop throw the user's string:
for number in n:
print(numbers[number] + " ", end='')
here is version that uses a list comprehension:
numbers = ["zero","one","two","three","four","five","six","seven","eight","nine"]
inp = input()
print(" ".join([numbers[int(dig)] for dig in inp]))
Related
My code write the numbers inverted but I would like that they return like:
1
2
3
not 321.
The language is Python, is this possible?
follow my code until now
number= int(input("Write a number \n"))
number= str(number)
print(number[::-1])
Your first problem is that you're trying to iterate through an int type, which isn't an iterable. You need to loop through an iterable (e.g. a list or a range) that consists of the numbers you want to print.
You want to print everything from 1 up to number. You can get a range iterable consisting of these by doing range(1, number + 1). This is saying to produce an iterable that starts from 1 and ends at one number below number + 1 (because things are indexed from 0 in Python).
So just loop through this and print each element:
number = int(input("Write a number: "))
for i in range(1, number + 1):
print(str(i))
How about:
number = input('Write a number: ')
print(*number, sep='\n')
Output:
Write a number: 123
1
2
3
Try this,
number = input("Write a number \n")
for e in number:
print(e)
e represent each element of the str(number)
I wrote this code to get an input of several int numbers and write the smallest and largest of them but the code does not work.
numbers=[]
num=input('enter your number')
Int_num=int(num)
Int_num.append(numbers)
print('maximum number is:',max(numbers))
print('minimum number is:',min(numbers))
In order to get a sequence of numbers:
numbers = []
while True:
number = input('Enter a number or enter q to exit: ')
if number == 'q':
break
else:
numbers.append(int(number))
print(f'Max: {max(numbers)}, Min: {min(numbers)}')
Replace Int_num.append(numbers) with numbers.append(Int_num.append)
To get multiple numbers you can try:
numbers = []
last_number = input('Enter a number: ')
while last_number:
numbers.append(int(last_number))
print(f'Max: {max(numbers)}, Min: {min(numbers)}')
You are trying to append a list to a integer, it should be numbers.append(Int_num), so you will append the number Int_num to the list numbers.
The problem is line
Int_num.append(numbers)
it should be
numbers.append(Int_num)
Also if you put a while(True): around all but the first line you can add lots of numbers to the list (use ctrl+c to stop the program, if it's running in cmd or powershell)
Try this:
numbers=[]
num=input('enter your number')
while num != "":
Int_num=int(num)
numbers.append(Int_num)
num=input('enter your number')
print('maximum number is:',max(numbers))
print('minimum number is:',min(numbers))
So were given a task that enters 6 digits, I want to put a length validation in my list because i had already done my number validation. for some reason even though i entered six numbers it prints ("6 digits only! Please try again"). anyways this is my code (pardon for the code construction since I just started learning python)
while True:
numbers = input("Enter 6 digits: ")
if numbers.isalpha():
print("Invalid Input!", numbers ," is not a number!")
else:
NumberList = numbers.split()
if len(NumberList) == 6:
print("user list is ", NumberList)
break
else:
print ("6 digits only! Please try again")
The split function, called without arguments, splits on whitespaces.
So, your string is not splitted to a list (you obtain only a list with one element, your string).
print("123456".split())
['123456']
To split the string, in this case, you have to use: NumberList = list(numbers).
list("123456")
['1', '2', '3', '4', '5', '6']
The input would surely give you a string and so you can use the split function, but it expects spaces by default.
So splitting this string would result in ['splitting,'this','string'], but something like 123456, results in ['123456'] and so the length is always one.
The way to solve this, is to convert the string to a list:
Replace
NumberList = numbers.split()
with
NumberList = list(numbers)
This should result in ['1','2','3','4','5','6'] and so should give you a proper length.
The string.split() method with no argument specified, will create a list of substrings, by splitting the original string at any white spaces. If your input is, say 123456, then numbers.split() will produce ["123456"] since the input string doesn't have any white spaces. In that case, len(NumberList) is 1 and that's why it fails your validation.
You could instead just check for len(numbers) == 6.
If you want to turn "123456" into ["1", "2", "3", "4", "5", "6"] (since it seems that's what you want to print), you can use list(numbers)
while True:
numbers = input("Enter 6 digits: ")
if numbers.isalpha():
print("Invalid Input!", numbers ," is not a number!")
else:
NumberList = len(numbers)
if NumberList == 6:
print("user list is", NumberList)
break
else:
print ("6 digits only! Please try again")
I assume your input is something like "123456", first of all, your check str.isalpha() will return true only if all the element of the string are letters, meaning that "123asd" would be considered False, and therefore valid for your program, which is a mistake, secondly str.split() will only separate the string according to a separator char, the default one is the blank space, if your line is "123456", the result of split, will just be a list of one element with the full string, because there is no space in that line.
while True:
numbers = input("Enter 6 digits: ")
if sum([n.isalpha() for n in numbers]):
print("Invalid Input!", numbers ," is not a number!")
else:
NumberList = list(numbers)
if len(NumberList) == 6:
print("user list is ", NumberList)
break
else:
print("6 digits only! Please try again")
Also, there is no need to split the string to a list, if the only operation you need to do is check its lenght, you can just use len(numbers)
while True:
num = input("Enter a Number: ")
try:
numbers = [int(i) for i in num]
if len(numbers) == 6:
print('valid')
numbers = numbers[:5]
print(numbers)
else:
print('invalid')
except ValueError:
print('only numbers')
The number validation is incorrect if you only want numbers. I tried entering numbers first then letters and I got through it.
I have this code for a program that should manipulate certain inputs the user enters.
I'm not sure how to only get x number of ouputs (x is specified by the user at the start of the program).
numOfFloats = int(input("Enter the number of floating point inputs: "))
numOfInts = int(input("Enter the number of integer inputs: "))
numOfStrings = int(input("Enter the number of string inputs: "))
for num in range(numOfStrings,0,-1):
print()
ffloats = float(input("Enter a real number: "))
iints = int(input("Enter an integer: "))
string = input("Enter a string: ")
print()
print("float: ", ffloats**(1/10))
print("int: ", iints**10)
print("string: ", (string + string))
I get all three requests each time, even though I have specified in the beginning that I only want 1 float, 2 ints, and 3 strings. I get asked for 3 floats, 3 ints, and 3 strings. I do realize what my code does, but I'm not sure how to get it to where I want it. I have a feeling something is wrong in the for loop conditions.
Any help is appreciated!
ffloats = []
for num in range(numOfFloats):
ffloats.append(float(input("\nEnter a real number: "))
iints = []
for num in range(numOfFloats):
iints.append(int(input("\nEnter an integer: "))
sstrings = []
for num in range(numOfFloats):
sstrings.append(input("\nEnter a real number: ")
print("Floats:", [f**(1/10) for f in ffloats])
print("Ints:", [i**10 for i in iints])
print("Strings:", [s + s for s in sstrings])
If you want them in order, then you'll have to:
for v in range(max([numOfFloats, numOfInts, numOfStrings])):
if v < numOfFloats:
ffloats.append(float(input("\nEnter a real number: "))
if v < numOfInts:
iints.append(int(input("\nEnter an integer: "))
if v < numOfStrings:
sstrings.append(input("\nEnter a string: ")
The program did exactly what you told it to do: given the number of strings -- 3 -- get that many int-float-string sets. You never used the other two quantities to control their loops. You need three separate loops; here's the one for strings, with all the int and float stuff removed.
numOfStrings = int(input("Enter the number of string inputs: "))
for num in range(numOfStrings,0,-1):
print()
string = input("Enter a string: ")
print()
print("string: ", (string + string))
Now just do likewise for ints and floats, and I think you'll have what you want.
Yes, you can do it in one loop, but it's inelegant. You have to find the max of all three numbers and use that as the loop's upper limit. Within the loop, check "num" against the int, float, and string limits, each in turn.
This code would be less readable, harder to maintain, and slower. Do you have some personal vendetta against loops? :-)
If your really want just a single loop, then I would suggest you use a while loop rather than a for loop, as you need to keep looping until all values have been entered.
numOfFloats = int(input("Enter the number of floating point inputs: "))
numOfInts = int(input("Enter the number of integer inputs: "))
numOfStrings = int(input("Enter the number of string inputs: "))
while numOfFloats + numOfInts + numOfStrings:
print()
if numOfFloats:
ffloats = float(input("Enter a real number: "))
if numOfInts:
iints = int(input("Enter an integer: "))
if numOfStrings:
string = input("Enter a string: ")
print()
if numOfFloats:
print("float: ", ffloats**(1/10))
numOfFloats -= 1
if numOfInts:
print("int: ", iints**10)
numOfInts -= 1
if numOfStrings:
print("string: ", (string + string))
numOfStrings -= 1
So for example:
Enter the number of floating point inputs: 1
Enter the number of integer inputs: 2
Enter the number of string inputs: 3
Enter a real number: 1.5
Enter an integer: 2
Enter a string: three
float: 1.0413797439924106
int: 1024
string: threethree
Enter an integer: 2
Enter a string: hello
int: 1024
string: hellohello
Enter a string: world
string: worldworld
the program asks user to enter 5 unique number, if the number is already in the list, ask for a new number. after 5 unique numbers have been entered, display the list
numbers = ['1','2','3','4','5']
count = 0
index = 0
while count <6:
user = raw_input ("Enter a number: ")
if user in numbers:
print "not unique"
if user not in numbers:
print "unique"
count += 1
numbers = numbers.replace(index,user)
index +=1
print numbers
when the program gets to the replace method, it raise an attribute error
You can use:
numbers[index] = user
A list doesn't have a replace() method. A string does have a replace method however.
If you wish to append a number to the end of a list, you can use append():
numbers.append(user)
If you wish to insert a number at a given position, you can use insert() (for example, position 0):
numbers.insert(0, user)
You don't have to initialize a list in Python:
numbers = []
while len(numbers) != 5:
num = raw_input('Enter a number: ')
if num not in numbers:
numbers.append(num)
else:
print('{} is already added'.format(num))
print(numbers)
You can replace it with Subscript notation, like this
numbers[index] = user
Apart from that your program can be improved, like this
numbers = []
while len(numbers) < 5:
user = raw_input ("Enter a number: ")
if user in numbers:
print "not unique"
else:
print "unique"
numbers.append(user)
print numbers
If you don't care about the order of the numbers, you should probably look into sets. Addidionally, if you want to work with numbers, not strings, you should cast the string to an int. I would've written something like this.
nums = set()
while len(nums) < 5:
try:
nums.add(int(raw_input("Enter a number: ")))
except ValueError:
print 'That is not a number!'
print 'Numbers entered: {}'.format(', '.join(str(x) for x in nums))
Output:
Enter a number: 5
Numbers entered: 5
Enter a number: 3
Numbers entered: 3, 5
Enter a number: 1
Numbers entered: 1, 3, 5
Enter a number: 7
Numbers entered: 1, 3, 5, 7
Enter a number: 9
Numbers entered: 1, 3, 9, 5, 7