This question already has answers here:
How can I read inputs as numbers?
(10 answers)
How do I parse a string to a float or int?
(32 answers)
Closed last year.
I am creating a calculator and I place the numbers taken by the user into a list.I had to make the input a string since I place the input in a while loop and gave it a string to break the loop (q).
while True:
numbers = input('Enter the numbers for calculation: ')
if numbers == 'q':
break
operations.append(numbers)
I want to turn the list where the user's input is kept into a float so that I can perform operations on them.
This is the list: operations = []
I'm still learning Python, so don't judge too harshly.
operations = []
while:
number = input('Enter number\n')
if number == 'q':
print('QUIT')
break
else:
number = float(int(number))
operations.append(number)
print(operations)
I just couldn't make a check for the input of any other letters, except for "q"
Related
This question already has answers here:
"pythonic" method to parse a string of comma-separated integers into a list of integers?
(3 answers)
Closed 1 year ago.
Hi I am creating a function to compute the mean from a list of integers inputed by the user. I am getting an error:
ValueError: invalid literal for int() with base 10:
Here is my code:
def calcmean (mylist):
listsum= 0
for index in mylist:
listsum = listsum + index
mean= listsum / len(mylist)
return mean
userinput= [int(input("Enter list separated by commas:"))]
print (mean (userinput))
This should work:
userinput = [int(x) for x in input("Enter list separated by commas:\n").split(', ')]
How do you make sure the user will type that numbers totally correct as you expected? What happens if the user types two/three/four/... consecutive commas like 1,2,3,,4,,,,5? It should be handled much more than that. To be clear, you should divide your program to 3 phases, including:
Input
Process the input
Calculate mean.
Following gives you an example:
Input
userinput = input("Please type number separated by commas")
Process the input
# split numbers to items by commas.
num_array = userinput.split(",")
# chose items that are valid numbers
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
num_array = [int(item) for item in num_array if is_number(item)]
Calculate mean
As you done in your code
print(mean(num_array))
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
Hey I'm trying to create an infinite list in python that takes user input in till 0 is entered, I don't really know if this is the right way to do so, here's what I did:
`n = input("Enter a list element separated by space ")
while n == 0:
break
else:
list = n.split()
print(list)`
Thank you!
This code will do what you originally described:
Numbers = []
while True:
number = int(input("Please enter a number:"))
if number == 0:
break
Numbers.append(number)
print(Numbers)
try this
l = []
while 1:
n = input("Enter a list element seperated by a space")
for x in n.split():
if x == 0:
break
l.append(int(x))
This question already has answers here:
for or while loop to do something n times [duplicate]
(4 answers)
Closed 3 years ago.
I am relatively new to programming and especially to Python. I am asked to create a for loop which prints 10 numbers given by the user. I know how to take input and how to create a for loop. What bothers me, is the fact that with my program I rely on the user to insert 10 numbers. How can I make the program control how many numbers are inserted? Here is what I tried:
x = input('Enter 10 numbers: ')
for i in x:
print(i)
You need to
ask 10 times : make a loop of size 10
ask user input : use the input function
for i in range(10):
choice = input(f'Please enter the {i+1}th value :')
If you want to keep them after, use a list
choices = []
for i in range(10):
choices.append(input(f'Please enter the {i + 1}th value :'))
# Or with list comprehension
choices = [input(f'Please enter the {i + 1}th value :') for i in range(10)]
What if input is row that contains word (numbers) separated by spaces? I offer you to check if there are 10 words and that they are numbers for sure.
import re
def isnumber(text):
# returns if text is number ()
return re.match(re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"), text)
your_text = input() #your input
splitted_text = your_text.split(' ') #text splitted into items
# raising exception if there are not 10 numbers:
if len(splitted_text) != 10:
raise ValueError('you inputted {0} numbers; 10 is expected'.format(len(splitted_text)))
# raising exception if there are any words that are not numbers
for word in splitted_text:
if not(isnumber(word)):
raise ValueError(word + 'is not a number')
# finally, printing all the numbers
for word in splitted_text:
print(word)
I borrowed number checking from this answer
This question already has answers here:
Two values from one input in python? [duplicate]
(19 answers)
Closed 2 years ago.
I want to use one line to get multiple inputs, and if the user only gives one input, the algorithm would decide whether the input is a negative number. If it is, then the algorithm stops. Otherwise, the algorithm loops to get a correct input.
My code:
integer, string = input("Enter an integer and a word: ")
When I try the code, Python returns
ValueError: not enough values to unpack (expected 2, got 1)
I tried "try" and "except", but I couldn't get the "integer" input. How can I fix that?
In order to get two inputs at a time, you can use split(). Just like the following example :
x = 0
while int(x)>= 0 :
try :
x, y = input("Enter a two value: ").split()
except ValueError:
print("You missed one")
print("This is x : ", x)
print("This is y : ", y)
I believe the implementation below does what you want.
The program exits only if the user provides a single input which is a negative number of if the user provides one integer followed by a non-numeric string.
userinput = []
while True:
userinput = input("Enter an integer and a word: ").split()
# exit the program if the only input is a negative number
if len(userinput) == 1:
try:
if int(userinput[0]) < 0:
break
except:
pass
# exit the program if a correct input was provided (integer followed by a non-numeric string)
elif len(userinput) == 2:
if userinput[0].isnumeric() and (not userinput[1].isnumeric()):
break
Demo: https://repl.it/#glhr/55341028
This question already has answers here:
Sum the digits of a number
(11 answers)
Closed 5 years ago.
def main():
number = input("enter large number:")
number = int(number)
result = 0
for i in number:
result = result + i
print("result is:",result)
is giving me an error with the int,I'm not sure how to fix it.
I need the user to type in a large number like 2541 and it needs to be separated like 2,5,4,1 and added to give me the result of 12 is not supposed to be just 4 number but needs to be a large number.
You can't iterate over a number, so for i in number will fail.
What you want is to start with the input as a string, iterate over that, then convert to an int when adding it to result:
number = str(input("enter large number:"))
result = 0
for i in number:
result = result + int(i)
print("result is:",result)