How is user input converted into a list with Python? - python

d_num = []
d_num.append(input("Enter a figure to verify if is a Disarium number: "))
With the above code, an input of 135 and print(d_num), would return '135' opposed to '1, 3, 5'.
A quick-fix would be, prompt the user to include whitespace or other characters between digits and use the split command. However, that poses a problem because the output calculation is based upon the index of the digit.
For example:
input: 135
output: true, 135 == Disarium number as 1^1 + 3^2 + 5^3 = 135
Is there an easier way to convert user input, despite type, into a list?

You wanted to know a way to automatically store each digit of the user input as a list item right? Below is the easiest way I can think of:
user_input = input("Enter a figure to verify if is a Disarium number: ")
d_num = [digit for digit in user_input]
The d_num list will have each digit stored separately and then you can convert it into an integer/float and perform the calculation to identify if its a Disarium number or not.
As #Jérôme suggested in the comment, a much simpler solution would be to simply convert the user input to a list and python handles the work of adding individual characters as a list item.
d_num = [digit for digit in user_input] can be written as d_num = list(user_input)
Hope that helps

Calling list(d_num) will give you a list of the individual characters that make up the number. From there, you can just go over them, convert them to integers and raise them to the appropriate power:
if int(d_num) == sum((int(d[1])**(d[0] + 1) for d in enumerate(list(d_num)))):
print("%s is a Disarium number" % d_num)
EDIT:
As Jean-François Fabre commented, you don't actually need the list call - you could enumerate the string's characters directly:
if int(d_num) == sum((int(d[1])**(d[0] + 1) for d in enumerate(d_num))):
print("%s is a Disarium number" % d_num)

Related

Sequence of numbers - python

i create a program that reads a sequence of numbers, determines how many different numbers there are (we count the repetitions once), and writes the result to the standard output.
my first code:
f=int(input("String of numbers: "))
l=[]
for x in range(f):
string_numbers = int(input(f'Enter {x+1} string of numbers: '))
l.append(string_numbers)
mylist = list(dict.fromkeys(l))
print(len(mylist))
I wanted to take into account if the user entered a string too short or too long than declared. I wanted the user to type everything on one line. When I enter an incorrect string number, I get duplicated "incorrect string lengthincorrect string length"
f=int(input("String of numbers: "))
my_list = input('Enter numbers in the string, separated by spaces: ').split()
list_of_integers=[]
l=len(str(list_of_integers))
for i in my_list:
list_of_integers.append((i))
mylist = list(dict.fromkeys(list_of_integers))
for i in range(f):
if i < l:
print("incorrect string length", end='')
elif i > l:
print("incorrect string length", end='')
else:
It seems like you're mixing up your different variables -- f is what you want the length to be, l is just the number 2, and the way you're comparing those two has nothing to do with the actual input entered by the user, which is my_list.
Using variable names that indicate their meaning might make it easier to keep it all straight:
num_count = int(input("Length of string of numbers: "))
num_list = input('Enter numbers in the string, separated by spaces: ').split()
if len(num_list) == num_count:
print(f"there are {len(set(num_list))} different numbers")
else:
print("incorrect string length")
In the above code, num_count is the count of how many (non-unique) numbers you expect them to input, and num_list is the actual list. To figure out if the list is the expected length, compare num_count to len(num_list).
Note that since all you're doing is looking for unique values, converting the strings in num_list to int is not necessary (whether or not you use a set as I've done here).
You will most likely be better off using another function that ultimately has a while loop. This will make sure that when the user is giving the input that if anything is malformed you can then parse it checking and finally making sure to prompt the user again.
For example:
f=int(input("String of numbers: "))
my_list = input('Enter numbers in the string, separated by spaces: ').split()
list_of_integers=[]
l=len(str(list_of_integers))
for i in my_list:
list_of_integers.append((i))
mylist = list(dict.fromkeys(list_of_integers))
for i in range(f):
# XXX Here call your "input-function"
get_user_input(i, l)
def get_user_input(user_len, len):
while True user_len != len:
print('Incorrect Input')
user_len = int(input("String of numbers: "))
return
This is not exactly a working example but with what you have you get the idea that you want to do a while loop until your inputs match.

How can I write a string inside of an input?

I'm having a problem of printing a string inside an input. I made a for loop for automatic numbering based on how many elements that the user wants to input.
list = []
n = int(input("How many elements you want to input: "))
for i in range(0, n):
element = int(input(i+1))
if n == element:
print("hello")
break
list.append(element)
For example, I inputted 3 in the number of elements. I want to make my program output be like this:
input
input
input
(input is the user will type once the number is shown)
But my program looks like:
1input
2input
3input
I just want to work up with the design, but I don't know how to do it.
What you need is called string formatting, and you might use .format by replacing
element = int(input(i+1))
using
element = int(input("{}. ".format(i+1)))
or using so-called f-strings (this requires Python 3.6 or newer):
element = int(input(f"{i+1}. "))
If you want to know more, I suggest reading realpython's guide.
Try:
input(str(i+1)+'. ')
This should append a point and a space to your Text. It converts the number of the input to a String, at which you can append another String, e.g. '. '.
You have to edit the input in the loop to something like this:
element = int(input(str(i+1) + ". "))
You are close. Convert i+1 to a string and concatenate a . to it and accept input.
Note: Do not use list as a variable name. It is a Python reserved word.
lst = []
n = int(input("How many elements you want to input: \n"))
for i in range(n):
element = int((input(str(i+1) + '. ')))
if n == element:
print("hello")
break
lst.append(element)
How many elements you want to input:
5
1. 1
2. 6
3. 7
4. 4
5. 6
n = int(input("How many elements you want to input: "))
for i in range(0, n):
print(str(i+1) + ". " + str(n))
This should do.
I used the same code shape as yours, and that way it is easier for you to understand.

