How to access function in a class on another file - python

I am currently working on a text-based adventure game project, I am still fairly new to python and I'm trying to access a class function in a new file. The error I am receiving says "ImportError: cannot import name 'bedroom' from 'story'", how would I fix this error?
main.py
from story import bedroom
def main():
while True:
print("Welcome to would you like to play?")
user = input(">>")
#string handling
if user.lower() == 'y':
bedroom()
else:
print("See you next time!")
exit()
if __name__ == '__main__':
main()
story.py
import stats as stat
class Rooms():
def bedroom():
stat.inventory.append("flashlight")
while True:
print("You awake in a dark room with no idea how you got there.\n")
print("You feel around and feel a flashlight.\n")```

You need to import the class itself, not the method.
Try this:
from story import Rooms
Then, whenever you need to use the method bedroom(), you can call it:
Rooms.bedroom()

Related

python not taking input after subprocess is called with subprocess.popen

Hello everyone im fairly new to python and this is my first language im learning so far. Im making a menu using a while true loop that takes input to select whichever flashing method a person needs to use and after calling whatever file using subprocess.popen or subprocess.call and it finishes it goes back into the menu loop but does not respond to any input at all.
import sys
import time
import subprocess
#!/bin/bash
sys.path.append
menu = True
def mainMenu():
while menu:
print("""
##################
# Utilities Menu #
##################
1. Tray Flasher
2. ESP Burner
3. Quit
""")
choice = (input('Select a utility: '))
if choice == '1':
trayFlasher()
elif choice == '2':
espBurner()
elif choice == '3':
print('Goodbye!')
def trayFlasher():
print('Have Fun!')
time.sleep(1)
subprocess.call(["<path to file>"])
def espBurner():
print('Burn Baby Burn...')
time.sleep(1)
subprocess.Popen(['<path to file>'])
sorry if my code is not so good or efficient, currently still learning. TIA!

How to pause / resume multiprocessing in Python?

So I got an idea to build something like mp3 player. To build that, I used multiprocessing module provided in Python. Here is my code
import multiprocessing
from playsound import playsound
def cp():
playsound('Music.mp3') # play the music
x = multiprocessing.Process(target = cp, daemon = True)
def main():
x.start()
while True and x.is_alive:
u = input("Input: ")
print(u)
if u == "S":
x.terminate()
print("Terminated process")
break
elif u == 'P':
# questioned code
print("Process paused")
elif u == 'R':
# questioned code
print("Process resumed")
if __name__ == '__main__':
main()
The idea is, when the program is executed, the program will automatically play the Music.mp3 file. To control the program, the user must input specific keyword into it.
S to stop the music and exit the program
P to pause the music
R to resuming playing the music
For now, I only know how to code the S option. For the others, I don't have any idea how to code it. So my question is: Is there any idea how to complete the P and R options? Or maybe, is there any idea about how to build the program using another method besides using multiprocessing module?
Thanks for the help

How can I call up this function properly?(Also it has now been fully resolved I no longer need help for this)

#functions
def main_menu():
print('If you want to read the rules select:1, to play the game select:2, to quit select 3.')
branch = int(input('What do you want to do:\n'))
menu = input('Type: main_menu()\n')
while branch == 1:
print('Hello to the rules')
main_menu
while branch == 2:
print(branch)
This will later become a number guessing game, where the function calls up the main menu, any help to call up the function?
from library import function_name
This is how you can load in main and than utilize where you want.
as a reference, I am giving you link below.
importing function from library or file to main file
Just use:
main_menu()
That's how you call a function in Python.
Are you looking for this:
def main_menu():
print('If you want to read the rules select:1, to play the game select:2, to quit select 3.')
branch = int(input('What do you want to do:\n'))
menu = input('Type: main_menu()\n')
while branch == 1:
print('Hello to the rules')
main_menu
while branch == 2:
print(branch)
main_menu() # just do this
That's how you call a function in Python.
Add a () in the function name

Repeating Menu but only repeats once

Whenever I select option 1 to play the game, the menu resets itself and starts from the beginning. It only does this once however and on the second time, choosing option 1 starts the game.
When I select any other option, it runs on the first attempt and does not repeat. Any help to stop this?
#Jake Eaton
#Menu
import time
from typing import type, type2
from main_game import Main_Game #Imports time, system and name Modules
from view_leaderboard import View_LB #Imports defined code with the names type, type 2, Main_Game and View_LB
from os import system, name
def clear():
if name =='nt': #Defines the clear command for the Terminal
_ = system('cls')
type("Welcome\n")
time.sleep(2)
type("Welcome to the only Text Adventure you will ever need to play in order to learn!\n")
time.sleep(2)
type("This Text Adventure covers the AQA A-level Computer Science Topic 4.6\n")
time.sleep(2)
type("Please remember that this is still in Beta and may never have a full 1.0 release\n")
time.sleep(2)
type("All releases and the source code can be found on Github using the link: https://github.com/Spud-Lord/Mock-NEA\n")
time.sleep(2)
type("To view the releases, just click on the releases tab on the Github Page\n")
time.sleep(2)
type("So let us begin!")
time.sleep(2)
type("Now then...")
time.sleep(2)
type("What do you want to do? Just type in the number of the option you want!")
time.sleep(2)
def Main_Menu(): #Defines all indented code as Main_Menu
menu = input("""
[1] - Start Game!
[2] - View Leaderboard
[3] - Exit Game
""") #The triple speech marks allow the Menu to go over multiple lines with only one code
if menu == "1":
clear() #Calls Clear Definition to clear Terminal Screen
Main_Game()
elif menu == "2":
print("")
View_LB() #Calls View_LB Definition to view leaderboard
time.sleep(2)
print("")
Main_Menu()
elif menu == "3":
exit() #Exits the game
else:
type("Please type in one of the numbers above...\n")
Main_Menu() #Loops back round if the user doesn't enter one of the numbers
Main_Menu() #Allows the Menu to loop
I did not reproduce your issue with the following code.
It seems you at least need to replace type(...) by print though!
The code needs to be cleaned up so that it becomes more readable. Put all your functions first then add the main part of the code (which starts at print("Welcome\n"))
#Jake Eaton
#Menu
import time
#from main_game import Main_Game #Imports time, system and name Modules
#from view_leaderboard import View_LB #Imports defined code with the names print, print 2, Main_Game and View_LB
from os import system, name
def clear():
if name =='nt': #Defines the clear command for the Terminal
_ = system('cls')
print("Welcome\n")
time.sleep(2)
print("Welcome to the only Text Adventure you will ever need to play in order to learn!\n")
time.sleep(2)
print("This Text Adventure covers the AQA A-level Computer Science Topic 4.6\n")
time.sleep(2)
print("Please remember that this is still in Beta and may never have a full 1.0 release\n")
time.sleep(2)
print("All releases and the source code can be found on Github using the link: https://github.com/Spud-Lord/Mock-NEA\n")
time.sleep(2)
print("To view the releases, just click on the releases tab on the Github Page\n")
time.sleep(2)
print("So let us begin!")
time.sleep(2)
print("Now then...")
time.sleep(2)
print("What do you want to do? Just print in the number of the option you want!")
time.sleep(2)
def Main_Game():
print ("Main game")
def View_LB():
print ("LB")
def Main_Menu(): #Defines all indented code as Main_Menu
menu = input("""
[1] - Start Game!
[2] - View Leaderboard
[3] - Exit Game
""") #The triple speech marks allow the Menu to go over multiple lines with only one code
if menu == "1":
clear() #Calls Clear Definition to clear Terminal Screen
Main_Game()
elif menu == "2":
print("")
View_LB() #Calls View_LB Definition to view leaderboard
time.sleep(2)
print("")
Main_Menu()
elif menu == "3":
exit() #Exits the game
else:
print("Please print in one of the numbers above...\n")
Main_Menu() #Loops back round if the user doesn't enter one of the numbers
Main_Menu()

When I enter no it doesn't execute properly

import webbrowser
import time
import sys
import urllib.request
def con():
cont = input("Do you want to continue? ")
if (cont.lower() == "yes" or cont.lower() == "y"):
main()
elif (cont.lower() == "no" or cont.lower() == "n"):
sys.exit()
else:
print("Invalid answer. Please try again")
time.sleep(1)
con()
def main():
try:
website = input("What website do you want to go to? (ex. Example.com) ")
fWebsite = "http://{}".format(website)
time.sleep(1)
if (urllib.request.urlopen(fWebsite).getcode() == 200):
webbrowser.open(fWebsite)
time.sleep(1)
except:
print("Invalid website. Please enter another one")
time.sleep(1)
main()
con()
main()
when the code runs con(), when ever I try to enter no, it always says invalid website. Please enter another one. How do I fix it to exit the program? everything else works it is just this one part.
The sys.exit function works by raising an SystemExit exception. Your code has a bare except block which is catching that exception and suppressing its normal purpose (that is, to exit quietly).
The best fix for this issue is to make your except clause more specific to the kinds of exceptions you expect to catch. It is almost always a bad idea to catch everything (the only exception to that is when you're catching all exceptions, but logging and re-raising most of them).
Since your specific code is trying to deal with exceptions from urllib, catching urllib.error.URLError is probably your best bet.

Categories

Resources