Test function with multiple raw inputs from a user - python

I need to test a function, similar to below, to check the prompts, and output, from the function. As you can see, there is some branching. My ideal goal is to be able to specify the values I want to try in the function, but also capture all of the output text along the way.
def prompt():
guess = input("guess a letter: ")
return(guess)
def testme():
i = 1
vocab = ['a', 'b', 'c','d', 'e', 'f']
import random
correct = random.choice(vocab)
while i < 4:
i = i + 1
guess = prompt()
if correct == guess:
print("Well done!")
i = 100
else:
print("Wrong!\n")
testme()
My need:
It's worth noting that you can see my function test intentionally does not take any arguments, but rather, is a function where the user has to interface with the prompts. I need to automate this part, and capture how the function reacts (the messages sent to the console) until the function ends.
I am trying to avoid manually running through this by hand to see if the function behaves the way I expect given the fact that the user can provide multiple inputs.

You can just take an argument and pass the list to it:
def testme(vocab):
i = 1
import random
correct = random.choice(vocab)
while i < 4:
i = i + 1
guess = prompt()
if correct == guess:
print("Well done!")
i = 100
else:
print("Wrong!\n")
And call it like:
testme(['a','b','c','d','e','f'])
Also you can take comma delimited values from user, split them and convert to list and pass to the function.

What do you mean by capturing the output? Do you want to save what the user typed? Do you want to see how many guesses it took?
I think you could take a look at the for loop and the break statement :) they will make your work easier
def prompt():
guess = input("guess a letter: ")
return(guess)
def testme(vocab):
import random
correct = random.choice(vocab)
for i in range(4):
guess = prompt()
if correct == guess:
print("Well done!")
break
else:
print("Wrong!\n")
return my_list_of_outputs
testme(['a','b','c','d','e','f'])

Related

How to avoid my program stopping because of a invalid index number when calling a tuple

I'm trying to make a pokémon text based journey in python.
I listed the starter pokémon in a tuple to call the number that the user typed in the input to then store the chosen starter pokémon.
It all works but when the user would type a different integer then availabe in the tuple, for example: writing 5 while there are only 3 indexs in the tuple. The program just stops when this happens.
Is there a way for me to just tell the program to not go into debugging mode when this happens; and recalling the "ChoseStarter" function instead?
Here is the code:
if(ChosenPok == 1,ChosenPok == 2,ChosenPok == 3):
ChosenPokInt = int(ChosenPok)
StarterPok = Starter[ChosenPokInt-1] #Here is the problem
Sure = f"You chose {StarterPok} are you sure? (y/n)"
YORN = input(Sure)
if(YORN == "Y" or YORN == "y"):
Congrats = f"Congratulations!! You just got a {StarterPok}!!"
WriteFast(Congrats)
print(Starter[ChosenPokInt-1])
else:
WriteFast(ERROR)
ChoseStarter()
No idea what the question is about or what logic you want to implement. See if the below code helps though. Seems like the "if condition" is buggy in your case. The following code repeatedly asks for the correct input using a while loop. Replace the while loop with an if statement if you don't want that.
starter = ["x", "y", "z"]
chosen_pok = int(input("Select a pok: "))
while not (1 < chosen_pok < 4):
print("Invalid pok. try again...")
chosen_pok = int(input("Select a pok: "))
starter_pok = starter[chosen_pok - 1]
yorn = input(f"You chose {starter_pok} are you sure? (y/n)")
if (yorn in ["Y", "y"]):
print(starter[chosen_pok - 1])
else:
print("Error")
You should just check for the len and if ChosenPokInt is in it's boundaries:
pokemon_index = ChosenPokInt - 1
if 0 <= pokemon_index < len(Starter)-1:
# everything is fine
else:
# handle the problem case
Besides that I advice you to look into pep8 :). You can find an awesome guide here: https://pep8.org
You can add a while loop before the condition that checks first if the input is in the correct range:
ChosenPok = ChoseStarter()
pokRange = [1, 2, 3]
while not (ChosenPok in pokRange):
print("Wrong input, try again")
ChosenPok = ChoseStarter()

How to display an integer many times