Why does this print if it's above value 99?

mySpeed = input("What is your speed? ")
if mySpeed < ("50"):
print ("safe")
Why does this print if the value is above 99?
Try this:
mySpeed = int(input("What is your speed? "))
if mySpeed < 50:
# same as before
Explanation: you should read a number and compare it against a number. Your code currently is reading a string and comparing it against another string, that's not going to give the results you expect.
Because you are comparing two strings, not two integers. A string is a sequence and for a sequence comparison works as follows:
The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.
So if you take a number large than '99', e.g. '100' it will take the first character '1' and compare it to '5' (first character of '50'). '1' is smaller than '5' in ascii ('1'==49 and '5'==53). So this comparison will already terminate and the result will be that indeed '100' is smaller than '50'.
For the same reason '9' is not smaller than '50':
In [1]: b'9'<b'50'
Out[1]: False
You should compare integers, as follows:
mySpeed = int(input("What is your speed? "))
if mySpeed < 50:
print ("safe")
"50" is a string, not a number ... try eliminating the " " ...
If mystring is a string, try a cast with the int-function - e.g. int(mystring)
mySpeed < ("50") is checking a string. You need to be working with integers:
mySpeed = input("What is your speed? ")
if mySpeed < (50):
print ("safe")
You can't evaluate a string as if it were an integer. Think of a string as the word "ten", whereas the integer is "10". You can't add the three letters t-e-n to an integer and result in a number. However, you can add "10+10", for example to result in "20". Your code should look like this:
mySpeed = int(input("What is your speed? "))
if mySpeed < 50:
print ("safe")
NOTE: by using the int() function to turn users' input into an integer, you are not in fact verifying what they input. If the user inputs a string, such as "ten", your code will return an error because "ten" cannot be converted into an integer.
My answer isn't best practice, but it will "work".

Python - Write a for loop to display a given number in reverse [duplicate]

This question already has answers here:
Using Python, reverse an integer, and tell if palindrome
(14 answers)
Closed 8 years ago.
How would I have the user input a number and then have the computer spit their number out in reverse?
num = int(input("insert a number of your choice "))
for i in
That is all I have so far...
I am using 3.3.4
Here's an answer that spits out a number in reverse, instead of reversing a string, by repeatedly dividing it by 10 and getting the remainder each time:
num = int(input("Enter a number: "))
while num > 0:
num, remainder = divmod(num, 10)
print remainder,
Oh and I didn't read the requirements carefully either! It has to be a for loop. Tsk.
from math import ceil, log10
num = int(input("Enter a number: "))
for i in range(int(ceil(math.log10(num)))): # => how many digits in the number
num, remainder = divmod(num, 10)
print remainder,
You don't need to make it int and again make it str! Make it straight like this:
num = input("insert a number of your choice ")
print (num[::-1])
Or, try this using for loop:
>>> rev = ''
>>> for i in range(len(num), 0, -1):
... rev += num[i-1]
>>> print(int(rev))
Best way to loop over a python string backwards says the most efficient/recommended way would be:
>>> for c in reversed(num):
... print(c, end='')
Why make it a number? 'In reverse' implies a string. So don't cast it to int but use it as string instead and just loop over it backwards.
You've got here a variety of different answers, many of which look similar.
for i in str(num)[::-1]:
print i
This concise variation does a few things worth saying in english, namely:
Cast num to a string
reverse it (with [::-1], an example of slicing, a pythonic idiom that I recommend you befriend)
finally, loop over the resultant string (since strings are iterable, you can loop over them)
and print each character.
Almost all the answers use [::-1] to reverse the list -- as you read more code, you will see it more places. I recommend reading more about it on S.O. here.
I hate to do your problem for you since you didn't really try to actually solve it or say what you're specifically having a problem with, but:
num = str(input("..."))
output = [num[-i] for i in range(len(num))]
print(output)
output = input("Insert number of your choice: ")[::-1]
print("Your output!: %s" % output)
In python 3.x+ input is automatically a string, doing [::-1] reverses the order of the string

Writing a program that accepts a two digit # that breaks it down

I am currently using Python to create a program that accepts user input for a two digit number and will output the numbers on a single line.
For Example:
My program will get a number from the user, lets just use 27
I want my program to be able to print "The first digit is 2" and "The second digit is 7"
I know I will have to use modules (%) but I am new to this and a little confused!
Try this:
val = raw_input("Type your number please: ")
for i, x in enumerate(val, 1):
print "#{0} digit is {1}".format(i, x)
It was not clear from your question whether you are looking to use % for string substitution, or % for remainder.
For completeness, the mathsy way using modulus operator on ints would look like this:
>>> val = None
>>> while val is None:
... try:
... val = int(raw_input("Type your number please: "))
... except ValueError:
... pass
...
Type your number please: potato
Type your number please: 27
>>> print 'The first digit is {}'.format(val // 10)
The first digit is 2
>>> print 'The second digit is {}'.format(val % 10)
The second digit is 7
Think about the two digit number as though it were a string. It is easier to grab each digit this way. Using str() will change the integer to a string. Modulos allow you to place these strings into your text.
Assuming the user inputs 27 into the variable called num, the code is:
print 'The first digit is %s and the second digit is %s' % (str(num)[0], str(num)[1])
Another way of coding Python:
val = raw_input("Type your number please: ")
for i in list(val):
print i
Note: val is read as string. For integer manipulation, use list(str(integer-value)) instead
two_digit_number = input("Type a two digit number: ")
print("The first digit is " + two_digit_number[0] + " The second digit is " +
two_digit_number[1])
You don't need modules to solve this question.

Categories

Resources