I've recently started to code and wanted to try my luck on a beginners program after 10 hrs of Udemy courses.
I've coded a "Guess the number" minigame, where a number is generated between 1-10 and I want the program to restart if someone guesses wrong.
import random
import os
import sys
def restart_program():
python = sys.executable
os.execv(sys.executable, ['python'] + sys.argv)
number = str(random.randrange(1,10))
choice = input("Which number did the PC pick?\n")
if choice == number:
print("You won!")
restart_program()
elif choice != number:
print("You lose!")
restart_program()
For some reason JupyterLab' kernel keeps dying on me the second I input a number.
I've tried restructuring the code and using completely different code but I always kill the kernel.
Can someone tell me if I did smth wrong?
I believe it is not a good idea to spawn a new Python interpreter as means of "restarting" program, especially if you are not its owner (did you spawn the program in the first place? No, a Jupyter kernel did it for you → you should not try to kill it and replace by another process as os.execv does).
Also, depending on what is in sys.argv you may actually invoke a different module which also could lead to a crash. See it for yourself - when running a notebook with IPython kernel sys.argv contains IPython internal commands, you should not play with those!
For this simple beginner program you probably should use a loop:
import random
done = False
while not done:
number = str(random.randrange(1,10))
choice = input("Which number did the PC pick?\n")
if choice == number:
print("You won!")
elif choice != number:
print("You lose!")
if choice == 'x':
done = True
But if you really need to restart the kernel you should use one of the solutions for restarting IPython kernel from code cell (or equivalent for any other kernel that you may be using).
Related
I am trying to design a game in Python. Where it will take inputs from five users.But i do not want the user's to know each others inputs. So i would like to erase the screen after taking a input from the user and then ask the next user.Is there any way to accomplish this?
I tried taking in inputs but the terminal shows the previous line revealing the input given by the previous user. Is there any way to hide it
User1=int(input("enter your number Player1"))
User2=int(input("enter your number Player2"))
User3=int(input("enter your number Player3"))
User4=int(input("enter your number Player4"))
User5=int(input("enter your number Player5"))
It is displaying the input taken by the previous User. I need a way to hide it.
I have tried using import os
and using os.system('cls')
but that did not work.(I was Using google colab)
import os
User1=int(input("enter your number Player1 "))
os.system('cls')
User2=int(input("enter your number Player2 "))
os.system('cls')
User3=int(input("enter your number Player3 "))
os.system('cls')
User4=int(input("enter your number Player4 "))
os.system('cls')
User5=int(input("enter your number Player5 "))
Try using os.system("clear") instead. That should do the trick. Google Colab uses linux and cls is for windows but clear is for macos and linux.
I'm working on a piece of code in Python 3 that acts as an interface for various dead by daylight cheats. I'm using a very basic setup, just input() and os.system() to find and open specific files. It works fine, but there's one small issue.
The interface uses cmd prompt, and I have it set up so that entering numbers 1-4 will open programs and executables used to modify the game. However, some of the programs are required to stay open while others run. For example, the BVHR Session Grabber must be running along with the SaveInjector Interface, because the SaveInjector needs to receive a certain code from the Grabber.
There's a problem here, the code is set up in such a way that you can only run one file at a time. I'm not sure what exactly causes this, but I'll try to explain what happens. When entering the number 1, for example, into the cmd prompt window, it opens the BHVR Session Grabber (as intended). After that, the interface becomes unusable until I close the BHVR Session Grabber. I can't type anything into it while it's active, so I can't open multiple programs at once.
Not entirely sure if this is intended or not, but I'm hoping it's avoidable. If anyone has any knowledge on the issue let me know how to find a way around this in the comments please.
import os.path
def interface():
os.system('cls' if os.name == 'nt' else 'clear')
print("""
\n\nSelect a cheat below:
\n
\n1: BHVR Session Grabber
\n2: SaveInjector Interface
\n3: Rank / Shards Editor
\n4: Exit\n
""")
def checker():
interface()
lst = ['1','2','3','4']
good_input = input(">")
global user_input
user_input = None
while not user_input:
if good_input in lst:
user_input = good_input
else:
print("Enter a valid integer.")
good_input = input(">")
checker()
cwd = os.getcwd()
def selection():
if user_input == '1':
f = (os.path.join(cwd, 'Programs', 'BHVRSession', 'CookieFinder.exe'));
os.system(f)
checker()
selection()
elif user_input == '2':
os.system('cmd /k "cd Programs & cd Injector & SI.exe & cd.. & cd.. & Ultimate.py"')
elif user_input == '3':
f = (os.path.join(cwd, 'Programs', 'RankShards', 'Sender.exe'));
os.system(f)
checker()
selection()
elif user_input == '4':
os.system('cmd /k "taskkill/im py.exe"')
selection()
The problem here is that os.system() is blocking. This means that it will only return and continue executing your Python code after the program it runs finishes. Instead, you should look at the subprocess package to learn how to fork a new process that can run in parallel with your Python program.
I've created a basic, multiple choice, interactive calculator in Python. I want the user to be able to have the option to stop the programme running by answering "No" when asked whether they want to test out my calculator.
I want to be able to print("Ok, no problem") which you can see is already there but I need something extra to stop the programme running if this is the answer that the user picks.
Code is below. See lines 12-13.
name = input("Hi There. What is your name? ")
print("Well Hi " + name + ", it sure is nice to meet you")
age = input("So how old are you anyway? ")
print("Wow, you're " + age + " huh? ")
print(name + " I would like you to try out the companies new calculator. Would you be
happy to do that? ")
answer = input("Please answer Yes or No ")
if answer == "Yes":
print("Thank you, I appreciated that. Let's begin")
elif answer == "No":
print("Ok, no problem")
else:
print("Sorry I didn't quite get that. Please answer yes or no")
import math
number_1 = int(input("Please pick a number "))
order = (input("Ok, now please pick either: +, -, / or * "))
number_2 = int(input("Great, now please pick a second number "))
if order == "+":
print(number_1 + number_2)
elif order == "-":
print(number_1 - number_2)
elif order == "/":
print(number_1 / number_2)
elif order == "*":
print(number_1 * number_2)
else:
print("Sorry that is not +, -, / or *. Please enter a relevant order")
Any help that you can give me would be much appreciated.
You can use sys.exit to terminate the program:
import sys
#...
elif answer == "No":
print("Ok, no problem")
sys.exit()
Here is an answer for you which helped me out:
Let me give some information on them:
quit() raises the SystemExit exception behind the scenes.
Furthermore, if you print it, it will give a message:
>>> print (quit)
Use quit() or Ctrl-Z plus Return to exit
>>>
This functionality was included to help people who do not know Python. After all, one of the most likely things a newbie will try to exit Python is typing in quit.
Nevertheless, quit should not be used in production code. This is because it only works if the site module is loaded. Instead, this function should only be used in the interpreter.
exit() is an alias for quit (or vice-versa). They exist together simply to make Python more user-friendly.
Furthermore, it too gives a message when printed:
>>> print (exit)
Use exit() or Ctrl-Z plus Return to exit
>>>
However, like quit, exit is considered bad to use in production code and should be reserved for use in the interpreter. This is because it too relies on the site module.
sys.exit() raises the SystemExit exception in the background. This means that it is the same as quit and exit in that respect.
Unlike those two however, sys.exit is considered good to use in production code. This is because the sys module will always be there.
os._exit() exits the program without calling cleanup handlers, flushing stdio buffers, etc. Thus, it is not a standard way to exit and should only be used in special cases. The most common of these is in the child process(es) created by os.fork.
Note that, of the four methods given, only this one is unique in what it does.
Summed up, all four methods exit the program. However, the first two are considered bad to use in production code and the last is a non-standard, dirty way that is only used in special scenarios. So, if you want to exit a program normally, go with the third method: sys.exit.
Or, even better in my opinion, you can just do directly what sys.exit does behind the scenes and run:
raise SystemExit
This way, you do not need to import sys first.
However, this choice is simply one on style and is purely up to you.
I want to set up the end of my python script to ask for an input for 5 seconds, and then print if nothing is set.
I have tried looking into the pygame library and a variety of other modules, but nothing seems to work or be 3.x compatible.
thank = ""
thank = input()
time.sleep(5)
if thank == "":
print("What, you aren't even going to say 'thank you'? So rude.")
else:
print("You are welcome")
office_list = []
print("Type in your office supplies.\nEnter 'DONE' to print out your list.\n--------------------\n")
while True:
list = input("> ")
if list == 'DONE':
break
office_list.append(list)
print("Here is your list\n--------------------\n")
for ls in office_list:
print(ls)
I've been trying to find this online but seem to have trouble trying to find the correct vocabulary I believe.
What I am trying to make the program do is clear what I have written to make the list and then print the list. What happens in the program right now is it will have the words I typed on top of the list and print when I enter the word 'DONE'.
You can use the os module. Under *nix, you can use os.system('clear') or os.system('cls') under Windows.
Using the os module, you can run shell commands. To clear the console on Linux/macOS you can use the clear command, on Windows there's cls:
import os
import sys
def clear():
if sys.platform == 'windows':
os.system('cls')
else:
os.system('clear')
Just print enough newline characters like this:
print('\n' * 50)
It doesn't hurt to print out too many lines for a console application as this will all happen in a split second. This method is cross-platform and should work in nearly any environment.
The OS-level answers actually do the same thing, but the OS knows exactly how many lines to print. If you don't care about hiding the precise number of lines that are shown on the screen, just print out enough (within reason) to clear the console.