I'd like to create a function that add 2 to an integer as much as we want. It would look like that:
>>> n = 3
>>> add_two(n)
Would you like to add a two to n ? Yes
The new n is 5
Would you like to add a two to n ? Yes
the new n is 7
Would you like to add a two to n ? No
Can anyone help me please ? I don't how I can print the sentence without recalling the function.
The idea is to use a while loop within your function that continues to add two each time you tell it to. Otherwise, it exits.
Given that knowledge, I'd suggest trying it yourself first but I'll provide a solution below that you can compare yours against.
That solution could be as simple as:
while input("Would you like to add a two to n ?") == "Yes":
n += 2
print(f"the new n is {n}")
But, since I rarely miss an opportunity to improve on code, I'll provide a more sophisticated solution as well, with the following differences:
It prints the starting number before anything else;
It allows an arbitrary number to be added, defaulting to two if none provided;
The output text is slightly more human-friendly;
It requires a yes or no answer (actually anything starting with upper or lower-case y or n will do, everything else is ignored and the question is re-asked).
def add_two(number, delta = 2):
print(f"The initial number is {number}")
# Loop forever, relying on break to finish adding.
while True:
# Ensure responses are yes or no only (first letter, any case).
response = ""
while response not in ["y", "n"]:
response = input(f"Would you like to add {delta} to the number? ")[:1].lower()
# Finish up if 'no' selected.
if response == "n":
break
# Otherwise, add value, print it, and continue.
number += delta
print(f"The new number is {number}")
# Incredibly basic/deficient test harness :-)
add_two(2)
You can use looping in your add_two() function. So, your function can print the sentence without recalling the function.
The above answer describes in detail what to do and why, if you're looking for very simple beginner-type code that covers your requirements, try this:
n = 3
while True:
inp = input("Would you like to add 2 to n? Enter 'yes'/'no'. To exit, type 'end' ")
if inp == "yes":
n = n + 2
elif inp == "no":
None
elif inp == "end": # if the user wants to exit the loop
break
else:
print("Error in input") # simple input error handling
print("The new n is: ", n)
You can wrap it in a function. The function breaks once the yes condition is not met
def addd(n):
while n:
inp = input('would like to add 2 to n:' )
if inp.lower() == 'yes':
n = n + 2
print(f'The new n is {n}')
else:
return
addd(10)

[Random String Generator]Getting stuck in a loop on else condition

