I'm trying to make a code that can generate valid credit card numbers. So far I've created the random number generator that adds a specific prefix in front of it (in this case, I'm using Visa's prefix '4' and generating an additional 15 random integers behind it). The problem I think I'm having is I am unable to get my 'while True' conditions to work.
As it stands, when I run the program, it prints a seemingly arbitrary amount of 16 digit numbers that do start with '4', but don't follow the algorithm I have set up in my 'while True' conditions. Some of the numbers this code prints is valid when copied and pasted here:
https://www.dcode.fr/luhn-algorithm
The majority do not, however.
I have used the portion of the code that confirms the Luhn's algorithm works with success on another project, but for some reason I can't get it to work here. Any guidance is greatly appreciated as I'm very new to Python.
This is what I have done so far...
import random
def s():
prefix = '4'
return (prefix + str(random.randint(100000000000000,999999999999999)))
while True:
print(s())
q_16= (2*int(s()[14]),2*int(s()[12]),2*int(s()[10]),2*int(s()[8]),2*int(s()[6]),2*int(s()[4]),2*int(s()[2]),2*int(s()[0]))
p= int("".join(map(str, q_16)))
p2= list(map(int, str(p)))
p3= sum(p2)+int(s()[15])+int(s()[13])+int(s()[11])+int(s()[9])+int(s()[7])+int(s()[5])+int(s()[3])+int(s()[1])
if p3 % 10 == 0:
break
Related
I've created a program to take in a password and tell the user by how many characters the password is wrong. To do this I've used difflib.Differ().
However I'm not sure how to create another loop to make it also be able to tell my how many characters the password is wrong if the input is missing characters.
This is the checking function itself.
import difflib
def check_text(correctPass, inputPass):
count = 0
difference = 0
d = difflib.Differ()
count_difference = list(d.compare(correctPass, inputPass))
while count < len(count_difference):
if '+' in count_difference[count]:
difference +=1
count +=1
return difference
At the moment the function can only pick up mistakes if the mistakes are extra characters (correct password in this case is 'rusty').
My understanding of difflib is quite poor. Do I create a new loop, swap the < for a > and the +s for -s? Or do I just change the conditions already in the while loop?
EDIT:
example input/output: rusty33 –> wrong by 2 characters
rsty –> wrong by 0 characters
I'm mainly trying to make the function detect if there are characters missing or extra, not too fussed about order of characters for the moment.
I couldn't quite find a similar question on here (or don't know Python well enough to figure it out from other questions), so here goes.
I'm trying to extract part of a string with re.search().start (I've also tried end()), and that line either seems to find something (but a few spaces off) or it returns None, which is baffling me. For example:
def getlsuscore(line):
print(line)
start=re.search(' - [0-9]', line).start()+2
score=line[start:start+3]
print(score)
score=int(score.strip())
return(score)
The two prints are in there for troubleshooting purposes. The first one prints out:
02:24 LSU 62 - 80 EDDLESTONE,BRANDON SUB IN. SHORTESS,HENRY SUB IN. ROBINSON III,ELBERT SUB OUT. QUARTERMAN,TIM SUB OUT.
Exactly as I expect it to. For the record, I'm trying to extract the 80 in that line and force it to an int. I've tried with various things in the regex match, always including the hyphen, and accordingly different numbers at the end to get me to the correct starting point, and I've tried playing with this in many other ways and still haven't got it to work. As for the print(score), I either get "AttributeError: 'NoneType' object has no attribute 'start'" when I have the start()+whatever correct, or if I change it to something wrong just to try it out, I get something like "ValueError: invalid literal for int() with base 10: '-'" or "ValueError: invalid literal for int() with base 10: '- 8'", with no addition or +1, respectively. So why when I put +2 or +3 at the end of start() does it give me an error? What am I messing up here?
Thanks for the help, I'm a noob at Python so if there's another/better way to do this that isn't regex, that works as well. I've just been using this exact same thing quite a bit on this project and had no problems, so I'm a bit stumped.
Edit: More code/context
def getprevlsuscore(file, time):
realline=''
for line in file:
line=line.rstrip()
if line[0:4]==time:
break
if re.search('SUB IN', line):
if not re.search('LSU', line[:9]):
realline=line
return(getlsuscore(realline))
It only throws the error when called in this block of code, and it's reading from a text file that has the play by play of a basketball game. Several hundred lines long, formatted like the line above, and it only throws an error towards the end of the file (I've tried on a couple different games).
The above function is called by this one:
def plusminus(file, list):
for player in list:
for line in file:
line=line.rstrip()
if not re.search('SUB IN', line):
continue
if not re.search('LSU', line):
continue
if not re.search(player.name, line):
continue
lsuscore=getlsuscore(line)
previouslsuscore=getprevlsuscore(file, line[0:4])
oppscore=getoppscore(line)
previousoppscore=getprevoppscore(file, line[0:4])
print(lsuscore)
print(previouslsuscore)
print(oppscore)
print(previousoppscore)
Obviously not finished, the prints are to check the numbers. The scope of the project is that I'm trying to read a txt file copy/paste of a play by play and create a plus/minus for each player, showing the point differentials for the time they've played (e.g. if player X was in for 5 minutes, and his school scored 15 while the other school scored 5 in that time, he'd be +10).
I think a much easier way of getting the scores extracted from that string, no regex involved, is to use the split() method. That method will split the input string on any whitespace and return an array of the substrings.
def getlsuscore(line):
# Example line: 02:24 LSU 62 - 80 ...
splitResults = line.split()
# Index 0 holds the time,
# Index 1 holds the team name,
# Index 2 holds the first score (as a string still),
# Index 3 holds the separating dash,
# Index 4 holds the second score (as a string still),
# And further indexes hold everything else
firstScore = int(splitResults[2])
secondScore = int(splitResults[4])
print(firstScore, secondScore)
return firstScore
You could try something like this:
m = re.search('(\\d+)\\s*-\\s*(\\d+)', line)
s1 = int(m.group(1))
s2 = int(m.group(2))
print(s1, s2)
This just looks for two numbers separated by a hypen, then decodes them into s1 and s2, after which you can do what you like with them. In practice, you should check m to make sure it isn't None, which would indicate a failed search.
Use a group to extract the number instead of resorting to fiddling with the start index of the match:
>>> import re
>>> line="02:24 LSU 62 - 80 EDDLESTONE,BRANDON SUB IN. blah blah..."
>>> int(re.search(r' - (\d+)', line).group(1))
80
>>>
If you get an error like AttributeError: 'NoneType' object has no attribute 'group' that means that the line you are working on doesn't have the " - (\d+)" sequence in it. For instance, maybe its an empty line. You can catch the problem with a try/except block. Then you have to decide whether this is a bad error or not. If you are absolutely positive that all lines follow your rules then maybe its a fatal error and you should exit warning the user that data is bad. Or if you are more loosey about the data, ignore it and continue.
This code was given to me by my professor, and prints a triangle of *s:
def printTriangle(size):
for i in range(0,size):
for j in range(0,i+1):
print "*",
print
This is my failed attempt to code an inverse of the triangle:
def printInvertedTriangle(size):
for i in range(size,0):
for j in range(size,i-1):
print "*",
print
I have tried this many different ways, but this is how I think it should be, and it only gives me blank space before the program ends.
My understanding is that this is how his works:
for i in range(start,finish):
for j in range(start,step):
print "*",
print
Can anyone explain to me why the first block my professor gave me works, and why mine prints blank space? I thought I understood his loop; so what was I doing wrong in mine? What should it look like? I want something based off of his for loop. His goes against what I've been reading in Python tutorials in that he has only (start,step), whereas the tutorials say it goes (start,stop,step).
I got started in programming with JS, and thought that some simple Python loops would be a walk in the park...
Thanks a lot for any and all help!! #noob
def printInvertedTriangle(size):
**for i in range(size,0):**
for j in range(size,i-1):
print "*",
print
Your error of having white space shown I believe is as a result of line two. Since this index is counting how many times to step through lines, this needs to still run through x amount of iterations by ranging from (0,size).
In the second for loop, as the lines increase from 1 to 2 to 3 ...etc use variable i and the max (size) to build the reverse triangle.
Try this:
def printReverseTriangle(size):
for i in range(0,size):
for j in range(i,size):
print "*",
print
The reason your script outputs nothing is your range doesn't work.
As we can see in the interpreter:
>>> range(10,0)
[]
It outputs an empty list.
One way to accomplish what you want is to use the reversed() builtin to reverse the list.
for i in reversed(range(0,size)):
for j in range(0,i+1):
To help you in the future, try to use the interpreter more to check the output of things.
You can open any python module in interactive mode, which runs the program and then lets you use the interpreter afterward.
python -i script.py
Here is a program that I had to make for my weekend assignment. It gives a pretty decent reverse triangle as well.
def reverse_triangle(n):
r=n/2+1
for i in range(r-1,0,-1):
print" "*(r-i)," *"*i
def main():
n=input('Enter the size=')
reverse_triangle(n)
main()
Note: In this bit " *"*i I put the space before the asterisk because my PC's version of Python 2.7 does not print the pattern symmetrically if the space is not added. You can try it with the space or without it and check if it works for you.
I'm completely new to Python so all of this is a bit new for me.
I'm trying to create a script in which it by itself thinks of a number and after wards wants the user to guess a number and enter it. It seemed to work but there are wo problems here.
It understands everything however it does not understand the == part.
Because even though the both numbers are the same, it still goes on towards the else statement.
import random
while True:
Thethinker = random.randint(1,10)
Guessnumber = (input("Guess a random number "))
if Guessnumber == Thethinker:
print("Correct")
print(Thethinker)
else:
print("Not correct")
print(Thethinker)
Any help?
Assuming Python 3, input returns a string.
In Python, a string and a number can never be "equal"; you have to transform one or the other. E.g, if you use
Thethinker = str(random.randint(1,10))
then the equality-comparison with another string can succeed.
Your input returns a string instead of an integer. To get an integer do:
int(Guessnumber)
This is better than using str() because then if you ever want to change the numbers, you wouldn't be able to do that without doing the method I suggested
As far as I know, I don't do much Python
I have been working on a small toolkit for awhile now as a way to learn basic python. part of this toolkit is the code that follows this explanation. It is a basic network enumeration script, to simply ping all ip addresses in your local subnet. However I am having an issue implementing a few pieces.
first the code
ip1=raw_input()
if ip1 == None:
ip="192.168.0.x"
else:
ip=ip1
ipend="1"
while ipend != 255:
ip.replace("x", ipend)
attempt=subprocess.Popen(["ping.exe", ip], stdout=subprocess.PIPE).communicate()[0]
if ("unreachable" in attempt):
pass
else:
print "The host at ", ip, "is UP!"
ipend += 1
if ipend == "255":
subprocess.stop
raw_input("Thank you for using PTK. Please press enter to exit.")
enum()
so my first issue, I believe is in my str.replace function, I am attempting to and an int to a str and due to this it seems to be unable to create, ping, and print the correct ip. I'm unsure if converting the entire string to a floating int would work, however its a thought I'm toying with. as previously stated I am very basic with python and am working on learning so please forgive me if this a stupid question with a simple fix.
This line doesn't actually do anything. You need to assign the result to something.
ip.replace("x", ipend)
ipend is a string, incrementing a string won't work. Make it a int and convert it to a str in the replace function.
ipend += 1
And it's usually better to use a for loop if you can, so you're safe from messing up and creating a infinite loop.
for ipend in range(1,256): #Range won't actually give you the last number here.
#Do stuff