Python one line for loop input - python

I don't know how to get input depending on user choice. I.e. 'How many numbers you want to enter?' if answers 5, then my array has 5 spaces for 5 integers in one line separated by space.
num = []
x = int(input())
for i in range(1, x+1):
num.append(input())
Upper code works, however inputs are split by enter (next line). I.e.:
2
145
1278
I want to get:
2
145 1278
I would be grateful for some help.
EDIT:
x = int(input())
while True:
attempt = input()
try:
num = [int(val) for val in attempt.split(" ")]
if len(num)== x:
break
else:
print('Error')
except:
print('Error')
This seems to work. But why I'm getting "Memory limit exceeded" error?
EDIT:
Whichever method I use, I get the same problem.
x = int(input())
y = input()
numbers_list = y.split(" ")[:x]
array = list(map(int, numbers_list))
print(max(array)-min(array)-x+1)
or
x = int(input())
while True:
attempt = input()
try:
num = [int(val) for val in attempt.split(" ")]
if len(num)== x:
break
else:
print('Error')
except:
print('Error')
array = list(map(int, num))
print(max(array)-min(array)-x+1)
or
z = int(input())
array = list(map(int, input().split()))
print(max(array)-min(array)-z+1)

Assuming you want to input the numbers in one line, here is a possible solution. The user has to split the numbers just like you did in your example. If the input format is wrong (e.g. "21 asd 1234") or the number does not match the given length, the user has to enter the values again, until a valid input is made.
x = int(input("How many numbers you want to enter?"))
while True:
attempt = input("Input the numbers seperated with one space")
try:
num = [int(val) for val in attempt.split(" ")]
if len(num)==x:
print(num)
break
else:
print("You have to enter exactly %s numbers! Try again"%x)
except:
print("The given input does not match the format! Try again")

The easiest way to do this would be something like this:
input_list = []
x = int(input("How many numbers do you want to store? "))
for inputs in range(x):
input_number = inputs + 1
input_list.append(int(input(f"Please enter number {input_number}: ")))
print(f"Your numbers are {input_list}")
Is there a reason you want the input to be on one line only? Because you can only limit how many numbers you store (or print) that way, not how many the user inputs. The user can just keep typing.

You can use this without needing x:
num = [int(x) for x in input().split()]

If you want the numbers to be entered on one line, with just spaces, you can do the following:
x = int(input("How many numbers do you want to store? "))
y = input(f"Please enter numbers seperated by a space: ")
numbers_list = y.split(" ")[:x]
print(f"We have a list of {len(numbers_list)} numbers: {numbers_list}")
Even if someone enters more than the amount of promised numbers, it returns the promised amount.
Output:
How many numbers do you want to store? 4
Please enter numbers seperated by a space: 1 4 6 7
We have a list of 4 numbers: ['1', '4', '6', '7']

Try this.
x = int(input())
num = [] # List declared here
while True:
try:
# attempt moved inside while
# in case input is in next line, the next line
# will be read in next iteration of loop.
attempt = input()
# get values in current line
temp = [int(val) for val in attempt.split(" ")]
num = num + temp
if len(num) == x:
break
except:
print('Error2')
Maybe the bot was passing integers with newline instead of spaces, in which case the while loop will never terminate (assuming your bot continuously sends data) because every time, it will just re-write num.
Note - this code will work for both space as well as newline separated inputs

Related

How can I manage to make this input only integers answer and rejected string. This include .split()

Good day everyone, I would like to ask about this problem which I need to make the outcome only Integers and not string
If I put string in the Input.. it will make error and If i place number it will print the number
example:
num = int(input("Enter number only: ")).split(",")
print(num)
Assuming the user gives a comma-delimited input 7,42,foo,16, you can use a try block to only add numbers, and pass over strings:
nums = []
user_input = input("Enter a series of numbers separated by commas: ")
input_fields = user_input.split(",")
for field in input_fields:
try:
num.append(int(field))
except ValueError:
pass
for num in nums:
print(str(num))
I would do this:
user_input = input("Enter a series of numbers separated by commas: ")
input_fields = user_input.split(",")
int_list = []
for i in input_fields:
int_list.append(int(i)) # you may want to check if int() works.

How I can get number from user that includes only 5,6?

