I am a beginner and I can't for the life of me find the error.
When I run this function and input '2' it continues and works properly. When I enter '3' it prints the proper message and loops back around to the top...but when I enter '1', this is the output:
Hmm... Given the options "1" and "2," you chose "1"!!!!???
try again.
The code for option 1 and option 2 are exactly the same (I copy and pasted), but the first option doesn't work. I even tried switching the values around, so that the boolean statements were flipped (the first option read, if file_option == '2' and the second read if file_option == '1') and no luck. I have determined that it is the first option that is always broken, but I do not understand why.
def file_path(location):
home = os.path.expanduser('~')
download_path = os.path.join(home, location)
return download_path
def file_path_chooser():
clear()
file_option = None
while file_option not in ('1','2'):
file_option = input('''
Choose from the following locations:
Note: You will have the option to choose folders inside of whatever you choose.
type '1' for Documents
type '2' for Desktop
response: ''')
if file_option == '1':
clear()
dir_contents_list = os.listdir(file_path('Desktop'))
folder_list = []
p0 = '''
Please pick from the following locations:
'''
for item in dir_contents_list:
if '.' not in item:
folder_list.append(item)
p1 =''
for folder in folder_list:
folders_text = '''
type '{num}' to save the file in {folder}'''.format(folder=folder, num=folder_list.index(folder))
p1 += folders_text
print(p0+p1)
if file_option == '2':
clear()
dir_contents_list = os.listdir(file_path('Desktop'))
folder_list = []
p0 = '''
Please pick from the following locations:
'''
for item in dir_contents_list:
if '.' not in item:
folder_list.append(item)
p1 =''
for folder in folder_list:
folders_text = '''
type '{num}' to save the file in {folder}'''.format(folder=folder, num=folder_list.index(folder))
p1 += folders_text
print(p0+p1)
else:
clear()
print('Hmm... Given the options "1" and "2," you chose ' + '"'+ file_option.upper()+'"!!!!???\n\ntry again.')
time.sleep(1)
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux (note: for these, os.name = 'posix)
else:
_ = system('clear')
I changed the if file_option == "2" to elif file_option == "2"
def file_path(location):
home = os.path.expanduser('~')
download_path = os.path.join(home, location)
return download_path
def file_path_chooser():
clear()
file_option = None
while file_option not in ('1','2'):
file_option = input('''
Choose from the following locations:
Note: You will have the option to choose folders inside of whatever you choose.
type '1' for Documents
type '2' for Desktop
response: ''')
if file_option == '1':
clear()
dir_contents_list = os.listdir(file_path('Desktop'))
folder_list = []
p0 = '''
Please pick from the following locations:
'''
for item in dir_contents_list:
if '.' not in item:
folder_list.append(item)
p1 =''
for folder in folder_list:
folders_text = '''
type '{num}' to save the file in {folder}'''.format(folder=folder, num=folder_list.index(folder))
p1 += folders_text
print(p0+p1)
elif file_option == '2':
clear()
dir_contents_list = os.listdir(file_path('Desktop'))
folder_list = []
p0 = '''
Please pick from the following locations:
'''
for item in dir_contents_list:
if '.' not in item:
folder_list.append(item)
p1 =''
for folder in folder_list:
folders_text = '''
type '{num}' to save the file in {folder}'''.format(folder=folder, num=folder_list.index(folder))
p1 += folders_text
print(p0+p1)
else:
clear()
print('Hmm... Given the options "1" and "2," you chose ' + '"'+ file_option.upper()+'"!!!!???\n\ntry again.')
time.sleep(1)
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux (note: for these, os.name = 'posix)
else:
_ = system('clear')
Related
Please let me know if I need to provide more info. This is for a soundboard setup- it's a raspberry-pi 4 with an attached 10-key. It works insofar as it plays the correct sound when I press a key, but the sound plays on a loop.
I see a section that says "Play an audio track indefinitely" but I have no idea if this is what I need to edit. Is this correct?
#!/usr/bin/python3
import os
import sys
import vlc
import time
inputs = ['\'1\'', '\'2\'', '\'3\'', '\'4\'', '\'5\'', '\'6\'', '\'7\'', '\'8\'', '\'9\'', '\'0\'']
special = ['\'*\'', '\'+\'', '\'-\'', '\'+\'', '\'/\'', '\'.\'']
instance = vlc.Instance('--input-repeat=999999')
player = instance.media_player_new()
def loadPresets():
''' Get all the Presets in the current directory '''
l = []
for file in os.listdir(os.getcwd()):
if file.endswith(".preset"):
print("Preset Found:", os.path.join(os.getcwd(), file))
l.append(os.path.join(os.getcwd(), file))
return l
def getPresetTracks(preset):
''' Get all the links inside of a preset track '''
l = []
with open(preset) as file:
for line in file:
# Need to get rid of those pesky \n's
print(str(len(l)) + ': ', line[:-1])
l.append(line[:-1])
if len(l) < 10:
print("Too little links. Cannot correctly populate.")
l = []
elif len(l) > 10:
print("Too many links. Cannot correctly populate.")
l = []
return l
def isYouTubeAudio(link):
import re
if re.match(r'http[s]:\/\/www\.youtube\.com/watch\?v=([\w-]{11})', link) == None:
return False
else:
return True
def getYouTubeAudioTrack(link):
''' Get Audio track of a link '''
import pafy
video = pafy.new(link)
bestaudio = video.getbestaudio()
# print(bestaudio.url)
return bestaudio.url
def playQuick(num):
''' Make quick sound '''
l = ['up.mp3', 'down.mp3', 'preset_change.mp3', 'startup.mp3']
s = instance.media_new(os.path.join(os.getcwd(), l[num]))
player.set_media(s)
player.play()
if num == 3:
time.sleep(4)
else:
time.sleep(1)
player.stop()
def switchPresets(readyPresets):
playQuick(2)
print("Ready to swap the preset. Loaded presets:")
i = 0
for link in readyPresets:
print(i, "-", link)
i += 1
newPreset = input("What would you like your preset to be?: ")
if newPreset.isdigit() and int(newPreset) < len(presetList):
# Number preset. We're goood
numPre = int(newPreset)
print("New Preset: ", numPre)
playQuick(0)
return numPre
else:
# It's a character. Stop
print("Invalid preset. Skipping.")
playQuick(1)
return None
def playTrack(track):
''' Play an audio track indefinetly. Also awaits response so it can detect a change in information '''
from readchar import readkey
# Load and add media file
media = instance.media_new(track)
player.set_media(media)
# Play
player.play()
# Pause before getting the status, to update everything
print(str(player.get_state()) + " ", end='\r')
sys.stdout.flush()
time.sleep(1)
print(str(player.get_state()) + " ")
if __name__ == '__main__':
presetList = loadPresets()
preset = getPresetTracks(presetList[0])
# Start Up and initial setup
active = False
playQuick(3)
import readchar
keyInput = '\'0\''
# Start Main loop
print("Ready for input")
while keyInput not in inputs or keyInput not in special:
keyInput = repr(readchar.readkey())
# Sanitize input
if keyInput in inputs:
# Play sound
santized = int(keyInput[1])
player.stop()
active = True
# print(preset[santized])
if isYouTubeAudio(preset[santized]):
playTrack(getYouTubeAudioTrack(preset[santized]))
else:
playTrack(preset[santized])
# Special Characters
elif keyInput == special[0]: # '\'*\'
# Preset
active = False
player.stop()
np = switchPresets(presetList)
if np != None:
preset = getPresetTracks(presetList[np])
elif keyInput == special[1]: # '\'+\''
# Play/Pause. +
if active:
player.pause()
active = False
else:
player.play()
active = True
elif keyInput == special[2]: # '\'-\''
pass
elif keyInput == '\'x\'':
# End case
exit()
At the start of my code, I let the user choose a file and store its path in a text file. Here is the function for that:
def choose_folder():
root = tk.Tk()
root.withdraw()
global DIR
DIR = filedialog.askdirectory()
global settings_file # Somehow works without this line despite being declared in main
with open(settings_file, "w") as sf:
sf.write(DIR)
Now, I want to let the user change the folder. In the main loop, the user chooses an option each time. Option 4 is to change the directory. Here is my code to change it:
elif user_input == 4:
open(settings_file, "w").close() # Clear the settings file
choose_folder()
The problem is, that for some reason the folder choosing dialog box will not open the second time. I've already checked and the code reaches the choose_folder() function but stops running on filedialog.askdirectory() (the screen flickers for a second which means that something happens but doesn't open the dialog box). What causes this to happen and how can I fix it?
EDIT: Here's the code snippet (I have also slightly changed choose_folder()):
import tkinter as tk
from tkinter import filedialog
import os
#other imports
def prompt_continue() -> bool:
choice = input("Do you want to continue (y/n)? ")[0].lower()
while choice != 'y' and choice != 'n':
choice = input("Invalid Input. ")[0].lower()
return choice == 'y'
def choose_folder():
root = tk.Tk()
root.withdraw()
global DIR
DIR = filedialog.askdirectory()
while not os.path.isdir(DIR):
print("Please choose a folder.")
DIR = filedialog.askdirectory()
while os.listdir(DIR):
print("Please choose an empty folder.")
DIR = filedialog.askdirectory()
with open(settings_file, "w") as sf:
sf.write(DIR)
if __name__ == "__main__":
DIR = ""
settings_file = os.path.expanduser('~/Documents/flagdir.txt')
if os.path.isfile(settings_file): # if settings file exists
if os.stat(settings_file).st_size == 0: # if settings file is empty
choose_folder()
else:
choose_folder()
with open(settings_file, 'r') as file:
DIR = file.read()
user_continue = True
total = 0
while user_continue:
print("Choose option:")
print("[1] Download n random flags")
print("[2] Enter 2 countries and download their mashup")
print("[3] Clear the flags folder")
print("[4] Change the flags folder path")
print("[5] Print the flags folder path")
print("[6] Exit")
user_input = int(input())
while user_input < 1 or user_input > 6:
user_input = int(input("Invalid Input."))
if user_input == 1:
# working code
elif user_input == 2:
# working code
elif user_input == 3:
# working code
elif user_input == 4:
open(settings_file, "w").close()
choose_folder()
elif user_input == 5:
# working code
else:
break
user_continue = prompt_continue()
print("Bye!")
sorry if this is not presented well. This is my first time ever using StackOverflow. I'm trying to create this to keep track of inventory. I do not know how to utilize try-excepts. Additionally, I don't know what else is going wrong. Thanks for any and all help !
data handler:
import os
class DataHandler():
def __init__(self, filename, datadict = {}):
self.filename = filename
self.datadict = datadict
def readData(self): # returns dictionary
try:
fileobj = open(self.filename,'r')
datastr = fileobj.read()
fileobj.close()
# return dictionary read from file or null dictionary
if datastr != '':
return eval(datastr)
else:
return self.datadict
except FileNotFoundError:
return self.datadict # null dictionary
def writeData(self, datadict): # must pass dictionary
fileobj = open(self.filename,'w')
fileobj.write(str(datadict))
fileobj.close()
separate file:
import DataHandler as DH
def menuDisplay():
print("="*40)
print("1 - Add inventory item")
print("2 - Modify inventory item")
print("3 - Delete inventory item")
print("4 - Print inventory list")
print("5 - Exit program")
print("="*40)
selection = input("\nPlease enter menu choice: ")
if selection < "1" and selection > "5":
input("Invalid selection, please enter 1 - 5")
menuDisplay()
else:
return int(selection)
def addItem(invDict,dh):
itemdesc = input("Item Description: ")
itemqty = int(input("Qty: "))
if len(invDict) > 0:
nextKey = sorted(invDict.keys())[-1]+1
else:
nextKey = 1
invDict[nextKey]=[itemdesc,itemqty]
dh.writeData(invDict)
def printInv(invDict):
print("{:<10}{:20}{:6}".format("Item #", "Description", "Qty",))
for dkey, lvalue in invDict.items():
print("{:<10}{:20}{:6d}".format(str(dkey), lvalue[0],lvalue[1], lvalue[2]))
def delItem(invDict,dh):
itemnum = input("Please enter item to delete: ")
del invDict[int(itemnum)]
dh.writeData(invDict)
# complete error checking
def modItem(invDict,dh):
itemnum = input("Please enter item to modify: ")
newqty = input("Please enter the new quantity: ")
invDict[int(itemnum)][1] = int(newqty)
dh = DH.DataHandler("inventory.txt")
invDict = dh.readData()
selection = 0
while selection != 5:
selection = menuDisplay()
if selection == 1:
addItem(invDict,dh)
elif selection == 2:
modItem(invDict,dh)
elif selection == 3:
delItem(invDict,dh)
elif selection == 4:
printInv(invDict)
I want to optimize my code to return well in a part of a code.
I know that I can do that with do while but I think it's maybe heavy with a lot of do while.
I identify where I want to return in comments
Can you suggest me a solution to solve my problem?
#return here 0
mainMenu()
choix = input()
if choix == 1:
print "Enter your username"
username = raw_input()
print "Enter your password"
password = raw_input()
createAccount.createAccount(username,password)
#return here 1
educatorMenu()
choix = input()
if choix == 1:
print "Enter his age"
ageChild = raw_input()
print "Enter his photo"
photoChild = raw_input()
educator.createChildAccount(ageChild, photoChild)
elif choix == 2:
childrenList = educator.seeChildrenList()
#Return to where it is written "return here 0"
elif choix == 3:
childrenList = educator.seeChildrenList()
print "Associate children?"
choixEnfant = input()
educator.associateChildren(childrenList,choixEnfant-1, educator.getIdEducator(username))
#Return to where it is written "return here 1"
Thanks a lot.
Note: I will not re-write/optimize your code, because I feel it should be a task for you to do so. Furthermore, there are quite some functions and references missing to rewrite it; you did not deliver an MWE.
Consequently, you may find this useful as a starting point and try to adapt this (very basic structure) to suit your needs. However, be warned: This also is far from being efficient, but it will help you to extend your knowledge of the basics.
def menu_main():
q = ['What would you like to do?',
'1: List educators',
'2: Create educator',
'3: Manage educator\'s children',
'4: Exit'].join('\n ')
return int(input(q).strip()[0])
def menu_educator_create():
usr = input('Enter username:').strip()
pwd = input('Enter password:').strip()
return (usr, pwd)
def menu_educator_manage():
q = ['What would you like to do?',
'1: List children',
'2: Add child',
'3: Return'].join('\n ')
return int(input(q).strip()[0])
if __name__ == '__main__':
edus = {}
exit = False
while not exit:
print('===')
cmd = menu_main()
if cmd == 1:
# List educators
pass
elif cmd == 2:
# Create educator
usr, pwd = menu_educator_create()
pass
elif cmd == 3:
# Manage children
# (should somehow obtain current educator first)
exit_edu = False
while not exit_edu:
subcmd = menu_educator_manage()
if subcmd == 1:
# List children
pass
elif subcmd == 2:
# Add child
pass
elif subcmd == 3:
# Return
exit_edu = True
else:
# None of the above
print('Unknown choice from educator menu.')
elif cmd == 4:
# Exit
exit = True
else:
# None of the above
print('Unknown choice from main menu.')
import random
import pickle, shelve
import os
#import RPi.GPIO as GPIO | Raspberry pi only
import tkinter
import sys
import time
class Operator(object):
global list_name
def __init__(self):
print("Welcome to Python OS 1.0")
print("type 'help' to access help...") # ADD CODE OS.REMOVE("FILE")
def CheckDetails(self):
if not os.path.isfile( 'details.dat' ) :
data=[0]
data[0] = input('Enter Your Name: ' )
file= open( 'details.dat' , 'wb' )
pickle.dump( data , file )
file.close()
else :
File = open( 'details.dat' , 'rb' )
data = pickle.load( File )
file.close()
user = ""
while user != data[0]:
input("please enter your username...")
print( 'Welcome Back To Python OS, '+ data[0])
def Help(self):
print("""
write(sentence) - Prints the typed sentence on the screen
open(file, mode) - Opens the file and mode such as 'r'
create(listName) - creates the list, listName
add(data, listName) - adds the data to listName
remove(data, listName) - removes the selected data from listName
""")
def write(self, sentence):
print(sentence)
#classmethod
def create(self):
list_name = input("Please enter the list name...")
vars()[list_name] = []
time.sleep(1)
print("List (" + list_name + ") created")
def add(self):
data = input("Please specify the data to be added...")
list_name += data
def remove(self, data, list_name):
remove_data = input("Plese specify the data to be removed...")
list_name -= data
def main():
os = Operator()
os.CheckDetails()
ans = ""
ans = ans.lower()
while ans != "quit":
ans = input()
if ans == "write":
os.write()
elif ans == "help":
os.Help()
elif ans == "create":
os.create()
elif ans == "add":
os.add()
elif ans == "remove":
os.remove()
elif ans == "quit":
break
else:
print("Sorry, that command does not exist or it will be added into a future update...")
print("goodbye...")
main()
I am trying to make some sort of simplified python, but hitting errors only on the CheckDetails() function. I'm pickling data (which is fine) but getting errors when making the user check his or her username is correct, I've tested it and even though I have typed in the correct username, it carry's on asking for my username. Can anyone please help?
You have a while loop that will execute forever because you are not assigning your user variable to anything.
while user != data[0]:
user = input("please enter your username...")
print( 'Welcome Back To Python OS, '+ data[0])