How can I write a string inside of an input? - python

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.

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 is user input converted into a list with 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)

How to read a specific number of integers and store it in a list in python?

Lets suppose I want to first input the total number of integers I am going to enter.
N = 5, I must be able to read exactly 5 integers and store it in a list
for i in range(5):
lst = map(int, raw_input().split())
doesn't do the job
In most primitive way, you can do it in following way.
n = int(raw_input())
numbers = map(int, raw_input().split())[:n]
We can help more if you tell us the context in which you are asking the problem. I doubt if you are using it for some competitive programming problem.
Actually, problem in your code is that you are reading a line and making list from it. But you are doing this FIVE times. Also, you can read lot more than five numbers if they are in single line.
Sa far as I understand, you need the following
lst=[]
for n in range(5):
lst.append(int(raw_input("Input a number: ").split()))
print repr(lst)
inp = raw_input # Python 2.x
# inp = input # Python 3.x
def get_n_ints(prompt, n):
while True: # repeat until we get acceptable input
s = inp(prompt)
try:
vals = [int(i) for i in s.split()]
if len(vals) == n:
return vals
else:
print("Please enter exactly {} values".format(n))
except ValueError:
# a string couldn't be converted to int
print("Values need to be integers!")

Adding up the sum of digits

I need to make a program that the user will enter in any number and then try guess the sum of those digits.
How do i sum up the digits and then compare then to his guess?
I tried this:
userNum = raw_input("Please enter a number:\n")
userGuess = raw_input("The digits sum is:\n")
if sum(userNum, userGuess):
print"Your answer is True"
else:
print "Your answer is False"
and it didnt work
You have 2 problems here :
raw_input() doesn't return an integer, it returns a string. You can't add strings and get an int. You need to find a way to convert your strings to integers, THEN add them.
You are using sum() while using + whould be enough.
Try again, and come back with your results. Don't forget to include error messages and what you think happened.
Assuming you are new to Python and you've read the basics you would use control flow statements to compare the sum and the guess.
Not sure if this is 100% correct, feel free to edit, but it works. Coded it according to his(assuming) beginner level. This is assuming you've studied methods, while loops, raw_input, and control flow statements. Yes there are easier ways as mentioned in the comments but i doubt he's studied map Here's the code;
def sum_digits(n):
s = 0
while n:
s += n % 10
n /= 10
return s
sum_digits(mynumber)
mynumber = int(raw_input("Enter a number, "))
userguess = int(raw_input("Guess the digit sum: "))
if sum_digits(mynumber) == userguess:
print "Correct"
else:
print "Wrong"
Credit to this answer for the method.
Digit sum method in Python
the python code is :
def digit_sum(n):
string = str(n)
total = 0
for value in string:
total += int(value)
return total
and the code doesnot use the API:
def digit_sum1(n):
total=0
m=0
while n:
m=n%10
total+=m
n=(n-m)/10
return total
Firstly you neet to use something such as int(raw_input("Please enter a number:\n")) so the input returns an integer.
Rather than using sum, you can just use + to get the sum of two integers. This will work now that your input is an integer.
Basically I would use a generator function for this
It will iterate over the string you get via raw_input('...') and create a list of the single integers
This list can then be summed up using sum
The generator would look like this:
sum([ int(num) for num in str(raw_input('Please enter a number:\n')) ])
Generators create lists (hence the list-brackets) of the elements prior to the for statement, so you could also take the double using:
[ 2 * int(num) for num in str(raw_input('Please enter a number:\n')) ]
[ int(num) for num in str(123) ] would result in [1,2,3]
but,
[ 2 * int(num) for num in str(123) ] would result in [2,4,6]

Python: Select Only Parts of an input?

Sorry...I'm kind of a programming noob. I was looking at some problem sets online and I found THIS ONE. I wrote this much:
import random
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.randint(1,53)
(f,g,h,i,j)=x=input("Your 5 Chosen Numbers:")
My problem is that I don't know how to make the program print something like "Please enter 5 numbers separated by only a comma" if more or less than five are entered. Also how would I do that if I wanted it to display a different message every other time they made that mistake?
Try this approach:
input_is_valid = False
while not input_is_valid:
comma_separated_numbers = raw_input("Please enter a list of 5 numbers,separated by commas: ")
numbers = [int(x.strip()) for x in comma_separated_numbers.split(",")]
if len(numbers) != 5:
print "Please enter exactly 5 numbers"
else:
input_is_valid = True
Looking at your link I'd say:
import random
while True:
sets = input('how many sets? ')
if type(sets) == int:
break
else:
pass
for i in range(sets):
ri = random.randint
powerball = ri(1,42)
other_numbers = sorted(ri(1,53) for i in range(5))
print 'your numbers:','\t',other_numbers,'\t','powerball:','\t',powerball
It seems that's more or less what he asks from you.
If I'm correct, you want the user to submit his series so to see if its one of the sets extracted (amirite?)
then it could be fine to do:
import random
while True:
sets = input('how many sets? ')
if type(sets) == int:
break
else:
pass
while True:
myset = raw_input('your 5 numbers:').split()
if len(myset) != 5:
print "just five numbers separated ny a space character!"
else:
myset = sorted(int(i) for i in myset)
break
for i in range(sets):
ri = random.randint
powerball = ri(1,42)
numbers = sorted(ri(1,53) for i in range(5))
print 'numbers:','\t',numbers,'\t','powerball:','\t',powerball
if numbers == myset:
print "you won!" ##or whatever the game is about
else:
print "ahah you loser"
EDIT: beware this doesn't check on random generated numbers. So it happens one number can appear more than once in the same sequence. To practice you may try avoiding this behavior, doing so with a slow pace learning some python in the way it could be:
make a set out of a copy of the list "numbers" -- use set()
if its length is less than 5, generate another number
check if the new number is in the list
if it is, then append it to the list. if its not unique yet, GOTO point 1 :-)
sort the whole thing again
there you go
happy reading the docs!
My proposition:
import random
import sys
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.randint(1,53)
bla = ["\nPlease enter 5 numbers separated by only a comma : ",
"\nPlease, I need 5 numbers separated by only a comma : ",
"\nPLEASE, 5 numbers exactly : ",
"\nOh gasp ! I said 5 numbers, no more nor less : ",
"\n! By jove, do you know what 5 is ? : ",
"\n==> I warn you, I am on the point to go off : "]
i = 0
while i<len(bla):
x = raw_input(warn + bla[i])
try:
x = map(int, x.split(','))
if len(x)==5:
break
i += 1
except:
print "\nTake care to type nothing else than numbers separated by only one comma.",
else:
sys.exit("You wanted it; I go out to drink a beer : ")
(f,g,h,i,j)=x
print f,g,h,j,i
.
Some explanation:
.
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there was no next item.
http://docs.python.org/reference/compound_stmts.html#index-801
.
.
x = map(int, x.split(','))
means that the function int() is applied to each element of the iterable which is the second argument.
Here the iterable is the list x.split(',')
Hence, x is a list of 5 integers
In Python 3, there is no more raw_input() , it has been replaced by input() that receives characters, as raw_input() in Python 2.
.
.

Categories

Resources