I'm new to programming and currently learning Python. I would like to write a program that :
request user to input a non-negative even integer.
request the user to input again if not fulfil non-negative even integer.
N = input("Please enter an non-negative even integer: ") #request user to input
And the criteria checking code is:
N == int(N) #it is integer
N % 2 == 0 #it is even number
N >=0 # it is non-negative number
But how should I combine them?
since the question is tagged python-2.7, use raw_input instead of input (which is used in python-3.x).
Use str.isdigit to check if a string is an positive integer, int(N) would raise ValueError if the input couldn't be converted into integer.
Use a while loop to request user input if condition not fulfilled, break when you get a valid input.
e.g.,
while True:
N = raw_input("Please enter an non-negative even integer: ") #request user to input
if N.isdigit(): # accepts a string of positive integer, filter out floats, negative ints
N = int(N)
if N % 2 == 0: #no need to test N>=0 here
break
print 'Your input is: ', N
You can use the and operator:
while True:
s = input("Please enter an non-negative even integer: ")
# Use raw_input instead of input in Python 2
try:
N = int(s)
except ValueError:
continue # Not an integer, try again
if N % 2 == 0 and N >= 0:
break # Abort the infinite loop
Compared to other versions presented here, I prefer to loop without using the break keyboard. You can loop until the number entered is positive AND even, with an initial value set to -1:
n = -1
while n < 0 or n % 2 != 0:
try:
n = int(input("Please enter an non-negative even integer: "))
except ValueError:
print("Please enter a integer value")
print("Ok, %s is even" % n)
Just another solution:
>>> def non_neg(n):
... try:
... if n & 1 == 0 and n > 0:
... return 'Even Positive Number'
... except:
... pass
... return 'Wrong Number'
...
>>> for i in [-1,-2,2,3,4,0.5,'a']:
... print i, non_neg(i)
...
-1 Wrong Number
-2 Wrong Number
2 Even Positive Number
3 Wrong Number
4 Even Positive Number
0.5 Wrong Number
a Wrong Number
>>>
code for fun:
result=[ x for x in [input("Please enter a number:")] if isinstance(x,int) and x>0 and x%2 ==0]
Excuting this list comprehension ,will get you an empty list if occurs any illegal key-in like 0.1, 'abc',999.
code for best practice:
There is quite popular to take all validation expression into lambda for python, for example, like django so :
isPositiveEvenNum=lambda x: x if isinstance(x,int) and x>0 and x%2 ==0 else None
while not isPositiveEvenNum(input("please enter a number:")):
print "None Positive Even Number!"
this can also be writen as
isPositiveEvenNum=lambda x: (isinstance(x,int) and x>0 and x%2 ==0) or False
while not isPositiveEvenNum(input("please enter a number:")):
print "None Positive Even Number!"
to solve the input and raw_input difference between 2.x and 3.x:
import sys
eval_input =lambda str: input(str) if sys.version_info<(3,0,0) else eval(input(str))
then just call eval_input
Related
I was working on a for loop and while loop for 2 separate programs asking for the same thing. My for loop is giving me syntax issues and won't come out as expected…
Expectations: A python program that takes a positive integer as input, adds up all of the integers from zero to the inputted number, and then prints the sum. If your user enters a negative number, it shows them a message reminding them to input only a positive number.
reality:
i1 = int(input("Please input a positive integer: "))
if i1 >= 0:
value = 0 # a default, starting value
for step in range(0, i1): # step just being the number we're currently at
value1 = value + step
print(value1)
else:
print(i1, "is negative")
And my While loop is printing "insert a number" infinitly…
Here is what my while loop looks like:
while True:
try:
print("Insert a number :")
n=int(input())
if(n<0):
print("Only positive numbers allowed")
else:
print ((n*(n+1))//2)
except ValueError:
print("Please insert an integer")
`Same expections as my for loop but as a while loop
Anyone know anyway I could fix this issue?
You have some indentation issues. This way works:
while True:
try:
print("Insert a number: ")
user_input = input()
if user_input == 'q':
exit()
n = int(user_input)
if n <= 0:
print("Only positive numbers allowed")
else:
print(n * (n+1) // 2)
except ValueError:
print("Please enter an integer")
Output sample:
Enter a number:
>>> 10
55
Enter a number:
>>> 1
1
Enter a number:
>>> -1
Only positive numbers allowed
Enter a number:
>>> asd
Please enter an integer
Enter a number:
See more about indentation in the docs.
I created a row of Fibonacci numbers. At the beginning is desired input the number to specify the size of Fibonacci series, in fact the size of the row. The number is required to be an integer number >=2.
The outcome is printing out all Fibonacci number until the last number of the row, with their respective indices within the row! After that it's required to take out a slice of the row, and the outcome is to print out all numbers within the slice with their respective indices.
I successfully mastered to exclude all values that do not fall within range specified, but however I had not succeed to exclude numbers and other inputs of undesired types, example would like to exclude float type of an input variable, and string type of an input variable.
I specified that undesirable types of an input variable are float and string! However it reports me an error! How to overcome that, or by another words how to specify the requirement to exclude a floating variable as well as string variable to not report me an error?
The code:
while True:
n = int(input('Please enter the size of Fibonacci row - positive integer number(N>=2)!'))
if n < 2:
print('This is not valid number! Please enter valid number as specified above!')
continue
elif type(n)==float: # this line is not working!
print('The number has to be an integer type, not float!')
continue
elif type(n)==str: # this line is not working!
print( 'The number has to be an integer type, not string!')
continue
else:
break
def __init__(self, first, last):
self.first = first
self.last = last
def __iter__(self):
return self
def fibonacci_numbers(n):
fibonacci_series = [0,1]
for i in range(2,n):
next_element = fibonacci_series[i-1] + fibonacci_series[i-2]
fibonacci_series.append(next_element)
return fibonacci_series
while True:
S = int(input('Enter starting number of your slice within Fibonacci row (N>=2):'))
if S>n:
print(f'Starting number can not be greater than {n}!')
continue
elif S<2:
print('Starting number can not be less than 2!')
continue
elif type(S)==float: # this line is not working!
print('The number can not be float type! It has to be an integer!')
continue
elif type(S)==str: # this line is not working!
print('Starting number can not be string! It has to be positive integer number greater than or equal to 2!')
continue
else:
break
while True:
E = int(input(f'Enter ending number of your slice within Fibonacci row(E>=2) and (E>={S}):'))
if E<S:
print('Ending number can not be less than starting number!')
continue
elif E>n:
print(f'Ending number can not be greater than {n}')
continue
elif E<2:
print('Ending number can not be greater than 2!')
continue
elif type(E)==float: # this line is not working!
print('Ending number can not be float type! It has to be an integer type!')
continue
elif type(E) ==str: # this line is not working!
print(f'Ending number can not be string! It has to be positive integer number greater than or equal to {S}')
continue
else:
break
print('Fibonacci numbers by index are following:')
for i, item in enumerate(fibonacci_numbers(n),start = 0):
print(i, item)
fibonacci_numbers1 = list(fibonacci_numbers(n))
print('Fibonacci numbers that are within your slice with their respective indices are following:')
for i, item in enumerate(fibonacci_numbers1[S:E], start = S):
print(i, item)
Solved :-) simply add try except block in ur code like the following:
while True:
try:
num = int(input("Enter an integer number: "))
break
except ValueError:
print("Invalid input. Please input integer only")
continue
print("num:", num)
upvote & check :-)
at the first line
n = int(input('Please enter the size of Fibonacci row - positive integer number(N>=2)!'))
you're converting the input to int, so whatever the user provides it will be converted to an int.
if you want your code to be working, replace it with this
n = input('Please enter the size of Fibonacci row - positive integer number(N>=2)!')
Use an try/except/else to test the input. int() raises a ValueError if a string value isn't strictly an integer.
>>> while True:
... s = input('Enter an integer: ')
... try:
... n = int(s)
... except ValueError:
... print('invalid')
... else:
... break
...
Enter an integer: 12a
invalid
Enter an integer: 1.
invalid
Enter an integer: 1.5
invalid
Enter an integer: 1+2j
invalid
Enter an integer: 5
>>>
If you need to check type, isinstance is usually better, e. g.:
if isinstance(var, int) or isinstance(var, str):
pass # do something here
I am making a program that calculates the sum of all even and odd numbers between two number which are user inputted. I'm new to Python and am not sure how to use the range in a loop to make my program work. Here is my code. I know its sloppy and not well put together and not finished but any help works thanks.
n = int(input(" please enter a number"))
m= int(input(" please enter another number"))
count =0
sum =0
for x in range(n,m+1,2):
if x%2==0:
count=count+x
sum = count
print(" the total sum of odd numbers are",sum)
It's important to know if n is greater than m and invert situation if so. Other than that, you need to know if the smallest number is odd or even and begin the two ranges accordingly:
n = int(input("Please enter a number: "))
m = int(input("Please enter another number: "))
# n will always be the smaller one
if n > m:
n, m = m, n
n_is_odd = n % 2 # Gives 1 if n is odd
n_even = n + n_is_odd # Sum 1 if n is odd
n_odd = n + (not n_is_odd) # Sum 1 if n is even
print("the total sum of even numbers is %d" % sum(range(n_even, m+1, 2)) )
print("the total sum of odd numbers is %d" % sum(range(n_odd, m+1, 2)) )
Input validation is a big part of good coding. A good overview can be found here:
Asking the user for input until they give a valid response
To make the validation it reusable I put the validation in a function that only accept integers and (if a minval is provided, makes sure that the input is bigger that the minval.
def while_invalid_ask_input_return_integer(text, minval = None):
"""Aks for input until a number is given that is > minval if minval not None
returns an integer."""
while True:
c = input (text)
try:
c = int(c)
if minval is not None and c < minval:
raise ValueError # its too small, raise an erros so we jump to except:
return c
except ValueError:
if minval is not None:
print("must be a number and greater ", minval)
else:
print("not a number")
I use it to get the first number, and the second number gets the first one as "constraint" so it will be bigger. For summation I just use the range starting once with n once with n+1 till m and a range step of 2. I check what even/oddness n has and print text accordingly:
n = while_invalid_ask_input_return_integer("please enter a number ")
m = while_invalid_ask_input_return_integer("enter number bigger then {}".format(n),n)
print( "Odd sum:" if n % 2 == 1 else "Even sum:", sum(range(n,m+1,2)) )
print( "Even sum:" if n % 2 == 1 else "Odd sum:", sum(range(n+1,m+1,2)) )
Output:
please enter a number k
not a number
please enter a number 55
enter number bigger then 55 2
must be a number and greater 55
enter number bigger then 55 150
Odd sum: 4896
Even sum: 4944
Doku:
sum(iterable)
try: except: error handling
python ternary operator (thats the thing # "Odd sum:" if n % 2 == 1 else "Even sum:" in the print statement)
Here's a function I think fits into the description of what you asked above. It returns None if the user doesn't enter the type of query he or she wants.
So query can either be odd or even and depending on this, it calculates the sum that you want. The function makes use of list comprehension which is super cool too.
def calculate_odd_or_even_sum(query):
start = int(input(" please enter a number"))
end = int(input(" please enter another number"))
count = 0
if query == 'even':
return sum([x for x in range(start, end) if x % 2 == 0])
elif query == 'odd':
return sum([x for x in range(start, end) if x % 2 != 0])
else:
return 0
I think I'm calculating the conversion from an integer to a binary number wrong. I entered the integer 6 and got back the binary number 0, which is definitely wrong. Can you guys help out? Here's the new code.
def ConvertNtoBinary(n):
binaryStr = ''
if n < 0:
print('Value is a negative integer')
if n == 0:
print('Binary value of 0 is 0')
else:
if n > 0:
binaryStr = str(n % 2) + binaryStr
n = n > 1
return binaryStr
def main():
n = int(input('Enter a positive integer please: '))
binaryNumber = ConvertNtoBinary(n)
print('n converted to a binary number is: ',binaryNumber)
main()
You forgot to call raw_input(). Right now you try to convert your prompt message to an integer which cannot work.
n = int(raw_input('Enter a positive integer please: '))
Of course a try..except around that line would be a good idea:
try:
n = int(raw_input('Enter a positive integer please: '))
except ValueError:
n = 0 # you could also exit instead of using a default value
In n = int('Enter a positive integer please: '), you are trying to make an int out of the string 'Enter a positive...'. I would assume you forgot your raw_input(). You could either do
n = int(raw_input('Enter a positive integer please: '))
or
n = raw_input('Enter a positive integer please: ')
n = int(n)
You can't cast a arbitratry string literal to an int. I think what you mean to do is call a prompt method of some sort that takes input from the user.
Write a program that will prompt the user for two integers, each of which is greater
than 0. The program will display and count the number of divisors that the two integers have in
common.
Additional requirements:
if the integer is less than 1 tell the user there is a problem and then prompt them for the
integer again.
This is what I have written so far, but I am stuck here I dont know how to incorporate both numbers. Essentially I do not know where to go from here or if 'here' is even correct???
Please help...[This is my first time with python]
integer1 = input("Enter an integer: ")
integer2 = input("Enter an integer: ")
print integer1, ": " ,
i = 1
while i <= integer1 and integer2 :
if integer1 or integer2 < 1 :
print input("Enter an integer: ")
if integer1%i == 0 and integer2%i == 0 :
print i ,
i = i + 1
Try to do one step after the other. And try to break down your task into simple steps. In your example it could be something like:
Get first number
Get second number
Calculate
This you can break down futher
Get first number:
Get Number from User
Loop while Number is not ok
...
This way you can see that the validation should not be inside the while loop.
Another tip: test each step separately. This way you will find that if integer1 or integer2 < 1 or while i <= integer1 and integer2 will not work the way you think they do.
This is not how logical operators work in Python or programming in general.
while i <= integer1 and integer2 :
In Python integer2 is a separate logical statement that is always true.
Try instead:
while i <= integer1 and i <= integer2
You'll want to move the code that
validates your input outside of the
loop.
Your print i doesn't need a
comma.
The syntax in your flow
control needs a bit of work, for
example if integer1 or integer2 <
1: should be if ((integer1 < 1) or
(integer2 < 1)):.
First we should do a simple way to get both integers; noting there could be multiple errors. (Even better would be raw_input and checking the number resolves to an int).
integer1 = -1
integer2 = -1
while(integer1 < 1):
integer1 = input("Enter integer 1: ")
while(integer2 < 1):
integer2 = input("Enter integer 2: ")
factor_list1 = [] # store factor list of first number
double_factor_count = 0
# generate the factor list of the first number
for i in range(1, integer1+1): # range(1,5+1) is the list [1,2,3,4,5]
if integer1 % i == 0:
factor_list1.append(i)
for j in range(1, integer2+1):
if integer2 % j == 0 and j in factor_list1:
print j,
double_factor_count += 1
print "\n double count:", double_factor_count
Possibly you want to change it to range(2, integer1) if you want to skip 1 and the integer typed in as numbers.
Note your original code wasn't indented (so didn't appear as code in the forums, and that and and or combine expressions (e.g., things that are True or False). So you meant if integer1 < 1 or integer2 < 1:.
Your code is actually very close, but you have a few problems:
You're not validating integer1 and integer2 correctly (though I suspect you know that, since you're just printing the replacement value).
Your loop test is broken. What you've written means "i is less than integer1, and also integer2 isn't zero".
You can also improve your code in a couple of ways:
Ensuring that your input is not only >= 1, but also an integer.
Using a for loop instead of a while loop, using Python's excellent iterables support.
Here's how to make sure that what the user typed was an integer:
integer1 = 0
while not integer1:
try:
# raw_input() ensures the user can't type arbitrary code
# int() throws a ValueError if what they typed wasn't an integer
integer1 = int(raw_input("Enter the first integer: "))
if integer1 < 1:
print "You must enter an integer greater than 0!"
integer1 = 0 # so that our while statement loops again
except ValueError:
# the user typed something other than an integer
print "You must enter an integer!"
The while, try, and if statements here ensure that the user will be forced to enter a valid integer before your code continues. Here's an example of what the user sees:
Enter the first integer: 6.6
You must enter an integer!
Enter the first integer: -5
You must enter an integer greater than 0!
Enter the first integer: sys.exit(0)
You must enter an integer!
Enter the first integer: 12
Enter the second integer:
And this is how I'd recommend setting up your loop:
# min() returns the smallest of its arguments
# xrange() iterates over a sequence of integers (here, starting with 1 and
# stopping at min(integer1, integer2))
for i in xrange(1, min(integer1, integer2) + 1):
# magic goes here!
Documentation links:
int()
min()
raw_input() and input()
xrange()
Your problem is with your if statements.
Rather than saying: while i <= integer1 and integer2, you need to say while i <= integer1 and i <= integer2
The same applies for your other if statement. if integer1 or integer2 < 1 : should be if integer1 < 1 or integer2 < 1 :