I have some code, which I will rather not share but this a portion
try_again = input ("Try again?")
if answer == "Y" or answer == "y":
clear()
file_path = os.path.dirname(os.path.realpath(__file__))
open file_path + "maze_game.exe"
exit()
else:
exit()
I want the file to open itself (to start at the beginning) I have tested it and it DOES work but, if the user renames the file (unlikely but possable) clearly this wont work unless they decompile, edit, and recompile. so I want to get the name of itself, store that in a variabe and open like this:
file_name = how ever I get the name
try_again = input ("Try again?")
if answer == "Y" or answer == "y":
clear()
file_path = os.path.dirname(os.path.realpath(__file__))
open file_path + file_name
exit()
else:
exit()
so how might I get the file name?
EDIT: here is my whole code:
import os
import time
clear = lambda: os.system('cls')
name = input ("What is your name? ")
friend = "Charels"
if name == "Charels" or name == "charels" or name == "Charles" or name == "charles":
friend = "Chuck"
print ("Welcome to the Maze Game Dr. " + name)
time.sleep(1.5)
clear()
print ("No one has made it out of Colwoods' labrynth,\nhowever there are rumours of untold riches at the end. \nThe most recent victim of the Maze is your best friend, " + friend)
time.sleep(1.5)
clear()
print ("Are you sure you want to continue?")
answer = input ("Y or N? ")
if answer == "Y" or answer == "y":
("")
else:
friend = friend + " for dead. R.I.P."
print ("Shame on you, you left " + friend)
time.sleep(1.5)
clear()
print ("YOU LOSE")
time.sleep(1.5)
clear()
file_name = how ever I get the name
try_again = input ("Try again?")
if answer == "Y" or answer == "y":
clear()
file_path = os.path.dirname(os.path.realpath(__file__))
open file_path + file_name
exit()
else:
exit()
input ("...")
no, the program is not completed and ignore the last line
Maybe I am misunderstanding what you want, but I think os.path.basename(__file__) will do the trick.
This will give you just the file part of your path, so if you have a filefoo/bar/baz.py and pass that path like os.path.basename('foo/bar/baz.py'), it will return the string 'baz.py'.
So try:
file_name = os.path.basename(__file__)
That being said, your approach seems a little atypical as #Blender points out, and I have never tried to have a program restart itself in this way. I am not sure if this answer will make your program work correctly, but it will give you the name of the file that is running your program, which seems to be what you are looking for.
Related
def your_advntur() :
afdfdf="ff"
start = input("do you want to play ?\n")
a = "-deep voice:"
while start != "yes" :
if start == "no":
quit()
else:
start = input("pleas answer with yes or no:\n")
name = input(a+" hello adventurer tell me your name.\n-adventurer: my name is ")
path1 = input(a + name+" you found your self in jungle facing a lake without any memory this
is your story"
"\nyou can \"cross it\" or \"walk around it\" or \"head back\" what do you want to do
?\n-"+name+":")
if path1 == "cross the lake" :
print("brave adventurer which face his problems directly \n"
"i like it but infurtchn you have been eaten by an aligator\n GAME OVER")
your_advntur()
while True:
response = input("wanna play again?")
if response == "yes":
your_advntur()
else:
break
t tried this but it didnt work i want the game to restart after the user typing yes and close after no and reask the if you want to replay q if the user typed anthor thing
def add(fm_list):
while True:
msg = input("What do you want to create?: "
"\n Insert 1 for Folder "
"\n Insert 2 for Subfolder.\n")
if msg == "1":
folder = input("Name of the folder: ")
choice = input("Do you want to add a subfolder to this folder?: (y/n): ")
if choice.lower() == "y":
# ... do things ...
break
elif choice == "n":
# ... do things ...
break
else:
print("Please choose between (y/n)\n")
elif msg == "2":
store = input("Where do you want to store your subfolder?: "
"\n Insert A to store it in the DEFAULT folder"
"\n Insert B to store it in a new folder\n")
if store.lower() == "a":
# do things ...
break
elif store.lower() == "b":
# do things ...
break
else:
print("Invalid entry!!!\n")
continue
Thanks in advance for the answers.
I have my function add() here, I would like when I hit the stage of the elif msg == 2... when the user inputs anything else other than the available options (a or b) then he gets prompt back to choose the appropriate option (In other words, I give the hand again and ask the user where to store the subfolder) ... instead it does prompt back at the beginning of the code.
msg = input("What do you want to create?: "
"\n Insert 1 for Folder "
"\n Insert 2 for Subfolder.\n")
...Thanks
Well after some time and some help I finally get to do what I wanted
we created a recursive function (not sure if this is it is called tho) then call it back later on the add function:....
def getstore(fm_list):
store = input("Where do you want to store your subfolder?: "
"\n Insert A to store it in the DEFAULT folder"
"\n Insert B to store it in a new folder\n")
if store.lower() == "a":
subfolder = input("What is the name of the subfolder: ")
fm_list.append(subfolder)
print("Your subfolder will be store to the Default folder: ")
os.chdir('F:\\Test\\Default') # this is the Default folder already in the test directory
os.makedirs(subfolder, exist_ok=True)
print(subfolder + " was added to the folder named Default")
quit()
elif store.lower() == "b":
folder = input("Name of the folder: ")
fm_list.append(folder)
os.chdir('F:\\Test')
os.makedirs(folder, exist_ok=True)
subfolder = input("Name of the subfolder: ")
fm_list.append(subfolder)
os.chdir('F:\\Test\\' + folder)
os.makedirs(subfolder, exist_ok=True)
print(folder + " was added to the list of folder.")
print(subfolder + " was added to " + folder)
quit()
else:
getstore(fm_list)
then later when we get to the elif msg == "2" we call getstore(fm_list)
just like this...
elif msg == "2":
getstore(fm_list)
break
else:
print("Invalid entry!!!\n")
continue
And that's it.
Very beginner programmer here in the process of learning. I am just wondering if this simple code I have typed is the most optimal way to do it.
with open('guest_book.txt', 'a') as file_object:
while True:
name=input("What is your name?")
print("Welcome " + name + ", have a nice day!")
file_object.write(name + " has visited! \n")
another = input("Do you need to add another name?(Y/N)")
if another == "y":
continue
elif another == "n":
break
else:
print("That was not a proper input!")
while True:
another = input("Do you need to add another name?(Y/N)")
if another == "y":
a = "t"
break
if another == "n":
a = "f"
break
if a == "t":
continue
else:
break
My questions is in the if statements. When I ask the input("Do you need to add another name?(y/n)", is what I have typed the best way to re-ask the question if I get an answer other than y or n. Basically I want the question to be repeated if I don't get either a yes or no answer, and the solution I found does not seem like the most optimal solution.
You are basically there. You can simply:
with open('guest_book.txt', 'a') as file_object:
while True:
name=input("What is your name?")
print("Welcome " + name + ", have a nice day!")
file_object.write(name + " has visited! \n")
another = input("Do you need to add another name?(Y/N)")
if another == "y":
continue
elif another == "n":
break
else:
print("That was not a proper input!")
continue
You can use function to write your all logic at one place.
def calculate(file_object):
name=raw_input("What is your name?")
print("Welcome " + name + ", have a nice day!")
file_object.write(name + " has visited! \n")
another = raw_input("Do you need to add another name?(Y/N)")
if another == "y":
calculate(file_object)
elif another == "n":
return
else:
print("That was not a proper input!")
calculate(file_object)
if __name__=='__main__':
with open('guest_book.txt', 'a') as file_object:
calculate(file_object)
You can do it this way, but there will not be any invalid input for saying no. It will only check for saying y
with open('guest_book.txt', 'a') as file_object:
another = 'y'
while another.lower() == 'y':
name=input("What is your name?")
print("Welcome " + name + ", have a nice day!")
another = input("Do you need to add another name?(Y/N)")
hello i have my code for a random maths quiz and i want it to save the name and there score next to the file and i want it to keep the data and not write over it every time could someone please help me and add this in i would like it so it could reocrd it like this let say i played it i would like the file to be like this then if someone else took the quiz it just adds there name to the list not erase the list first
name score
def quiz():
import random
import time
name=input("What is your name?")
print ("Alright",name,"Welcome to your maths quiz")
score=0
question=0
for question in range (1,11):
ops=['*','+','-']
rand=random.randint(1,10)
rand2=random.randint(1,10)
operation=random.choice(ops)
maths = eval(str(rand) + operation + str(rand2))
print ("Question",question)
time.sleep(0.5)
print (rand,operation,rand2)
question=question+1
d=int(input ("What is your answer:"))
if d==maths:
print ("Correct")
score=score+1
else:
print ("Incorrect. The actual answer is",maths)
if score >=7:
print ("Well done you got",score,"out of 10")
else:
print ("Unlucky you got",score,"out of 10")
percentage=score/10*100
print ("You got",percentage,"%")
f = open('results.txt','w')
f.write('%d' % score)
f.close()
playagain = 'yes'
while playagain == 'yes':
quiz()
print('Do you want to play again? (yes or no)')
playagain = input()
Change
f = open('results.txt','w')
to
f = open('results.txt','a')
Read the python docs for File I/O. 'w' overwrites an existing file
if you want the name with the score
f.write('{} : {}\n'.format(name, score) )
I'm a beginner to Python, and am having problems with a function. I am making a program in which I have many parameters for the user to choose from and I need to allow them to confirm or deny their choices. Here is a simplified code section that represents my issue.
my code:
def confirm(function):
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
break
elif answer == 'no':
return function() # if the user wants to change their name, recall function
else:
continue # to reprompt user if the answer is not "yes" or "no"
def your_name():
while True:
name = raw_input("What is your name? ")
if not name:
continue # to reprompt user if they do not enter anything
else:
confirm(your_name)
print 'Congratulations! You have a name!'
break
your_name()
When running this program, it will print the congratulatory string the same amount of times that answer received an input.
my output:
What is your name? Bastion
Are you sure? no
What is your name? Artex
Are you sure? no
What is your name? Falcor
Are you sure? yes
Congratulations! You have a name!
Congratulations! You have a name!
Congratulations! You have a name!
My intention is for the congratulatory message to be printed just one time. How can I edit my function(s) in order to achieve this?
What I've tried:
I have attempted all of these, using the exact same input values I used in my output block above.
Within the section of confirm(function) that says:
if answer == 'no':
return function()
I've tried changing it to:
if answer == 'no':
function()
In the output, this will ask for the answer raw_input 3 times, posting the congratulatory message after each input. If I write the code in this way:
if answer == 'no':
print function()
It will print the congratulatory response 3 times and print None on a separate line below for each time. I am looking for an elegant, clean format so this will not do.
So your problem is you are creating a kind of recursive function without meaning to, you don't need to pass the function to be called again as you are already inside the function. I would suggest the following:
def confirm():
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
return True
if answer == 'no':
return False
else:
continue # to reprompt user if the answer is not "yes" or "no"
def your_name():
while True:
name = raw_input("What is your name? ")
if not name:
continue # to reprompt user if they do not enter anything
elif confirm():
print 'Congratulations! You have a name!'
break
your_name()
I think the cleanest way is to change your_name to:
def your_name(toplevel=False):
while True:
name = raw_input("What is your name? ")
if not name:
continue # to reprompt user if they do not enter anything
else:
confirm(your_name)
if toplevel: print 'Congratulations! You have a name!'
break
and the very first call from the top level to your_name(True).
There are other ways, but they require global variables (ecch:-) or even dirtier tricks to find out if the function has been called from the top level; telling it explicitly is way cleaner...
Because of the style recursion you're doing (kudos on that) you end up invoking the your_name() function once each time they fill an answer.
I'd try something more like this:
def confirm():
answer = ''
while answer == '':
answer = raw_input('Are you sure? ')
if answer == 'yes':
return True
elif answer == 'no':
return False
else:
answer = ''
def your_name():
name = ''
while name == '':
name = raw_input("What is your name? ")
if confirm():
print 'Congratulations! You have a name!'
else:
your_name()
your_name()
I think you don't have to use all those "recursive" calls, try this:
def your_name():
flag = True
while flag:
name = raw_input("What is your name? ")
if name:
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
flag = False
break
elif answer == 'no':
break
print 'Congratulations! You have a name!'
your_name()
Using an inner loop for asking if the user is sure. With the use of a flag to determine whenever or not the main "What is your name? " question cycle is over.
You can just put the print 'Congratulations! You have a name!' inside your confirmation() function instead of your_name() so it will be something like this:
def confirm(function):
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
print 'Congratulations! You have a name!'
break
elif answer == 'no':
return function() # if the user wants to change their name, recall function
else:
continue # to reprompt user if the answer is not "yes" or "no"
def your_name():
while True:
name = raw_input("What is your name? ")
if not name:
continue
else:
confirm(your_name)
break
your_name()
BTW, I also modify your conditional syntax in the first function so that the program won't go through two if statements.
This solution is relatively succinct. It loops requesting your name while 'name' is an empty string. When requesting confirmation, it resets name to an empty string and thus continues the loop unless the user confirms 'yes'. It then prints the user's name to confirm its assignment.
def your_name():
name = ''
while name == '':
name = raw_input("What is your name? ")
answer = raw_input('Are you sure (yes or no)? ') if name != '' else 'no'
name = '' if answer != 'yes' else name
print 'Congratulations {0}! You have a name!'.format(name)