I cannot tweak this for it to only respond to a value between 1 and 100. I know its somthing simple, but cannot find anything through searching that works.
while True:
Mynumber = raw_input('Enter number of random points')
if Mynumber == '0 < 100':
print 'number choosen'
Mynumber = int(Mynumber)
break
if 1 <= my_number <= 100:
Or, since you are grabbing from raw_input and have to convert to int from unknown string first:
try:
my_number = int(raw_number)
except ValueError:
print "%s not an integer value." % raw_number
else:
if 1 <= raw_number <= 100:
Though on further analysis, it looks like you are trying to do:
base_prompt = 'Enter number of random points'
user_input = raw_input(base_prompt)
while True:
try:
input_number = int(user_input)
except ValueError:
user_input = raw_input('%s not an interger\n%s' % (user_input, base_prompt))
else:
if 1 <= input_number <= 100:
break
else:
user_input = raw_input('%d out of range (1 to 100)\n%s' % (input_number, base_prompt))
If you're on Python 3.x, the following also works:
if int(my_number) in range(1, 101):
# ...
The caveat is that the end point of a range is exclusive, so it probably reads less intuitively than chained operators.
Related
Basic task of making code that can find the sum & average of 10 numbers from the user.
My current situation so far:
Sum = 0
print("Please Enter 10 Numbers\n")
for i in range (1,11):
num = int(input("Number %d =" %i))
sum = Sum + num
avg = Sum / 10
However, I want to make it so that if the user inputs an answer such as "Number 2 = 1sd" it doesn't stop the code immediately. Instead I'm looking for it to respond as "Invalid input. Try again" and then it restarts from the failed input.
e.g.
"Number 2 = 1sd"
"Invalid input. Try again."
"Number 2 = ..."
How would I achieve that?
You can output an error message and prompt for re-entry of the ith number by prompting in a loop which outputs an error message and reprompts on user input error. This can be done by handling the ValueError exception that is raised when the input to the int() function is an invalid integer object string initializer such as as "1sd". That can be done by catching that exception, outputting Invalid input. Try again. and continuing when that occurs.
One possible resulting code that may satisfy your requirements is:
Sum = 0
print("Please Enter 10 Numbers\n")
for i in range (1,11):
num = None
while num is None:
try:
num = int(input("Number %d =" %i))
except ValueError:
print('Invalid input. Try again.')
sum = Sum + num
avg = Sum / 10
This one is working for me.
sum_result = 0
print("Please Enter 10 Numbers\n")
for i in range (1,11):
try:
num = int(input("Number %d =" %i))
sum_result = sum_result + num
except Exception:
print("Please try again")
num = int(input("Number %d =" %i))
sum_result = sum_result + num
avg_result = sum_result / 10
print(sum_result)
print(avg_result)
Suggestions:
Check the conventions for name variables in python, you are using builtin functions, which can be an issue in your code.
When you are dealing with user inputs, usually you need error handling, so try, except, else, finally, are the way to go.
When you have a code similar to this use, you normally name a function to do these tasks.
You can do:
while True:
try:
num = int(input('Enter an integer: '))
break
except Exception:
print('Invalid input')
#now num is an integer and we can proceed
you can check the input, then continue or return an error, something like this:
sum = 0
print('Please Enter 100 Numbers:\n')
for i in range(1, 11):
num = input('Number %d' % i)
while not num.isdigit():
print('Invalid input. Try again.')
num = input('Number %d' % i)
sum += int(num)
avg = sum / 10
print('Average is %d' % avg)
from statistics import mean
i=0
number_list = []
while i <= 9:
num = input("Please Enter 10 Numbers\n")
if num.isdigit() ==False:
print('Invalid input. Try again.')
num
else:
number_list.append(int(num))
i +=1
print(sum(number_list))
print(mean(number_list))
If your data is not too much, I think put them in a list is better. Because you can easier change program to calculate others if you want.
nums = [] # a list only store valid numbers
while len(nums) < 10:
input_n = input("Number %d = " % (len(nums) + 1))
if input_n.isdigit():
n = int(input_n)
nums.append(n)
else:
print("Invalid input. Try again.")
# average is more commonly known as a float type. so I use %f.
print("Average = %f" % (sum(nums) / len(nums)))
I have an exercise:
Write code that asks the user for integers, stops loop when 0 is given.
Lastly, adds all the numbers given and prints them.
So far I manage this:
a = None
b = 0
while a != 0:
a = int(input("Enter a number: "))
b = b + a
print("The total sum of the numbers are {}".format(b))
However, the code needs to check the input and give a message incase it is not an integer.
Found that out while searching online but for the life of me I cannot combine the two tasks.
while True:
inp = input("Input integer: ")
try:
num = int(inp)
except ValueError:
print('was not an integer')
continue
else:
total_sum = total_sum + num
print(total_sum)
break
I suspect you need an if somewhere but cannot work it out.
Based on your attempt, you can merge these two tasks like:
a = None
b = 0
while a != 0:
a = input("Enter a number: ")
try:
a = int(a)
except ValueError:
print('was not an integer')
continue
else:
b = b + a
print("The total sum of the numbers are {}".format(b))
If you want to use an If-Statement, you don't need the else: If the number is not 0 it will just start again until it's 0 sometime.
total_sum = 0
while True:
inp = input("Input integer: ")
try:
num = int(inp)
except ValueError:
print('was not an integer')
continue
total_sum = total_sum + num
if num == 0:
print(total_sum)
break
Since input's return is a string one can use isnumeric no see if the given value is a number or not.
If so, one can convert the string to float and check if the given float is integer using, is_integer.
a = None
b = 0
while a != 0:
a = input("Enter a number: ")
if a.isnumeric():
a = float(a)
if a.is_integer():
b += a
else:
print("Number is not an integer")
else:
print("Given value is not a number")
print("The total sum of the numbers are {}".format(b))
We have to find out the average of a list of numbers entered through keyboard
n=0
a=''
while n>=0:
a=input("Enter number: ")
n+=1
if int(a)==0:
break
print(sum(int(a.list()))/int(n))
You are not saving the numbers entered. Try :
n = []
while True:
a=input("Enter number: ")
try: #Checks if entered data is an int
a = int(a)
except:
print('Entered data not an int')
continue
if a == 0:
break
n.append(a)
print(sum(n)/len(n))
Where the list n saves the entered digits as a number
You need to have an actual list where you append the entered values:
lst = []
while True:
a = int(input("Enter number: "))
if a == 0:
break
else:
lst.append(a)
print(sum(lst) / len(lst))
This approach still has not (yet) any error management (a user enters float numbers or any nonsense or zero at the first run, etc.). You'd need to implement this as well.
a needs to be list of objects to use sum, in your case its not. That is why a.list doens't work. In your case you need to take inputs as int (Can be done like: a = int(input("Enter a number")); ) and then take the integer user inputs and append to a list (lets say its name is "ListName")(listName.append(a)), Then you can do this to calculate the average:
average = sum(listName) / len(listName);
def calc_avg():
count = 0
sum = 0
while True:
try:
new = int(input("Enter a number: "))
if new < 0:
print(f'average: {sum/count}')
return
sum += new
count += 1
print(f'sum: {sum}, numbers given: {count}')
except ValueError:
print("That was not a number")
calc_avg()
You can loop, listen to input and update both s (sum) and c (count) variables:
s, c = 0, 0
while c >= 0:
a = int(input("Enter number: "))
if a == 0:
break
else:
s += a
c += 1
avg = s/c
print(avg)
the function i am working on is supposed to tell a user whether a number they have given is a perfect number or not (i.e. is equal to half the sum of its factors). if a user gives the number 8, the output should look like this:
8 is not a perfect number
but i can't figure out what to put in the return statement to make the int, which changes depending on the user input, print out with the string. the code so far looks like this:
#the code is within another larger function which is the reason for the elif
elif(message == 2):
num1 = int(input("""Please enter a positive integer :"""))
while(num1 <= 0):
print("Number not acceptable")
num1 = int(input("""Please enter a positive integer :"""))
thisNum = isPerfect(num1)
if(thisNum == True):
return num1, is a perfect number
elif(thisNum == False):
return num1 is not a perfect number
def isPerfect(num1):
sumOfDivisors = 0
i = 0
listOfDivisors = getFactors(num1)
for i in range(0, len(listOfDivisors) - 1):
sumOfDivisors = sumOfDivisors + listOfDivisors[i]
i += 1
if(sumOfDivisors / 2 == num1):
return True
else:
return False
if i were to do return(num1, "is not a perfect number") it would come out like
(8, 'is not a perfect number')
return "%d is not a perfect number" % number
You can do this with string formating using %s. Anyway there is some other ways as describes String Formating Operators
convert the integer to a string and concatenate the rest of your statement:
return str(num1) + ' is not a perfect number'
You can use the .format() mini language, and at the same time, simplify your code:
elif(message == 2):
num1 = int(input("""Please enter a positive integer :"""))
while(num1 <= 0):
print("Number not acceptable")
num1 = int(input("""Please enter a positive integer :"""))
if isPerfect(num1):
return '{} is a perfect number'.format(num1)
else:
return '{} is not a perfect number'.format(num1)
Also in your other method, simply return the result of the comparison:
def isPerfect(num1):
sumOfDivisors = 0
listOfDivisors = getFactors(num1)
for i listOfDivisors:
sumOfDivisors += i
#if(sumOfDivisors / 2 == num1):
# return True
#else:
# return False
return sumOfDivisors / 2 == num1
Also, I would suggest having a read of PEP-8, which is the style guide for Python.
I am trying to get the user input 2 numbers which are split into a list of 2 integers, but unfortunately I can't seem to get them to turn into integers, but I am also unsure of my checks and if it is going to terminate properly and return what I need.
def getlohiint():
lohilist = []
lohi = raw_input("Enter min and max number of points to use(e.g., 2 1000): ")
lohilist = lohi.split()
for x in lohilist:
int(x)
if lohilist[0]<=2 and lohilist[1]<=1000 and lohilist[0]<lohilist[1]:
break
else:
prompt = "%d is not in the range of 2 to 1000; "
prompt1 = "must be at least 2"
prompt2 = "must be no higher than 1000"
if lohilist[0]<2:
print prompt + prompt1
elif lohilist[1]>1000:
print prompt + prompt2
else:
print prompt + prompt1 + prompt2
lohi
high = lohilist[1]
low = lohilist[0]
return(low, high)
You never assign the result of int(x) to anything. It's easiest achieved with a list comprehension:
lohilist = [int(x) for x in lohi.split()]
Note that you can assign to multiple targets at once:
low, high = [int(x) for x in lohi.split()]
would convert everything in lohi to integers and assign to the two variables in one go.
You may want to test for exceptions too here:
def getlohiint():
while True:
lohi = raw_input("Enter min and max number of points to use(e.g., 2 1000): ")
try:
low, high = [int(x) for x in lohi.split()]
except ValueError:
# either not integers or not exactly 2 numbers entered.
print "You must enter exactly 2 numbers here"
continue
if low <= 2 and high <= 1000 and low < high:
# valid input, return
return low, high
if low > 2:
print 'The minimum must be 2 or lower'
if high > 1000:
print 'The maximum must be 1000 or lower'
if low >= high:
print 'The maximum must be greater than the minimum'
int(x) returns an integer value, it does not modify the value of x.
You probably want something like:
def getlohiint():
lohilist = []
lohi = raw_input("Enter min and max number of points to use(e.g., 2 1000): ")
lohilist = lohi.split()
lohilist = [int(x) for x in lohilist]
I would abstract this out a bit: make a function that parses a list of integers from input, then another function which takes a list of integers and tests that they fit your criteria:
import sys
# version compatibility shim
if sys.hexversion < 0x3000000:
# Python 2.x
inp = raw_input
else:
# Python 3.x
inp = input
def get_ints(prompt, delimiter=None):
while True:
try:
return [int(i) for i in inp(prompt).split(delimiter)]
except ValueError:
pass
def get_lo_hi_ints(prompt, min_=None, max_=None):
while True:
try:
lo, hi = get_ints(prompt)
if lo >= hi:
print("First value must be < second value")
elif (min_ is not None and lo < min_):
print("Low value must be >= {}".format(min_))
elif (max_ is not None and hi > max_):
print("High value must be <= {}".format(max_))
else:
return lo, hi
except ValueError:
print("Please enter 2 values!")
then you can use it like
min_points, max_points = get_lo_hi_ints("Enter min and max number of points to use(e.g., 2 1000): ", 2, 1000)