How I can get number from user that only includes 5 and 6?
I try for loop but it's not work,also try convert the input to string,also no work.how to do?
Number = int(input('enter num')
for x in number:
if 4<x<7:
print('ok)
else:
print ('no')
In python 3, input returns a string. You can easily filter the numbers you want with
val = int(''.join(c for c in input('enter num: ') if c in '56'))
Not sure, why do you need a loop there and why you use x. Try this:
number = int(input('enter num')
if number in [5, 6]:
print('ok)
else:
print ('no')
While I'm sure the others might work, this is yet another way to check for a specific number.
#Gets the number from the user
Number = int(input("Enter Num"))
#checks to see if the number is either 5 or 6
if (Number == 5 or Number == 6):
print("ok") #if it is, it prints ok
else:
print("No") #if it isn't, it prints no
It is probably easier if you check for digits 5 and 6 before converting to int.
Number_str = input('enter num')
for x in Number_str:
if not ord('4')<ord(x)<ord('7'):
print ('no')
break
else:
Number = int(Number_str)
print('ok')

How to accept user input of a sequence?

I'm new to python and I'm trying to help out a friend with her code. The code receives input from a user until the input is 0, using a while loop. I'm not used to the python syntax, so I'm a little confused as to how to receive user input. I don't know what I'm doing wrong. Here's my code:
sum = 0
number = input()
while number != 0:
number = input()
sum += number
if number == 0:
break
In your example, both while number != 0: and if number == 0: break are controlling when to exit the loop. To avoid repeating yourself, you can just replace the first condition with while True and only keep the break.
Also, you're adding, so it is a good idea to turn the read input (which is a character string) into a number with something like int(input()).
Finally, using a variable name like sum is a bad idea, since this 'shadows' the built-in name sum.
Taking all that together, here's an alternative:
total = 0
while True:
number = int(input())
total += number
if number == 0:
break
print(total)
No need last if, and also make inputs int typed:
sum = 0
number = int(input())
while number != 0:
number = int(input())
sum += number
You can actually do:
number=1
while number!=0:
number = int(input())
# Declare list for all inputs
input_list = []
# start the loop
while True:
# prompt user input
user_input = int(input("Input an element: "))
# print user input
print("Your current input is: ", user_input)
# if user input not equal to 0
if user_input != 0:
# append user input into the list
input_list.append(user_input)
# else stop the loop
else:
break
# sum up all the inputs in the list and print the result out
input_sum = sum(input_list)
print ("The sum is: ", input_sum)
Or
If you don't want to use list.
input_list = 0
while True:
user_input = int(input("Input an element: "))
print("Your current input is: ", user_input)
if user_input != 0:
input_list += user_input
else:
break
print ("The sum is: ", input_list)
Note:
raw_input('Text here') # Python 2.x
input('Text here') # Python 3.x

How do I let users input any number of input values in Python? [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 4 years ago.
For example, if you wanted to accept say 2 input values it would be something like,
x = 0
y = 0
line = input()
x, y = line.split(" ")
x = int(x)
y = int(y)
print(x+y)
Doing it this way however, would mean that I must have 2 inputs at all times, that is separated by a white space.
How do I make it so that a user could choose to enter any number of inputs, such as nothing (e.g. which leads to some message,asking them to try again), or 1 input value and have an action performed on it (e.g. simply printing it), or 2 (e.g. adding the 2 values together) or more.
You can set a parameter how many values there will be and loop the input and put them into a map - or you make it simple 2 liner:
numbers = input("Input values (space separator): ")
xValueMap = list(map(int, numbers.split()))
this will create a map of INT values - separated by space.
You may want to use a for loop to repeatedly get input from the user like so:
num_times = int(input("How many numbers do you want to enter? "))
numbers = list() #Store all the numbers (just in case you want to use them later)
for i in range(num_times):
temp_num = int(input("Enter number " + str(i) + ": "))
numbers.append(temp_num)
Then, later on, you can use an if/elif/else chain to do different actions to the numbers based on the length of the list (found using the len() function).
For example:
if len(numbers) == 0:
print("Try again") #Or whatever you want
elif len(numbers) == 1:
print(numbers[0])
else:
print(sum(numbers))
Try something like this. You will provide how many numbers you want to ask the user to input those many numbers.
def get_input_count():
count_of_inputs = input("What is the number you want to count? ")
if int(count_of_inputs.strip()) == 0:
print('You cannot have 0 as input. Please provide a non zero input.')
get_input_count()
else:
get_input_and_count(int(count_of_inputs.strip()))
def get_input_and_count(count):
total_sum = 0
for i in range(1,count+1):
input_number = input("Enter number - %s :"%i)
total_sum += int(input_number.strip())
print('Final Sum is : %s'%total_sum)
get_input_count()

Stuck with this

I am trying to write a program that will add together a series of numbers that the user inputs until the user types 0 which will then display the total of all the inputted numbers. this is what i have got and im struggling to fix it
print ("Keep inputting numbers above 0 and each one will be added together consecutively. enter a and the total will be displayed on the screen. have fun")
number = input("Input a number")
sum1 = 0
while number >= 1:
sum1 = sum1 + number
if number <= 0:
print (sum1)
Here is a more robust way to input the number. It check if it can be added. Moreover I added the positive and negative number.
# -*-coding:Utf-8 -*
print ("Keep inputting numbers different than 0 and each one will be added together consecutively.")
print ("Enter a and the total will be displayed on the screen. Have fun.")
sum = 0
x = ""
while type(x) == str:
try:
x = int(input("Value : "))
if x == 0:
break
sum += x
x = ""
except:
x = ""
print ("Please enter a number !")
print ("Result : ", sum)
If you're using Python 3, you will need to say number = int(input("Input a number")) since input returns a string. If you're using Python 2, input will work for numbers but has other problems, and the best practice is to say int(raw_input(...)). See How can I read inputs as integers? for details.
Since you want the user to repeatedly enter a number, you also need an input inside the while loop. Right now it only runs once.

Categories