I saw the code snippet that I think it is illegal, but not sure yet.
This is not exactly the same code, but I try to keep the original as much as I can.
def validate_check(string):
try:
len(string) > 0
# do something
except Error:
# do something
Doesn't len(string) > 0 have to be in condition statement? Or is it something python syntax?
Doesn't len(string) > 0 have to be in condition statement?
No, but the example you've provided doesn't make a ton of sense.
Here's a different, similar construction that might help:
x = input()
try:
10 / int(x)
except ZeroDivisionError:
print("Can't divide by zero")
except ValueError:
print("Can't convert to int")
The result of 10 / int(x) is calculated (to see whether it will raise an error), but the result of that calculation is thrown away.
The reason I say your example is a bit weird is because the comparison with zero will have no effect whatsoever. So while the code will serve as a way of testing whether len can be called on string, that's about all it'll do.
This is valid syntax. But if you write:
len(string) > 0
print("hi")
then "hi" will be printed regardless of the length of the string. The only relevance this statement has is that it will throw an exception when either string has no length, or the result of len(string) is not comparable to 0.
What the author of the code is doing is avoiding the more complicated check if isinstance(string, str) and string: (or, I guess, if isinstance(string, collections.abc.Sized) and len(string) > 0).
If string is None, the len function will raise an error.
Perhaps it's the reason why your function is named validate_check.
Trying to write a one-line function that will take the input string and get the middle letter/letters depending on if the string is even or uneven. I get an error code saying there's a syntax error at the first len(s) after the else if. The third line of code should continue on the second line.
The code:
def get_middle(s):
return m = s[int(len(s/2))] if type(len(s)/2) is float else if
s[int(len(s)/2)-1:int(len(s)/2)]
The ERROR:
Traceback (most recent call last):
File "main.py", line 1, in <module>
from solution import *
File "/home/codewarrior/solution.py", line 2
return m = s[len(s/2)] if type(len(s)/2) is float else if
s[int(len(s)/2)-1:int(len(s)/2)]
^
SyntaxError: invalid syntax
type(len(s)/2) is float is not a check for even-odd length, as you can see below, both even and odd string lengths evaluate to True for the check you had, because both divisions are float values
4/2 = 2.0 and 5/2=2.5
In [16]: s = 'abcd'
In [17]: type(len(s)/2) is float
Out[17]: True
In [18]: s = 'abcde'
In [19]: type(len(s)/2) is float
Out[19]: True
Why not keep things simple by checking divisibility by 2 for even/odd length.
Check if the number is length is odd or even, and select middle characters accordingly.
def get_middle(s):
#If even length, select 2 characters
if len(s)%2 == 0:
return s[int(len(s)/2)-1:int(len(s)/2)+1]
#If odd length, select 1 character
else:
return s[int(len(s)/2)]
print(get_middle('a'))
print(get_middle('ab'))
print(get_middle('abc'))
print(get_middle('abcd'))
print(get_middle('abcde'))
The output will be
a
ab
b
bc
c
From here, we can easily write the one liner
def get_middle(s):
return s[int(len(s)/2)-1:int(len(s)/2)+1] if len(s)%2 == 0 else s[int(len(s)/2)]
The guys in the comments and other answers already answered your question but I want to extend them a bit with some life-style advice. Yes, the issue at hand is that you shouldn't have else if at the end, the correct syntax is foo if condition else bar. And also type(len(s)) is Float is an absurd way to check for oddness. Hopefully, you already got that from the comments.
However, I want to argue that writing things on 1 line just so you can brag about how smart you are is a very detrimental practice. Programs must be written for people to read, and only incidentally for machines to execute. Unless, you can truly make that one liner understandable, it makes no sense to write it like you did - rather prefer to write it on multiple lines to make any errors obvious. Prefer to think about the other people that will be reading this code more than 'oh, see how cool is that'.
Now if you really insist on writing short and concise code, that's ok and here's how you can actually rewrite the thing to be a meaningful one liner:
from math import ceil
def get_middle(s):
return s[ceil(len(s)/2 - 1): ceil(len(s)/2)]
I'll let you figure out why that works on your own.
Your code has syntax error because if cannot be on the second line unless you escape the new line and only expr if cond else expr is valid inline if-statement:
foo() if condition \
else bar()
And there's something you'll probably like: onelinerizer
Original post has another problem with even/odd check. To solve it in one line:
def get_middle(s):
return m = s[int(len(s/2))] if len(s)%2 != 0 else s[int(len(s)/2)-1:int(len(s)/2)]
Here uses %2 to get remainder.
Though comments saying int(len(s)/2) would fail, also it's not guaranteed to be floor of division, as far as I see it's equivalent as len(s)//2:
def get_middle(s):
return m = s[len(s)//2] if len(s)%2 != 0 else s[len(s)//2-1:len(s)//2]
i have a question
Write a program to check the validity of password input by users.
Following are the criteria for checking the password:
At least 1 letter between [a-z]
At least 1 number between [0-9]
At least 1 letter between [A-Z]
At least 1 character from [$##]
Minimum length of transaction password: 6
Maximum length of transaction password: 12
Your program should accept a sequence of comma separated passwords and will
check them according to the above criteria. Passwords that match the criteria are
to be printed, each separated by a comma
Example
If the following passwords are given as input to the program:
ABd1234#1,a F1#,2w3E*,2We3345
Then, the output of the program should be:
ABd1234#1
the solution is below
def check_password(word):
special_str = "$##"
accepted = []
passwords = word.split(',')
for password in passwords:
lower = 0
upper = 0
digits = 0
special = 0
for char in password:
if char.islower():
lower += 1
elif char.isupper():
upper += 1
elif char.isdigit():
digits += 1
elif special_str.find(char) != -1:
special += 1
if lower >= 1 and upper >= 1 and digits >= 1 and special >= 1 and len(password) in range(6,13):
accepted.append(password)
return accepted
i was told to also write a unit test for it
Now am new to using unit tests, so after going through some examples i tried writing a unit test as below
import unittest
import question1
class Test_PasswordChecker(unittest.TestCase):
def test_valid(self):
self.assertEquals(question1.check_password("ABd1234#1,a F1#,2w3E*,2We3345"),'ABd1234#1')
if __name__ == '__name__':
unittest.main()
The source code works well, though am having problems on whether i have made the correct unit test for it.
Need some help on how to make the best unit test
First of all your code has an issue: you are printing the result instead of returning it.
As a general principle you should always strive to decouple input-ouput to "processing". If you have functions that both compute stuff and print/request input you end up reducing their reusability and testability.
In this case the issue with your unittest is that check_password always returns None since you did not return anythign and hence it will always fail.
So first thing replace:
print(accepted)
with
return accepted
Now: you need more than one test for this function. You should try to write a test for all possible cases.
For example:
check what happens when no password satisfies the requirements?
What happens if all satisfy the requirements?
What happens if you give the empty input to the function?
For each requirement try to see what happens if you try to call the function with a password that satisfies all requirement except that one.(e.g. a password that has a lowercase letter, an uppercase letter, a symbol, a digit but whose length is 4 or 20).
Basically you should try to divide the possible input into a number of categories and check at least one input for each category.
It prints diga and digb but doesnt work with c! Any help? It's supposed to be a Denary to Binary converter but only 1-64, once i've cracked the code will increase this! Thanks so much
denaryno=int(input("Write a number from 1-64 "))
if 64%denaryno > 0:
diga=0
remaindera=(64%denaryno)
if 32/denaryno<1:
digb=1
remainderb=(denaryno%32)
else:
digb =0
if 16/remainderb<1:
digc=1
remainderc=(denaryno%16)
else:
digc=0
if 8/remainderc<1:
digd=1
remainderd=(denaryno%8)
else:
digd=0
if 4/remainderd<1:
dige=1
remaindere=(denary%4)
else:
dige=0
if 2/remaindere<1:
digf=1
remainderf=(denary%2)
else:
digf=0
if 1/remainderf<1:
digg=1
remainderg=(denary%1)
else:
digg=0
print (str(diga)+str(digb))
You only set digc in one of the top if/else statement. If 32/denaryno<1 is True, you don't set digc at all.
Set digc at the top of the function (to 0 or whatever else you want it to be). This applies to all the digit variables, digd, dige, etc.
What you really should do, instead, is use a list of digits, and append either a 0 or a 1 to that list every time you divide the number by a factor.
You may want to take a look at the divmod() function; it returns both the quotient and the remainder. You could also do with some looping here to slash the number of if statements needed here:
number = int(input("Write a number from 1-64 "))
digits = []
factor = 64
while number:
quotient, number = divmod(number, factor)
digits.append(quotient)
factor //= 2
print(''.join(map(str, digits)))
Wow that was a lot of work, you don't have to do all that.
def bin_convert(x, count=8):
return "".join(map(lambda y:str((x>>y)&1), range(count-1, -1, -1)))
here are the functions comprising this one from easy->important
str() returns a string
range() is a way to get a list from 1 number to another. Written like this range(count-1, -1, -1) counts backwards.
"".join() is a way to take an iterable and put the pieces together.
map() is a way to take a function and apply it to an iterable.
lambda is a way to write a function in 1 line. I was being lazy and could have written another def func_name(y) and it would have worked just as well.
>> is a way to shift bits. (which I believe understanding this one is the key component to understanding your problem)
This question already has answers here:
What's the canonical way to check for type in Python?
(15 answers)
Closed 3 years ago.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
How do I check whether a variable is an integer?
If you need to do this, do
isinstance(<var>, int)
unless you are in Python 2.x in which case you want
isinstance(<var>, (int, long))
Do not use type. It is almost never the right answer in Python, since it blocks all the flexibility of polymorphism. For instance, if you subclass int, your new class should register as an int, which type will not do:
class Spam(int): pass
x = Spam(0)
type(x) == int # False
isinstance(x, int) # True
This adheres to Python's strong polymorphism: you should allow any object that behaves like an int, instead of mandating that it be one.
BUT
The classical Python mentality, though, is that it's easier to ask forgiveness than permission. In other words, don't check whether x is an integer; assume that it is and catch the exception results if it isn't:
try:
x += 1
except TypeError:
...
This mentality is slowly being overtaken by the use of abstract base classes, which let you register exactly what properties your object should have (adding? multiplying? doubling?) by making it inherit from a specially-constructed class. That would be the best solution, since it will permit exactly those objects with the necessary and sufficient attributes, but you will have to read the docs on how to use it.
All proposed answers so far seem to miss the fact that a double (floats in python are actually doubles) can also be an integer (if it has nothing after the decimal point). I use the built-in is_integer() method on doubles to check this.
Example (to do something every xth time in a for loop):
for index in range(y):
# do something
if (index/x.).is_integer():
# do something special
Edit:
You can always convert to a float before calling this method. The three possibilities:
>>> float(5).is_integer()
True
>>> float(5.1).is_integer()
False
>>> float(5.0).is_integer()
True
Otherwise, you could check if it is an int first like Agostino said:
def is_int(val):
if type(val) == int:
return True
else:
if val.is_integer():
return True
else:
return False
Here's a summary of the different methods mentioned here:
int(x) == x
try x = operator.index(x)
isinstance(x, int)
isinstance(x, numbers.Integral)
and here's how they apply to a variety of numerical types that have integer value:
You can see they aren't 100% consistent. Fraction and Rational are conceptually the same, but one supplies a .index() method and the other doesn't. Complex types don't like to convert to int even if the real part is integral and imaginary part is 0.
(np.int8|16|32|64(5) means that np.int8(5), np.int32(5), etc. all behave identically)
If you really need to check then it's better to use abstract base classes rather than concrete classes. For an integer that would mean:
>>> import numbers
>>> isinstance(3, numbers.Integral)
True
This doesn't restrict the check to just int, or just int and long, but also allows other user-defined types that behave as integers to work.
>>> isinstance(3, int)
True
See here for more.
Note that this does not help if you're looking for int-like attributes. In this case you may also want to check for long:
>>> isinstance(3L, (long, int))
True
I've seen checks of this kind against an array/index type in the Python source, but I don't think that's visible outside of C.
Token SO reply: Are you sure you should be checking its type? Either don't pass a type you can't handle, or don't try to outsmart your potential code reusers, they may have a good reason not to pass an int to your function.
Why not try something like:
if x%1 == 0:
Rather than over complicate things, why not just a simple
if type(var) is int:
A simple method I use in all my software is this. It checks whether the variable is made up of numbers.
test = input("Enter some text here: ")
if test.isdigit() == True:
print("This is a number.")
else:
print("This is not a number.")
You can also use str.isdigit. Try looking up help(str.isdigit)
def is_digit(str):
return str.isdigit()
Found a related question here on SO itself.
Python developers prefer to not check types but do a type specific operation and catch a TypeError exception. But if you don't know the type then you have the following.
>>> i = 12345
>>> type(i)
<type 'int'>
>>> type(i) is int
True
it's really astounding to see such a heated discussion coming up when such a basic, valid and, i believe, mundane question is being asked.
some people have pointed out that type-checking against int (and long) might loose cases where a big decimal number is encountered. quite right.
some people have pointed out that you should 'just do x + 1 and see whether that fails. well, for one thing, this works on floats too, and, on the other hand, it's easy to construct a class that is definitely not very numeric, yet defines the + operator in some way.
i am at odds with many posts vigorously declaring that you should not check for types. well, GvR once said something to the effect that in pure theory, that may be right, but in practice, isinstance often serves a useful purpose (that's a while ago, don't have the link; you can read what GvR says about related issues in posts like this one).
what is funny is how many people seem to assume that the OP's intent was to check whether the type of a given x is a numerical integer type—what i understood is what i normally mean when using the OP's words: whether x represents an integer number. and this can be very important: like ask someone how many items they'd want to pick, you may want to check you get a non-negative integer number back. use cases like this abound.
it's also, in my opinion, important to see that (1) type checking is but ONE—and often quite coarse—measure of program correctness, because (2) it is often bounded values that make sense, and out-of-bounds values that make nonsense. sometimes just some intermittent values make sense—like considering all numbers, only those real (non-complex), integer numbers might be possible in a given case.
funny non-one seems to mention checking for x == math.floor( x ). if that should give an error with some big decimal class, well, then maybe it's time to re-think OOP paradigms. there is also PEP 357 that considers how to use not-so-obviously-int-but-certainly-integer-like values to be used as list indices. not sure whether i like the solution.
If you want to check that a string consists of only digits, but converting to an int won't help, you can always just use regex.
import re
x = "01234"
match = re.search("^\d+$", x)
try: x = match.group(0)
except AttributeError: print("not a valid number")
Result: x == "01234"
In this case, if x were "hello", converting it to a numeric type would throw a ValueError, but data would also be lost in the process. Using a regex and catching an AttributeError would allow you to confirm numeric characters in a string with, for instance, leading 0's.
If you didn't want it to throw an AttributeError, but instead just wanted to look for more specific problems, you could vary the regex and just check the match:
import re
x = "h01234"
match = re.search("\D", x)
if not match:
print("x is a number")
else:
print("encountered a problem at character:", match.group(0))
Result: "encountered a problem at character: h"
That actually shows you where the problem occurred without the use of exceptions. Again, this is not for testing the type, but rather the characters themselves. This gives you much more flexibility than simply checking for types, especially when converting between types can lose important string data, like leading 0's.
why not just check if the value you want to check is equal to itself cast as an integer as shown below?
def isInt(val):
return val == int(val)
It is very simple to check in python. You can do like this:
Suppose you want to check a variable is integer or not!
## For checking a variable is integer or not in python
if type(variable) is int:
print("This line will be executed")
else:
print("Not an integer")
If you are reading from a file and you have an array or dictionary with values of multiple datatypes, the following will be useful.
Just check whether the variable can be type casted to int(or any other datatype you want to enforce) or not.
try :
int(a);
#Variable a is int
except ValueError :
# Variable a is not an int
In the presence of numpy check like ..
isinstance(var, numbers.Integral)
.. (slow) or ..
isinstance(var, (int, long, np.integer))
.. in order to match all type variants like np.int8, np.uint16, ...
(Drop long in PY3)
Recognizing ANY integer-like object from anywhere is a tricky guessing game. Checking
var & 0 == 0
for truth and non-exception may be a good bet. Similarly, checking for signed integer type exclusively:
var ^ -1 == -var - 1
If the variable is entered like a string (e.g. '2010'):
if variable and variable.isdigit():
return variable #or whatever you want to do with it.
else:
return "Error" #or whatever you want to do with it.
Before using this I worked it out with try/except and checking for (int(variable)), but it was longer code. I wonder if there's any difference in use of resources or speed.
A simple way to do this is to directly check if the remainder on division by 1 is 0 or not.
if this_variable % 1 == 0:
list.append(this_variable)
else:
print 'Not an Integer!'
Here is a simple example how you can determine an integer
def is_int(x):
print round(x),
if x == round(x):
print 'True',
else:
print 'False'
is_int(7.0) # True
is_int(7.5) # False
is_int(-1) # True
If you just need the value, operator.index (__index__ special method) is the way to go in my opinion. Since it should work for all types that can be safely cast to an integer. I.e. floats fail, integers, even fancy integer classes that do not implement the Integral abstract class work by duck typing.
operator.index is what is used for list indexing, etc. And in my opinion it should be used for much more/promoted.
In fact I would argue it is the only correct way to get integer values if you want to be certain that floating points, due to truncating problems, etc. are rejected and it works with all integral types (i.e. numpy, etc.) even if they may not (yet) support the abstract class.
This is what __index__ was introduced for!
If you want to check with no regard for Python version (2.x vs 3.x), use six (PyPI) and it's integer_types attribute:
import six
if isinstance(obj, six.integer_types):
print('obj is an integer!')
Within six (a very light-weight single-file module), it's simply doing this:
import sys
PY3 = sys.version_info[0] == 3
if PY3:
integer_types = int,
else:
integer_types = (int, long)
use the int function to help
intchecker = float(input('Please enter a integer: '))
intcheck = 0
while intcheck != 1:
if intchecker - int(intchecker) > 0:
intchecker = float(input("You didn't enter a integer. "
"Please enter a integer: "))
else:
intcheck = 1
print('you have entered a integer')
I was writing a program to check if a number was square and I encountered this issue, the
code I used was:
import math
print ("this program will tell you if a number is square")
print ("enter an integer")
num = float(input())
if num > 0:
print ("ok!")
num = (math.sqrt(num))
inter = int(num)
if num == inter:
print ("It's a square number, and its root is")
print (num)
else:
print ("It's not a square number, but its root is")
print (num)
else:
print ("That's not a positive number!")
To tell if the number was an integer I converted the float number you get from square rooting the user input to a rounded integer (stored as the value ), if those two numbers were equal then the first number must have been an integer, allowing the program to respond. This may not be the shortest way of doing this but it worked for me.
You can do this.
if type(x) is int:
#!/usr/bin/env python
import re
def is_int(x):
if(isinstance(x,(int,long))):
return True
matchObj = re.match(r'^-?\d+\.(\d+)',str(x))
if matchObj:
x = matchObj.group(1)
if int(x)-0==0:
return True
return False
print is_int(6)
print is_int(1.0)
print is_int(1.1)
print is_int(0.1)
print is_int(-956.0)
If you have not int you can do just this:
var = 15.4
if(var - int(var) != 0):
print "Value is not integer"
If you want to write a Python 2-3 compatible code
To test whether a value is an integer (of any kind), you can to do this :
# Python 2 and 3:
import sys
if sys.version_info < (3,):
integer_types = (int, long,)
else:
integer_types = (int,)
>>> isinstance(1, integer_types)
True
# Python 2 only:
if isinstance(x, (int, long)):
...
# Python 3 only:
if isinstance(x, int):
...
source : http://python3porting.com/differences.html
A more general approach that will attempt to check for both integers and integers given as strings will be
def isInt(anyNumberOrString):
try:
int(anyNumberOrString) #to check float and int use "float(anyNumberOrString)"
return True
except ValueError :
return False
isInt("A") #False
isInt("5") #True
isInt(8) #True
isInt("5.88") #False *see comment above on how to make this True
you can do this by:
name = 'Bob'
if type(name) == str:
print 'this works'
else:
print 'this does not work'
and it will return 'this works'... but if you change name to int(1) then it will return 'this does not work' because it is now a string...
you can also try:
name = int(5)
if type(name) == int:
print 'this works'
else:
print 'this does not work'
and the same thing will happen
There is another option to do the type check.
For example:
n = 14
if type(n)==int:
return "this is an int"