my program is simple, you enter your name, you select the desired amount of names youd like to enter and it prints out all the combinations... my only issue is not being able to add an if statement arount this couple lines of code so that the user wont be able to enter duplicate names or use any numbers in the name. i have tried a couple of things but i cant remember the exact code
names = []
for i in range(n):names.append(raw_input("Enter name "+str(i+1)+": "))
count = 0
def perm(a,k=0):
global count
if(k==len(a)):
print a
count += 1
else:
for i in xrange(k,len(a)):
a[k],a[i] = a[i],a[k]
perm(a, k+1)
a[k],a[i] = a[i],a[k]
my entire code can be found here if you'd like to paste it and run it, its kinda fun. in other words, if anyone could help me out just for the fact of where or how to achomplish this if/else statement, around the
(raw_input("Enter name "+str(i+1)+": "))
line of code. thank you all in advance
names = []
while len(names) < n:
name = raw_input("Enter name "+str(len(names)+1)+": ")
if validate_name(names, name):
names.append(name)
def validate_name(names, name):
return re.match("^[Sa-zA-Z]*$", name) and not name in names
Related
I'm "newish" to python programming. I'm trying my best to make my code look nice and function well. I'm using Pycharm as my IDE. I'm doing something for myself. I play tabletop RPG's and I'm attempting to create a character creator for a game I play. I have everything working well, but Pycharm is telling me that "Expression can be simplified" and "PEP 8: E712 comparison to True should be 'if cond is not True:' or 'if not cond:'"
Here is the code in question:
fname = False
while fname != True:
new_character.firstName = input('What would you like your first name to be?\n').capitalize()
if 1 >= len(new_character.firstName) or len(new_character.firstName) > 20:
print('Name does not meet length requirements. Please try again.')
if new_character.firstName.isalpha() != True:
print('Please do not use numbers or special characters in your name. Please try again.')
if (1 < len(new_character.firstName) < 20) and (new_character.firstName.isalpha() == True):
fname = True
Pycharm is telling me that my "while fname != True:" is the part that can be simplified as well as the "if new_character.firstName.isalpha() != True:".
I've tried googling a solution for what I'm doing, but most of them are for something kinda like what I'm asking, but never with the != True portion. I've even reached out to one of my friends that's a python programmer, but I haven't heard back yet.
Again, I want to state that as it is now, the code works correctly the way it is written, I'm just wanting to understand if there is a way to make the code look cleaner/neater or do the same function and be simplified somehow.
Any pointers on how to potentially simplify those lines of code and maintain the functionality would be greatly appreciated.
Here's one way you could rewrite this code to make it easier to read, and more efficient:
# Loop until the user provides a good input
while True:
# Set a temp variable, don't constantly reassign to the new_character.firstName attribute
name = input('What would you like your first name to be?\n').capitalize()
# If the name isn't between 2 and 20 characters, start the loop over at the beginning
if not (1 < len(name) <= 20):
print('Name does not meet length requirements. Please try again.')
continue
# If the name contains anything other than letters, start the loop over at the beginning
if not name.isalpha():
print('Please do not use numbers or special characters in your name. Please try again.')
continue
# You can only reach this break if the name "passed" the two checks above
break
# Finally, assign the character name
new_character.firstName = name
One thing you could do to simplify further is to check both conditions at the same time, and print a more helpful error message that re-states the requirements explicitly:
NAME_ERROR_MESSAGE = """
Invalid name '{name}'. Your character's name
must be between 2 and 20 characters long, and
contain only letters. Please try again.
"""
while True:
name = input('What would you like your first name to be?\n').capitalize()
if (1 < len(name) <= 20) and name.isalpha():
new_character.firstName = name
break
print(NAME_ERROR_MESSAGE.format(name=name)
My goal is to take two user inputs on a loop, save them in a dictionary, and when the user ends the loop, to have the save the dictionary.
# ------ Global Variables -------
user_cont = True
# ------- Functions -------
def get_Product():
while user_cont:
# get product code
get_ProductCode()
# get product number
get_ProductNum()
# save to dict
create_ProductDict()
# ask to continue
user_continue()
# save dict to file
def get_ProductCode(): works
def get_ProductNum(): works
def user_continue(): works but now is not getting prompted
What I'm currently trying to fix:
# save to dictionary
def create_ProductDict():
product_Dict = {}
productCode = get_ProductCode()
productNum = get_ProductNum()
print(product_Dict)
By my understanding on each loop, it should be receiving the returned productCode and productNum, and storing them? But now it won't ask the user to continue and end the loop so I can view the dictionary before I attempt to have the user save it.
In addition, I need to have the user choose a filename for the data.
As always, help is much appreciated!
There are two problems here. First issue is that your dictionary is being destroyed once the create_ProductDict() function ends, since the dictionary is created within the scope of the function.
One way to get around this would be to declare the dictionary in the global scope as a global variable. This way, the dictionary will persist as more items are added to it.
Next, your input variables currently aren't being used and the dictionary isn't being added to. The syntax for this is as follows:
productDict[productCode] = productNumber
So assuming that your input functions are equivalent to python's input() function, a solution that solves both of these issues would look something like this:
products = {}
def create_product_dict():
code = input("Enter Code: ")
num = input("Enter Number: ")
products[code] = num
create_product_dict()
create_product_dict()
print(products)
The output of this would be:
Enter Code: 123
Enter Number: 456
Enter Code: abc
Enter Number: 596
{'123': '456', 'abc': '596'}
Hope this is helpful :)
Try this:
def get_Product():
user_cont = True
while user_cont:
get_ProductCode()
get_ProductNum()
create_ProductDict()
user_cont = user_continue()
def user_continue():
ip = input('Enter Yes to Continue: ').lower()
return True if ip == 'yes' else False
Here is my finished main function after everything above pointed me in the direction I needed, but was not able to answer my questions entirely. My key finding was updating the dictionary before I asked to continue, and then adding the saving of the dictionary at the end. (The additional functions not included here as did not pertain to question/solution. Thank you!
user_cont = True
while user_cont:
# get product code
productCode = get_ProductCode()
# get product number
productNum = get_ProductNum()
# print(productCode, productNum)
# save to dict
products[productCode] = productNum
# debug to ensure dictionary was saving multi lines
# print(products)
# ask to continue
user_cont = user_continue()
for productCode, productNum in products.items():
formproducts = (productCode + ", " + productNum)
# print test
# print(formproducts)
# save dict to file
FILENAME = input(str("Please enter a file name: "))
file = open(FILENAME, "w")
file.write( str(products) )
file.close()
print("File saved.")
I'm trying to create an authorization process and it always says name unauthorized, despite the name not being assigned to the unauthorized variable.
I've tried different organization of the code, ie different order, but the problem hasn't improved.
Tessa=str
un = Tessa
n1=str
n2=str
input(n1("What is the name of player one?"))
if n1 == un:
print("Name unauthorised, try again")
else:
print ("Name authorised")
input(n2("What is the name of player two?"))
if n2 == un:
print("Name unauthorised, try again")
else:
print("Name authorised")
print("Welcome")
I expect any inputted name other than Tessa to result in the phrase "Name authorized" but instead it prints the unauthorized message."
I don't understand the statements n1 = str. Please check my code.
un = 'Tessa'
n1 = input("What is the name of player one?")
if n1 == un:
print("Name unauthorised, try again")
else:
print ("Name authorised")
n2 = input("What is the name of player two?")
if n2 == un:
print("Name unauthorised, try again")
else:
print("Name authorised")
print("Welcome")
and the result will be as below.
What is the name of player one? lam
Name authorised
What is the name of player two? rio
Name authorised
Welcome
you're clearly new to Python, so here are some things that you should fix:
Python doesn't need variables to have certain type. There is no need for what you were intending with n1 = str.
If you want to assign an actual string value, you can do so using quotes: "my string value".
If you want to do repeated checks, do it as part of a loop
If you want to store multiple values, use a list. (like for player names)
If you might have multiple values to check against (you might have multiple unauthorised names), use a list.
In light of these, consider the following code snippet:
unauthorised_names = ["Tessa"]
player_names = []
while len(player_names) < 2:
name = input("Please enter a name for player {}:".format(len(player_names) + 1))
if name in unauthorised_names:
print("Unauthorised name, please try again")
else:
player_names.append(name)
print(player_names)
Here unauthorised_names holds every name that cannot be entered. It can be one, it can be many.
player_names contain the names of the players.
You run it, until you got a sufficient number of valid player names, with the while loop
You take the input, with the number of the player as a parameter
Check it if it's on the list of invalid names, and store it, if it isn't.
Once you have the right number of names, you proceed with your program.
Try it for yourself!
To take an input and keep the value in n1, you need to do this:
n1 = str(input("What is the name of player one?"))
Also, I have no idea where you're going with the n1 = str, etc., so I suggest you scrap it.
So I am making a simple randomized number game, and I want to save the players High Score even after the program is shut down and ran again. I want the computer to be able to ask the player their name, search through the database of names in a text file, and pull up their high score. Then if their name is not there, create a name in the database. I am unsure on how to do that. I am a noob programmer and this is my second program. Any help would be appreciated.
Here is the Code for the random number game:
import random
import time
def getscore():
score = 0
return score
print(score)
def main(score):
number = random.randrange(1,5+1)
print("Your score is %s") %(score)
print("Please enter a number between 1 and 5")
user_number = int(raw_input(""))
if user_number == number:
print("Congrats!")
time.sleep(1)
print("Your number was %d, the computers number was also %d!") %(user_number,number)
score = score + 10
main(score)
elif user_number != number:
print("Sorry")
time.sleep(1)
print("Your number was %d, but the computers was %d.") %(user_number, number)
time.sleep(2)
print("Your total score was %d") %(score)
time.sleep(2)
getscore()
score = getscore()
main(score)
main(score)
EDIT:
I am trying this and it seems to be working, except, when I try to replace the string with a variable, it gives an error:
def writehs():
name = raw_input("Please enter your name")
a = open('scores.txt', 'w')
a.write(name: 05)
a.close()
def readhs():
f = open("test.txt", "r")
writehs()
readhs()
with open('out.txt', 'w') as output:
output.write(getscore())
Using with like this is the preferred way to work with files because it automatically handles file closure, even through exceptions.
Also, remember to fix your getscore() method so it doesn't always return 0. If you want it to print the score as well, put the print statement before the return.
In order to write a file using python do the following:
file2write=open("filename",'w')
file2write.write("here goes the data")
file2write.close()
If you want to read or append the file just change 'w' for 'r' or 'a' respectively
First of all you should ask your question clearly enough for others to understand.To add a text into text file you could always use the open built-in function.Do it like this.
>>> a = open('test.txt', 'w')
>>> a.write('theunixdisaster\t 05')
>>> a.close()
Thats all.If need further help try this website.
http://www.afterhoursprogramming.com/tutorial/Python/Writing-to-Files/
You could also use a for loop for the game to print all the scores.
Try this one on your own.It would rather be fun.
THE RECOMENDED WAY
Well as if the recommended way use it like this:
>>> with open('test.txt', 'w') as a:
a.write('theunixdisaster\t 05')
With this its certain that the file would close.
With variables
>>> name = sempron
>>> with open('test.txt', 'w') as a:
a.write('%s: 05' % name)
Now try calling it.Well I use python 3.4.2.So, if you get into errors, try to check if there is any difference in the string formatting with the python version that you use.
names = []
print("Duplicate names won't be in the list!") # reminder
while True:
userInput = input("Enter a name: ")
if userInput == "": # condition to terminate loop
print("You've entered these names, duplicated names won't be included")
print(names)
break
elif userInput not in names: # condition to see if input is duplicated
names.append(userInput) # if satisfied, adds it to the list
else:
print("value exists!") # reminder about the value entered is duplicate
That's my code so far, I don't know how could I count how many times a specific duplicate value was entered, a Dictionary will solve it a lot of people say but I am not too familiar yet with it. In the output, When the input of names is complete, the console user should be able to search the list for
names by simply typing the name at the console. The program should output either “Not
found” or display the name and the number of times it was entered.
When the searching is complete, the console user should be able to delete names from the list
by typing the name. If a name is not found, the program should output “Not found”. If a name
is found then it should be removed from the list and the name is displayed along with a
“Deleted” message to the user e.g. “Deleted Ted”.
Thank you very much to people that would help!
You should use a Counter.
c = Counter() #Initialize the counter
print("Duplicate names won't be in the list!")
while True:
userInput = input("Enter a name: ") #input used to be raw_input in Python 2
if userInput == "":
print("You've entered these names, duplicated names won't be included")
print(c.keys())
break
elif userInput not in c:
c.update([userInput]) # if satisfied, adds it to the counter. You have to provide a list, hence the [ ]. If you provide a string, it will be broke down into characters.
else:
print("value exists!")
In order to show a specific count,
print c[word]
You can also see the most common terms, etc.
However your code forbids that a name be entered more than once, but if you want to count the number of times people enter your name, this is the way to go.
A dictionary consists of a key and a value, a key in a dictionary should always be unique, so unless you have a unique key with every value you use, it wouldn't support duplicate values and will not suit your purposes.