I dont understand this syntax error - python

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.

Related

How to exclude specific type of an input variable in Python?

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

Checking non-negative even integer in Python

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

How to count how many tries are used in a loop

For a python assignment I need to ask users to input numbers until they enter a negative number. So far I have:
print("Enter a negative number to end.")
number = input("Enter a number: ")
number = int(number)
import math
while number >= 0:
numberagain = input("Enter a number: ")
numberagain = int(numberagain)
while numberagain < 0:
break
how do I add up the number of times the user entered a value
i = 0
while True:
i += 1
n = input('Enter a number: ')
if n[1:].isdigit() and n[0] == '-':
break
print(i)
The str.isdigit() function is very useful for checking if an input is a number. This can prevent errors occurring from attempting to convert, say 'foo' into an int.
import itertools
print('Enter a negative number to end.')
for i in itertools.count():
text = input('Enter a number: ')
try:
n = int(text)
except ValueError:
continue
if n < 0:
print('Negative number {} entered after {} previous attempts'.format(n, i))
break
The solution above should be robust to weird inputs such as trailing whitespace and non-numeric stuff.
Here's a quick demo:
wim#wim-desktop:~$ python /tmp/spam.py
Enter a negative number to end.
Enter a number: 1
Enter a number: 2
Enter a number: foo123
Enter a number: i am a potato
Enter a number: -7
Negative number -7 entered after 4 previous attempts
wim#wim-desktop:~$

Check if numbers are in a certain range in python (with a loop)? [duplicate]

This question already has answers here:
Determine whether integer is between two other integers
(16 answers)
Closed 4 years ago.
Here's my code:
total = int(input("How many students are there "))
print("Please enter their scores, between 1 - 100")
myList = []
for i in range (total):
n = int(input("Enter a test score >> "))
myList.append(n)
Basically I'm writing a program to calculate test scores but first the user has to enter the scores which are between 0 - 100.
If the user enters a test score out of that range, I want the program to tell the user to rewrite that number. I don't want the program to just end with a error. How can I do that?
while True:
n = int(input("enter a number between 0 and 100: "))
if 0 <= n <= 100:
break
print('try again')
Just like the code in your question, this will work both in Python 2.x and 3.x.
First, you have to know how to check whether a value is in a range. That's easy:
if n in range(0, 101):
Almost a direct translation from English. (This is only a good solution for Python 3.0 or later, but you're clearly using Python 3.)
Next, if you want to make them keep trying until they enter something valid, just do it in a loop:
for i in range(total):
while True:
n = int(input("Enter a test score >> "))
if n in range(0, 101):
break
myList.append(n)
Again, almost a direct translation from English.
But it might be much clearer if you break this out into a separate function:
def getTestScore():
while True:
n = int(input("Enter a test score >> "))
if n in range(0, 101):
return n
for i in range(total):
n = getTestScore()
myList.append(n)
As f p points out, the program will still "just end with a error" if they type something that isn't an integer, such as "A+". Handling that is a bit trickier. The int function will raise a ValueError if you give it a string that isn't a valid representation of an integer. So:
def getTestScore():
while True:
try:
n = int(input("Enter a test score >> "))
except ValueError:
pass
else:
if n in range(0, 101):
return n
You can use a helper function like:
def input_number(min, max):
while True:
n = input("Please enter a number between {} and {}:".format(min, max))
n = int(n)
if (min <= n <= max):
return n
else:
print("Bzzt! Wrong.")

Python Factorial program help

Here is what i wrote:
number = raw_input('Enter an integer= ')
if number < 0:
print 'Invalid number'
else:
for k in range(1,(number)):
number *= k
print number
I want to be able to input any number (that is greater than 0), but when i input a number say 4 (the factorial of 4 is 24) i get this error:
Traceback (most recent call last):
File "problem.py", line 6, in <module>
for k in range(1,(number)):
TypeError: range() integer end argument expected, got str.
I don't understand what it means and as far as i know the code should be working, Please Help!
This works perfectly: factorial.py
#!/usr/bin/env python
# imports go here
__author__ = 'Michael O. Duffy'
__status__ = "Development"
def factorial(n):
""" Calculate a factorial of an integer """
factorial = 1
if n < 0:
print 'Invalid number'
else:
for k in range(1,n+1):
factorial *= k
return factorial
if __name__ == '__main__':
for number in range(1, 20):
print 'n: ', number, 'n!: ', factorial(number)
You should know that this is an inefficient, academic implementation that shouldn't be used in any serious application. You'll be a lot better off using a gamma or lngamma implementation and a dictionary cache to save on calculations if you use values repeatedly:
http://mathworld.wolfram.com/GammaFunction.html
What about recursion?
def factorial(n):
if n < 0:
print("ERROR!") # throw error, return -1, or whatever
elif n <= 1:
return 1
else:
return n * factorial(n - 1)
raw_input returns a string, not an integer. Create an integer this way:
number = int(raw_input('Enter an integer= '))
The user might type something besides an integer, in which case you might want to handle that possibility.
while True:
try:
number = int(raw_input('Enter an integer= '))
except ValueError:
print "That wasn't an integer"
else:
break
using xxxxx.py
num=int(raw_input("Enter a number"))
n=1
while num>=0:
n=n*num
num=num-1
print "Factorial of the given number is: ",n

Categories

Resources