So (as you will probably see from my code) I am a beginner at Python (version 3.8.3) and enjoying it very much so far, and I have challenged myself on several different beginner projects. I am currently making a random string generator (i.e. a password generator, hence the use of the secrets module).
# Password Generator
import secrets, string
print("Welcome to the generator. Please specify your requirements")
print("A. All Characters;\nB. No Numbers;\nC. No Punctuation\nPlease choose the appropriate letter for your needs.")
userInput = input()
def userWelcome():
if userInput.lower() == "a":
generatePass = string.ascii_letters + string.digits + string.punctuation
print("How long do you want your string to be?")
stringRange = int(input())
print( "".join(secrets.choice(generatePass) for _ in range(stringRange)) )
elif userInput.lower() == "b":
generatePass = string.ascii_letters + string.punctuation
print("How long do you want your string to be?")
stringRange = int(input())
print("".join(secrets.choice(generatePass) for _ in range(stringRange)))
elif userInput.lower() == "c":
generatePass = string.ascii_letters + string.digits
print("How long do you want your string to be?")
stringRange = int(input())
print("".join(secrets.choice(generatePass) for _ in range(stringRange)))
else:
print("Not an option! Let's try again.")
userWelcome()
userWelcome()
However, my problem is what to do if the user inputs an incorrect option. As you can see, with the else statement I assume what they filled in does not match any of the earlier options - and so I want to try to rerun the generator again (so I try to call userWelcome again in the else statement).
However, when I type in for example 12 as input, my shell starts to output my string (Not an option Let's try again) literally a thousand times like it is stuck in a loop. I am wondering what I am doing wrong exactly.
What I have tried:
(1) So I have tried to solve this input problem first with try and except, running the except when there is a ValueError but that only works for numbers and I did not manage to rerun userWelcome()
(2) I have tried to create a elif statement in which I check the input for integers, however that also gets stuck in a loop. Code:
elif userInput.isalpha() == False:
print("Not an option! Let's try again.")
userWelcome()
Anyway, I hope that explains it well. I have been busy with this for a few hours now and I thought I'd ask this. Maybe it's a very stupid question but for me it's hard :)
TL;DR: Want to check for proper user input by running my function again, get stuck in weird loop
Thank you for your time and effort!
The code calls userWelcome() recursively, without changing the global variable userInput. The same bad string is processed again, causing the same result, which again calls userWelcome() - for ever (at least until max call depth).
You should read a new string at the beginning of userWelcome, instead of using a global variable. Also, recursion here is an overkill that confuses you. Better use a simple while loop:
while True:
userInput = ....
if ....
do something
return
elif ...
do something else
return # exit the function - breaking out of the loop
else:
print(error message)
# No return here, means the loop will continue to loop
If you want to call the function instead of loop inside, you can instead make the function return success (True) vs. failure (False), and loop that in the caller:
while not userWelcome(inputString):
inputString = read the string
def userWelcome(inputString):
if inputString == ....:
something
return True # To mark OK
elif inputString == .....:
something else
return True # To mark OK
else:
print an error
return False # To mark failure
Just avoid global variables, it is a bad practice. Pass the value through parameters, as in the code above.

Trying to locate syntax error in python while loop

very very new beginner here - just started learning today! stumped on what the syntax error is here:
import random
x = random.randrange(7)
user_start = "yes"
user_start_input = str(input("type 'yes' to generate random number. "))
while user_start_input == user_input:
print("your random dice number is " + str(x))
user_start_input = input("roll again?")
if user_start_input != user_input:
break
print("done")
The error message is:
File "/Users/joel/Documents/Learning Python/Dice.py", line 12
while user_start_input == user_input:
^
SyntaxError: invalid syntax
what am I doing wrong?
First off we're (those that wish to answer) missing some information, while is on line 5 where as the error is being reported with while on line 12, there's plenty that could be causing an error to pop on a following line; eg. missing quote. Looks like G. Anderson already eluded to that last point, as far as errors usually being from a preceding line. My suggestion in this case would be to find an developer friendly text editor (IDE) that'll point out minor typos through syntax-highlighting; Atom is pretty groovy, especially with a few addons, but there's plenty of other text editors to play with.
Second, as commented by CoffeeTableEspresso the tabs are non-existent in your code snip! If your source code looks identical to what has been posted, then your bug-stomping has only just begun.
Third, because ya had stated that Python is not your first language it might be helpful, if not now then certainly in the future, to know of __doc__ strings, eg...
>>> print(random.randrange.__doc__)
Choose a random item from range(start, stop[, step]).
This fixes the problem with randint() which includes the
endpoint; in Python this is usually not what you want.
... many of the things within Python are documented and accessible via the __doc__ method, which can also be accessed with help(), eg. help(random.randrange), and it is possible to write your own with the following syntax...
def test_func(arg):
"""
This is a __doc__ string
"""
print("arg -> {0}".format(arg))
And finally, well for now, it's a good idea when writing in an unfamiliar language to use copious comments and split things up into smaller bits that express your intentions; for example...
#!/usr/bin/env python
import random
def dice(sides = 6):
"""
Returns random int between `1` and `sides`
"""
return random.randrange(start = 1, stop = int(sides) + 1, step = 1)
def prompt(message, expected):
"""
Returns `True` if user input matches `expected`
"""
return expected == str(input("{0} ".format(message)))
def main_loop():
"""
Returns list of `dice(...)` results, list length depends
upon number of times `prompt(...)` returns `True`
"""
roll_results = []
user_start = 'yes'
# Set message for first run of loop
message = "Type '{0}' to roll the dice".format(user_start)
while prompt(message = message, expected = user_start):
# Save dice output to variable for later use and
# append to list of rolls that will be returned
roll = dice(sides = 6)
roll_results.append(roll)
# For now just print each roll, but this is one
# aria to expand upon with your own edits
print("Rolled {0}".format(roll))
# Set new message line for following loop iterations
message = 'Roll again?'
return roll_results
# Do stuff if script is run directly instead of imported as a module
if __name__ == '__main__':
main_loop()
P.S. keep at it, eventually all the learnings'll start to click and the following RP related example classes will make more since...
#!/usr/bin/env python
from __future__ import range
import random
class DiceBag(dict):
"""
DiceBag is a collection of short-cuts to `random.randrange`.
- `selection`, list of `n` sided dice, eg `[4, 20]` would _stock_ bag with d4 and d20
"""
def __init__(self, selection = [2, 4, 20], **kwargs):
super(DiceBag, self).__init__(**kwargs)
self.update(selection = selection)
def dice(self, sides = 6):
"""
Returns random int between `1` and `sides`
"""
return random.randrange(start = 1, stop = int(sides) + 1, step = 1)
def handfull_of(self, dice = {}):
"""
Returns `dict` with lists of dice rolls
## Example
dice_bag = DiceBag()
toss_results = dice_bag.handfull_of({20: 1, 4: 2})
Should return results of one `d20` and two `d4` such as
{
20: [18],
4: [1, 3]
}
"""
output = {}
for sides, count in dice.items():
if sides not in self['selection']:
continue
rolls = []
for roll in range(count):
rolls.append(self.dice(sides))
output[sides] = rolls
if not output:
raise ValueError("No dice in bag matching sizes -> {0}".format(dice.keys()))
return output
"""
Short cuts for dice of a `n` sides, expand upon it if you wish
"""
#property
def coin(self):
return self.dice(sides = 1)
#property
def d4(self):
return self.dice(sides = 4)
#property
def d6(self):
return self.dice(sides = 6)
class Flail(DiceBag):
def __init__(self, damage_modifier = 0, damage_dice = {'sides': 6, 'count': 2}, **kwargs):
super(Flail, self).__init__(selection = [damage_dice['sides'], 20], **kwargs)
self.update(damage_modifier = damage_modifier)
self.update(damage_dice = damage_dice)
def attack(self, attack_modifier = 0):
"""
Returns `dict` with `hit` chance + `attack_modifier`
and `damage` rolls + `self['damage_modifier']`
"""
rolls = self.handfull_of(dice = {
20: 1,
self['damage_dice']['sides']: self['damage_dice']['count']
})
return {
'hit': rolls[20][0] + attack_modifier,
'damage': sum(rolls[self['damage_dice']['sides']]) + self['damage_modifier']
}
Updates
Here's what your code block may look like with proper indentation...
import random
x = random.randrange(7)
user_start = "yes"
user_start_input = input("type 'yes' to generate random number. ")
while user_start_input == user_input:
print("your random dice number is " + str(x))
user_start_input = input("roll again?")
print("done")
... and here's what a working version might look like...
import random
message = "type 'yes' to generate random number. "
expected = "yes"
while input(message) == expected:
x = random.randrange(7)
print("your random dice number is {num}".format(num = x))
message = "roll again? "
print("done")
... there's little reason to use an if something break when using while to do the same kinda thing, well given the current question's code sample.
Moving the assignment of x to be within the loop ensures that there's a chance of a new number on each iteration, while not stated I've a feeling that that was your intent.
Using input(message) and updating the message displayed instead hopefully makes sense. Though I'm not sure why you where wrapping things within str(), didn't seem to make a bit of difference when I tested.
First, it seems like you've mixed up the two variable names user_start and user_input, so those need to be changed to the same variable name.
Next, Python structures code with indentation: so the content in while loops and the like would need to be indented.
So here, you would indent all the code inside the while loop, and further indent the code inside the if statement inside the while loop.
It also seems like the purpose of your code is to simulate a dice roll each time the while loop runs again. In the while loop, you call on the variable x for the dice roll, but x is never changed. You never changed x to be a different random number, so it will just show the same random number every time the user rolls the dice again.
To fix this, simply re-define x each time the while loop is run. So just move the definition of the variable x to within the while loop.
With all these fixes, the code works:
import random
user_start = "yes"
user_start_input = str(input("type 'yes' to generate random number. "))
while user_start_input == user_start:
x = random.randrange(7)
print("your random dice number is " + str(x))
user_start_input = input("roll again?")
if user_start_input != user_start:
break
print("done")
Of course the variable names could be a bit more informative, and the code could be structured better to improve performance and user friendliness, but overall, great job for a beginner!

Faulty Random Password Generator (Python 3)

I am beginning to learn Python and started experimenting with an example code block. I edited it a few times, and on the last edit that I did, I added an optional random password generator. Then I decided that it would make more sense to put the password generator into a separate document, so I copied the necessary code and made a new document. After editing it however, I cannot generate an even number of digits in the password.
Pastebin
Copy of Faulty Code (Pastebin)
import math
import random
alpha = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
print('Would you like a random password suggestion generator', 'Yes or No')
permissionRandomGenerator = input().lower()
print('How long do you want your password?')
lengthRandomGenerator = int(input())
if permissionRandomGenerator == 'yes':
def randInt():
return math.floor(random.random()*10)
def randChar():
return alpha[math.floor(random.random()*27)]
randPasswordList = []
listInsert = 0
def changeCase(f):
g = round(random.random())
if g == 0:
return f.lower()
elif g == 1:
return f.upper()
while listInsert < lengthRandomGenerator:
randPasswordList.insert(listInsert, randInt())
listInsert = listInsert + 1
if listInsert >= lengthRandomGenerator:
break
randPasswordList.insert(listInsert, randChar())
randPasswordList[listInsert] = changeCase(randPasswordList[listInsert])
listInsert = listInsert + 1
continue
listInsert = 0
printList = 0
if lengthRandomGenerator <= 0:
print('It has to be longer than that')
elif lengthRandomGenerator >= 25:
print('I can\'t generate a password that long')
elif math.isnan(lengthRandomGenerator):
print('error: not valid data type')
else:
while printList < (len(randPasswordList)-1):
printItem = randPasswordList[printList]
print(printItem)
printList = printList + 1
printList = 0
randPasswordList = []
elif permissionRandomGenerator == 'no':
print('Too bad...')
else:
print('You had to answer Yes or No')
I refactored your program a bit, and got rid of a lot of unnecessary steps and inconsistencies. Here it is in full, then I'll explain each part:
import random
import string
import sys
possible_chars = string.ascii_letters + string.digits + string.punctuation
def nextchar(chars):
return random.choice(chars)
yes_or_no = input("""
Would you like a random password suggestion generated?
Type Yes to continue: """).lower()
if yes_or_no == 'yes':
try:
pwd_len = int(input('How long do you want your password? '))
except ValueError:
sys.exit("You need to enter an integer. Please start the program over.")
if 0 < pwd_len < 26:
new_pwd = ""
for _ in range(pwd_len):
new_pwd += nextchar(possible_chars)
print("Your new password is:\n" + new_pwd)
else:
print("I can only generate passwords between 1 and 25 characters long.")
else:
print("Well then, why did you run me?")
Python is not just the syntax and builtin functions, it is also the standard library or stdlib. You're going to be working with the stdlib's modules all the time, so when you think you'll be using one, read the docs! You'll learn about the module, what its intended use is, some of its history and changes (such as in which version a certain function was added), and all of the classes, functions, and attributes contained therein. Make sure you read the whole thing (none of them are that long) and try to get at least a basic idea of what each thing does. That way, such as in this case, you'll be able to pick the best function for the job. One thing I like to do in my spare time is just pick a random module and read the docs, just to learn. They're generally fairly well written, and usually pretty inclusive. Get used to Monty Python references, they're everywhere.
import random
import string
import sys
Imports are first, and should almost always be only at the top. I like to put mine in alphabetical order, with the stdlib on top, then a blank line, then 3rd-party modules, including self-written ones next. Put a blank line or two after the imports as well. One thing to remember, that I mentioned in the comments: readability counts. Code is not only meant to be read by machines, but by people as well. Comment when necessary. Be generous with whitespace (also remember that whitespace is syntactically important in Python as well, so it forces you to indent properly) to separate related bits of code, functions, classes, blocks, etc. I highly recommend reading, rereading, and spending time pondering PEP-8, the Python style guide. Its recommendations aren't absolute, but many projects that enforce coding standards rely on it. Try to follow it as much as you can. If a line comes out to 83 characters, don't sweat it, but be aware of what you're doing.
The reason I made such a big deal out of reading the docs is the following few lines:
possible_chars = string.ascii_letters + string.digits + string.punctuation
def nextchar(chars):
return random.choice(chars)
They get rid of about half of your code. string contains a bunch of predefined constants for working with strings. The three I chose should all be good valid password characters. If you're on a system that won't take punctuation marks, just remove it. Note that possible_chars is a string - like tuples, lists and dicts, strings are iterable, so you don't need to make a separate list of each individual possible character.
Next is the function - it replaces your randInt(), randChar(), and changeCase() functions, along with a bunch of your inline code, which was rather bizarre, to tell you the truth. I liked the method you came up with to decide if a letter was upper- or lower-case, but the rest of it was just way too much effort when you have random.choice() and the string constants from above.
yes_or_no = input("""
Would you like a random password suggestion generated?
Type Yes to continue: """).lower()
You may not have been aware, but you don't need to print() a description string before getting user input() - just pass the string as a single argument to input() and you'll get the same effect. I also used a triple-quoted """ (''' can also be used) string literal that differs from the more common single- ' and double-quoted " string literals in that any newlines or tabs contained within it don't need to be escaped. The take-home for now is that you can write several lines of text, and when you print() it, it will come out as several lines.
try:
pwd_len = int(input('How long do you want your password? '))
except ValueError:
sys.exit("You need to enter an integer. Please start the program over.")
I used a try/except block for the next part. If the user enters a non-integer up at the input prompt, the int() function will fail with a ValueError. I picked the simplest manner possible of dealing with it: if there's an error, print a message and quit. You can make it so that the program will re-ask for input if an error is raised, but I figured that was beyond the scope of this exercise.
if 0 < pwd_len < 26:
new_pwd = ""
for _ in range(pwd_len):
new_pwd += nextchar(possible_chars)
print("Your new password is:\n" + new_pwd)
else:
print("I can only generate passwords between 1 and 25 characters long.")
Here is where all the action happens. Using an if/else block, we test the desired length of the password, and if it's between 1 and 25 (an arbitrary upper bound), we generate the password. This is done with a for loop and the range() function (read the docs for exactly how it works). You'll notice that I use a common Python idiom in the for loop: since I don't actually need the number generated by range(), I "throw it away" by using the underscore _ character in place of a variable. Finally, the else statement handles the alternative - either pwd_len is 0 or less, or 26 or greater.
else:
print("Well then, why did you run me?")
We're at the end of the program! This else is paired with the if yes_or_no == 'yes': statement - the user entered something other than yes at the input prompt.
Hopefully this will help you understand a little bit more about how Python works and how to program efficiently using it. If you feel like you're spending a bit too much time implementing something that you think should be easier, you're probably right. One of Python's many advantages is its "batteries included" philosophy - there's a huge range of things you can do with the stdlib.
I made some small edits, and my code seems to be working now. Here is the finished product (I put comments to show what the code does, and also to mark the edits.):
import math
import random #Import necessary modules
alpha = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] #List with alphabet
print('Would you like a random password suggestion generator', 'Yes or No') #Prints the question for permission
permissionRandomGenerator = input().lower() #Stores the answer of the above question in lower case
if permissionRandomGenerator == 'yes': #Generates a password if the answer of the first question is 'yes'
print('How long do you want your password?') #Asks for length
lengthRandomGenerator = int(input()) #Stores length as an integer
def randInt(): #Creates a random integer
return math.floor(random.random()*10)
def randChar(): #Selects a random string from the list with the alphabet
return alpha[math.floor(random.random()*27) - 1]
randPasswordList = [] #Creates a list to store the password
listInsert = 0 #Creates a list index variable
def changeCase(f): #Defines a function to randomly change the case of letters before adding them to the list randPasswordList
g = round(random.random())
if g == 0:
return f.lower()
elif g == 1:
return f.upper()
while listInsert < lengthRandomGenerator + 1: #Creates a random password and inserts it into randPasswordList (I added `+ 1` here)
randPasswordList.insert(listInsert, randInt())
listInsert = listInsert + 1
if listInsert >= lengthRandomGenerator:
break
randPasswordList.insert(listInsert, randChar())
randPasswordList[listInsert] = changeCase(randPasswordList[listInsert]) #Calls the changeCase function whenever it inserts a letter
listInsert = listInsert + 1
continue
listInsert = 0
printList = 0
if lengthRandomGenerator <= 0: #If the length it 0 or less (for example, negatives) the password will not generate (I need to fix this a little bit. Currently the code attempts to create a password beforehand)
print('It has to be longer than that')
elif lengthRandomGenerator >= 25:
print('I can\'t generate a password that long')
elif math.isnan(lengthRandomGenerator): #Currently this doesn't do anything, it needs to be moved farther forward
print('error: not valid data type')
else:
while printList < (len(randPasswordList)-1): #Prints the list item by item
printItem = randPasswordList[printList]
print(printItem)
printList = printList + 1
printList = 0 #Resets the variables
randPasswordList = []
elif permissionRandomGenerator == 'no':
print('Too bad...')
else:
print('You had to answer Yes or No')
Note: I made this code purely to experiment and better learn basic aspects of Python. This code is not optimized, and is also not as random as I can (and will) make it.
P.S. Sorry if the comments are incomplete, I am still learning this language.
I don't know why you are doing over complicated for this simple problem, you can just use the constant provided by the string object, I would rather have the following programs to generate random password
import random, sys, string
def pgen(length=8):
if length < 8:
length = 8
keys = list(string.printable[:-6])
random.shuffle(keys)
return ''.join(keys)[:length]
if __name__ == '__main__':
try:
print( pgen(int(sys.argv[1])))
except Exception as e:
print("Provide length of password \n passwordgen.py <length_of_password>")
Outputs
magautam#nix1947:/tmp$ python passwordgen.py 12
HNLxi!{.qe=b
magautam#nix1947:/tmp$ python passwordgen.py 45
}w5u?+C=e[DfI.n'*1G(m{r0FH|UBKz/#kL>;Sh`tEW8-

Categories

Resources