I'm working on a homework assignment (honestly been working for a while now) where we take input from the user, slice the string, and store the new strings in two different variables. The second part of the split string is supposed to be a number and I'm attempting to write an if statement to check if it is indeed a number. The problem is it's not because I split a string, so it's defined as a str. I know I could redefine the variable to an int() but that would produce an error if they weren't to enter an integer. Sorry if this isn't clear, this is my first question! (I can also post a screenshot of the instructions if that would be more helpful, I just don't know if that's encouraged on here.)
data_title = input("Enter a title for the data: ")
print("You entered: ", data_title)
column1 = input("Enter the column 1 header: ")
print("You entered: ", column1)
column2 = input("Enter the column 2 header: ")
print("You entered: ", column2)
data_point = input("Enter a data point (-1 to stop input): ")
while data_point != -1:
if ',' in data_point:
if data_point.count(',') < 2:
data_split = data_point.split(",")
data_stg = data_split[0]
data_int = data_split[1]
if data_split[1].isdigit() is True:
print("Data string: ", data_stg)
print("Data integer: ", data_int)
data_point = input("Enter a data point (-1 to stop input): ")
else:
print("Error: Comma not followed by an integer.")
data_point = input("Enter a data point (-1 to stop input): ")
else:
print("Error: Too many commas in input.")
data_point = input("Enter a data point (-1 to stop input): ")
else:
print("Error: No comma in string.")
data_point = input("Enter a data point (-1 to stop input): ")
The problem is in the in the 3rd if loop nested in the while loop. I have to make sure their input has an integer after the comma.
if data_split[1].isdigit() is True:
print("Data string: ", data_stg)
print("Data integer: ", data_int)
data_point = input("Enter a data point (-1 to stop input): ")
else:
print("Error: Comma not followed by an integer.")
data_point = input("Enter a data point (-1 to stop input): ")
As you give me the captured image, I couldn't see the full requests.
So I made an example for you.
while True:
a = input('please give me your data :')
if ',' not in a:
try:
if int(a) == -1: break
except:
pass
print( 'please give me the seperated inputs wiht ","')
else:
b, c = a.split(',')
try:
c = int(c)
except:
print( 'please give me int !!')
else:
print( b, c)
I believe this code would help you see what python is.
Related
If user entered anything other than an integer it should be ignored, whereas, if it were to be an integer it should be added to the lst (list)
the function should display the list of integers, ignoring anything that wasn't an integer and display the max and min number.
lst = []
n = int(input("Enter Integers: "))
for index in range(min(n), max(n)):
if index == ' ':
return
for i in range(min(n),max(n)):
elements = int(input())
lst.append(elements)
print(lst)
print(len(lst))
for num in lst:
if num % 2 == 0:
print(num, end= ' ')
I have a function here that prompts users to enter a list of integers, if SPACE is inputted: it should END the input.
I'm quite new at python and not sure how to go about this code.
The expression
input("Enter Integers: ")
evaluates to a string. Since you want to read strings until a space is inserted, you need a infinite loop:
numbers = []
while True:
value = input("Enter an integer: ")
If the user provides a space, stop reading numbers:
numbers = []
while True:
value = input("Enter an integer: ")
if value == ' ':
# Exit the loop
break
If you want to convert it to an integer, use the int function and append it to numbers:
numbers = []
while True:
value = input("Enter an integer: ")
if value == ' ':
break
numbers.append(int(value))
You can also add a validation, if the user provides a value that isn't a number:
numbers = []
while True:
value = input("Enter an integer: ")
if value == ' ':
break
try:
number = int(value)
except ValueError:
print('The value is not a number!')
# Continue looping
continue
numbers.append(number)
Your code there is somewhat misleading and adds confusion to the question. My solution below is based off the question before the code.
lst = []
print("Enter Integers:")
while True:
n = input()
try:
# Try converting to an int, if can't ignore it
lst.append(int(n))
except ValueError:
pass
# If space input, break the loop
if n == ' ':
break
print("Integer list: ")
print(lst)
if len(lst) > 0:
print("Min: " + str(min(lst)))
print("Max: " + str(max(lst)))
I am trying to create a program where the user has to input 3 numbers to be displayed by the range function. However, I am trying to assign a numerical value to when an empty input is given to one of the variables. Here is part of my code. For this section of the code, I want to assign a value of zero when the user enters empty input. However, when I try running this section of the program, I get this error: line 5, in
number = int(input_value)
ValueError: invalid literal for int() with base 10: ''
Any suggestions are greatly appreciated!
while True:
input_value = input("Type a number: ")
number = int(input_value)
if input_value.isalpha():
print("Not a number")
break
else:
if input_value is None:
number = int(0)
break
else:
if int(number):
break
print(number)
When a user input is empty, input_value will be "", which python cannot convert to an integer. number = int("") will throw an error.
What you can do is check if the input is equal "" and if it is, set number to 0, else convert it using int().
Better yet, I would wrap number = int(input_value) in a try catch statement:
while True:
input_value = input("Type a number: ")
try:
number = int(input_value)
except:
print("invalid input")
break
So to break the loop, you'd enter something thats not a number. In this case, you'd only be storing the last input value into number, so it's up to you how you want to keep track of all the inputs (probably using a list).
just a thought:
while True:
input_value = input("Type a number: ")
if input_value:
try:
number = int(input_value)
break
except:
continue
print(number)
the code below works as expected. I am trying to ensure that all data entered is integers. Non integers should get the error meessage. My while loop works for the first input where the user is asked what # of numbers to enter.
However it does not catch errors for the subsequent inputs.
while True:
try:
userIn = int(input("Input no of numbers :"))
userNums = []
uNums = []
print("Type " + str(userIn) + " numbers in list :")
for index in range(int(userIn)):
userNums.append(input("entry" + str(index+1) +" = "))
for number in userNums:
if number not in uNums:
uNums.append(number)
print("unique number counted")
for uNum in uNums:
print(str(uNum) + " count is " + str(userNums.count(uNum)) + "times")
break
except:
print("Error. only ints allowed")
You don’t actually try and convert to integers at any point. Below just saves the strings.
for index in range(int(userIn)):
userNums.append(input("entry" + str(index+1) +" = "))
And, by the way, you can get rid of the following:
for number in userNums:
if number not in uNums:
uNums.append(number)
If you made userNum a set - userNum = set() - which can only have unique values in it.
Your main mistake is a forgotten int():
for index in range(userIn):
num = int(input("entry" + str(index+1) +" = "))
userNums.append(num)
However, still the whole program has to start again in case of a wrong input, therefore I recommend a try&except whenever in need. You also tend to:
1.convert variables when not necessary
2.use +and str(), which might be not the best habit
This code should be straight forward and the customised INPUT-function might be useful in the future:)
def INPUT(InputText):
"""customized input handling"""
while True:
try:
return int(input(InputText))
except ValueError:
print ("Error: Only integers accepted")
#note: you could wrap the code below in a function
# and call the function afterwards if you want:
userIn = INPUT("Input no of numbers :")
userNums = []
uNums = []
print("Type {} numbers in list :".format(userIn))
for index in range(userIn):
num = INPUT("entry {} = ".format(index+1))
userNums.append(num)
for number in userNums:
if number not in uNums:
uNums.append(number)
print("unique number counted")
for uNum in uNums:
print("{} count is {} times".format(uNum,userNums.count(uNum)))
The below solution should work. The main changes:
(1) Added explicit ValueError checks, as this is good practice.
(2) Added explicit continue, as this is also good practice.
(3) Incorporated else clauses to create try / except / else structure.
(4) Added try / except to loop of number input code.
(5) Use set to get unique items of list.
while True:
try:
userIn = int(input("Input no of numbers :"))
except ValueError:
print("Error: only ints allowed")
continue
else:
userNums = []
print("Type " + str(userIn) + " numbers in list :")
for index in range(int(userIn)):
while True:
try:
x = int(input("entry" + str(index+1) +" = "))
userNums.append(x)
break
except ValueError:
print("Error: only ints allowed")
continue
uNums = set(userNums)
print("Unique numbers counted:")
for uNum in uNums:
print(str(uNum) + " count is " + str(userNums.count(uNum)) + " times")
break
You’re not casting the subsequent inputs to int().
You need something like
userNums.append(int(input("entry" + str(index+1) +" = ")))
Question= Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers.
So basically I have to write a program as stated above.
EDIT: Im done with this question but would like to edit a try and except clause that would show an error if I were to enter a string instead of an integer. when I run the code the error message comes out but the string still gets added to the numberlist :(
def findlargest():
largest= None
for value in numberlist:
if largest is None:
largest= value
elif value> largest:
largest= value
print "The largest value is", largest
def findsmallest():
smallest=None
for value in numberlist:
if smallest is None:
smallest= value
elif value<smallest:
smallest= value
print "The smallest value is: ", smallest
numberlist=[]
while True:
newdata= raw_input("Enter your number: ")
if newdata == "done":
break
numberlist.append(newdata)
if newdata != "":
try:
newdata=int(newdata)
numberlist.append(newdata)
except ValueError:
print "Invalid input. Please enter a number"
findlargest()
findsmallest()
Well, how about you take each user input, and...add it to a list?
Wow, I know, cutting edge.
Then, I don't know, maybe do some operations on that list that find the min and max?
Here's an example. If this is homework, you're better off rewriting for yourself. And if you're using Python 2.x, as your updated question indicates, you're going to have to modify what I'm giving you either way, because it is for Python 3
numberlist=[] #where we're storing our data
while True:
print("Please enter a number, or 'Done'")
newdata=input()
if newdata == 'done' or newdata == 'Done' or newdata == 'DONE': #only gave options here because I typed the wrong case in while testing
break #breaks the loop when done is entered
numberlist.append(newdata) #adds the number entered to our list
print("List of numbers: "+str(numberlist))
print("Min: "+min(numberlist))
print("Max: "+max(numberlist))
Here is a solution that works:
max = None
min = None
receiveInput = False
while True:
input = raw_input("Enter your number: ")
if input == "done":
if not receiveInput:
print ("No numbers entered by user!")
else:
print ("Max: " + max)
print ("Min: " + min)
break
elif (max is None and min is None):
receiveInput = True
max, min = input, input
elif input > max:
max = input
elif input < min:
min = input
list_value = []
while True:
user_input = raw_input()
if user_input == "done":
if list_value:
sorted_array = sorted(list_value)
print "successfully done \n largest number %s and smallest number %s" % (sorted_array[0], sorted_array[-1])
break
if user_input != '':
try:
user_value = int(user_input)
list_value.append(user_value)
except ValueError:
print " Invalid input"
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
I'm quite new to programming. I was trying to figure out how to check if a user input (which get stores as a string) is an integer and does not contain letters. I checked some stuff on the forum and in the end came up with this:
while 1:
#Set variables
age=input("Enter age: ")
correctvalue=1
#Check if user input COULD be changed to an integer. If not, changed variable to 0
try:
variable = int(age)
except ValueError:
correctvalue=0
print("thats no age!")
#If value left at 1, prints age and breaks out of loop.
#If changed, gives instructions to user and repeats loop.
if correctvalue == 1:
age=int(age)
print ("Your age is: " + str(age))
break
else:
print ("Please enter only numbers and without decimal point")
Now, this works as shown and does what I want (ask the persons age untill they enter an integer), however is rather long for such a simple thing. I've tried to find one but I get too much data that I don't understand yet.
Is there a simple shorter way or even a simple function for this to be done?
You can make this a little shorter by removing the unnecessary correctvalue variable and breaking or continue-ing as necessary.
while True:
age=input("Enter age: ")
try:
age = int(age)
except ValueError:
print("thats no age!")
print ("Please enter only numbers and without decimal point")
else:
break
print ("Your age is: " + str(age))
Use isdigit()
"34".isdigit()
>>> "34".isdigit()
True
>>> "3.4".isdigit()
False
>>>
So something like this:
while True:
#Set variables
age=input("Enter age: ")
#Check
if not age.isdigit():
print("thats no age!")
continue
print("Your age is: %s" % age)
age = int(age)
break
This works for nonnegative integers (i.e., without a sign marker):
variable = ''
while True:
variable = input("Age: ")
if variable.isdigit():
break
else:
print("That's not an age!")
variable = int(variable)
The idea is that you loop continuously until the user inputs a string that contains only digits (that's what isdigit does).
Your code can be made a bit shorter like this. I was going to suggest changing your correctvalue variable from an integer 1 or 0 to a boolean True or False but it is redundant anyway. continue can be used to repeat the loop as necessary.
while True:
age = input("Enter age: ")
try:
age = int(age)
except ValueError:
print("That's no age!")
print("Please enter only numbers and without decimal point")
continue
print ("Your age is: " + str(age))
break