I am slightly stuck on my code. My knowledge of python is very limited but I am trying to quit the loop to display the items someone selects. I have tried if statements that don't work. Considered a def statement but not too sure how to implement it and Return is an idea but obviously needs the def statement to work.
Any help is much appreciated.
P.S I have no idea how to upload the CSV file but, the following link is what I am aiming to do: https://dl.dropboxusercontent.com/u/31895483/teaching%20delivered/FE/2013-14/Access%20-%20Prg/assignment/menu2.swf
import csv
f = open("menu.csv", "r") #Has items for the menu and is read only
spent = 0
order = []
menu = []
for line in f:
line = line.rstrip("\n")
dish = line.split(',')
menu = menu + [dish]
f.close()
#Menu imported into python, no need to leave file open
while True:
dishes = -1
for dish in menu:
if dishes == -1:
print ("Dish No".ljust(10), end="")
else:
print(str(dishes).ljust(10), end="")
print(dish[0].ljust(15), end="")
print(dish[1].ljust(30), end="")
print(dish[2].ljust(15), end="")
print(dish[3], end="\n\n")
dishes += 1
reply = input("Please choose your first item: ")
print()
spent = spent + float(menu[int(reply)+1][2])
order = order + [reply]
print(len(order), "choices made so far =", order, "and cost = £ ", spent)
print()
print ("Please choose an item from the menu (0-9 or press Q to end): ")
print()
All you need to do is check for the exit condition, and then use the break statement to break out of the loop.
while True:
# other stuff here
reply = input("Please choose a menu item:")
if reply.upper() == 'Q':
break # Break out of the while loop.
# We didn't break, so now we can try to parse the input to an integer.
spent = spent + float(menu[int(reply)+1][2])
This pattern of while True + other_code + if condition: break is pretty common, which has at least two benefits:
You're using accepted idioms, so you'll recognize them when you encounter them elsewhere.
Other people (including your future self) will be able to understand your code when they read it.
a cool trick that I like
my_menu_choices = iter(lambda : input("Please choose a menu item:").lower(),"q")
for i,dish in dishes:
print("%d. %s"%(i,dish))
print("Q. type q to QUIT")
my_menu_choices = list(my_menu_choices)
print("You Choose: %s"%my_menu_choices)
Related
finishgame = "n"
counter = 0
#the song randomizer
num = random.randint(0,50)
f = open("songs.txt","r")
lines = f.readlines()
#first letter only system
song = str(lines[num])
firstl = song[0]
print(firstl)
#the artist generator
g = open("artists.txt","r")
line = g.readlines()
print(line[num])
#guess system
while finishgame == "n":
guess = str(input("Enter your guess"))
if guess == song:
counter = counter+5
print("Correct!")
finishgame = "y"
elif counter == 2:
print("Out of guesses, sorry :(")
print("The Correct Answer was:",song)
finishgame = "y"
else:
counter = counter+1
print("Try Again")
First time asking so apologizes for any errors. I have create a song guessing game where it takes a song from an external file, and displays the first letter of the title. It then takes the artist from a separate file (where it is in the same line as the song in the other file) and displays that too. Then you should guess the song. However, my code is having trouble recognizing when a 'guess' is correct, please can anyone tell me why? I've tried using different methods of identification such as the id() function but so far have not got any results. I'm probably missing something simple but any help would be much appreciated.
I'm currently working on an small banking application in python. I created functions that opens a txt file. I tested the function on its own so I know it works, however when implemented alongside the menu it seems not to work.
def parse_in():
with open('bank.txt', 'r') as details:
lines = details.read().splitlines()
return lines
Later on I have a simple menu with few options but here I will only show the one I'm having issues with.
def menu():
print("Please selected one of the options" + "\n\t1: Open account"
while True:
try:
selection = int(input("Please enter your choice: "))
if selection == 1:
open_account(details)
else:
break
except:
print("Please enter number 1-6")
if 1 is selected an open account should be ran
def open_account(details):
print("Welcome to your new account")
new_account_number = randint(000000, 999999)
while True:
try:
new_account_balance = float(input("Enter your sum of money: "))
if new_account_balance < 0:
print("please enter positive value")
else:
break
except:
print("Please Enter Number Only")
while True:
new_account_name = input("Enter your name: ")
if " " in new_account_name:
print("Please enter your full name")
else:
break
details.append(new_account_number)
details.append(new_account_balance)
details.append(new_account_name)
After the information was imputed the idea is that they're suppose to save to the same file using a function.
def parse_out(details):
with open('bank.txt', 'w') as file:
for i in details:
file.write(str(i) + '\n')
and everything is ran in main function
def main():
details = parse_in()
welcome()
menu()
parse_out(details)
When I press 1 the open account function seems not be running instead, the menu loops back to choosing one of the options. I'n not really sure why it does that as it seems it should run and take information from user fallowed by saving the info to file.
Hello please forgive me if my question duplicate, I've searched previous questions and nothing seems to be quite the same. I'm working on a program that will scan a specific folder and search for specific file types to create a menu for a user to select. Once the user select the menu option the the corresponding file which is a power shell script. Currently My program does everything but run even a simple power shell script. I've attempted several configuration and it's not working. It would be great if someone can see what I may be doing wrong or provide me with some pointers. Code below.
##Text Menu Dynamic test
##version 1
## Created By Dragonshadow
## Code produce in Notpad++ For python v3.4.4
import os
import subprocess
import time
import pathlib
import logging
import fnmatch
import re
## Directory Enumerator
fileFolderLocationFilter = fnmatch.filter(os.listdir('C:\\Users\\myfolder\\Documents\\Automation_Scripts\\ENScripts\\'),"*.ps1")
selectedFile=""
## Menu defined setting veriables
def ENOC_menu():
files = fileFolderLocationFilter
counter = 1
print (20 * "=" , "Enoc Quick Menu" , 20 * "=")
enumFiles = list(enumerate(files))
for counter, value in enumFiles:
str = repr(counter) + ") " + repr(value);
print(str)
str = repr(counter+1) + ") Exit";
print(str)
print (57 * "_")
str = "Enter your choice [1 - " + repr((counter+1)) + "]:"
choice = int(input("Please Enter a Selection: "))
selectedFiles = enumFiles[choice]
return(selectedFiles[1])
if choice > counter :
choice = -1
elif choice != counter :
print("Please selecte a valid choice")
else:
selectedFiles = enumFiles[choice]
print(selectedFiles[1])
##selectedFiles = selectedFiles[1]
return choice
def you_sure():
opt = input("Are you sure Yes or No: ")
if opt=="Yes":
print("Continuing please wait this may take a moment...")
elif opt=="No":
print("returnig to Enoc Menu")
else: ##Stays in loop
print ("Please choose yes or no")
##count_down
def count_down ():
count_down = 10
while (count_down >= 0):
print(count_down)
count_down -= 1
if count_down == 0:
print("Task will continue")
break
##initiating loop
loop = True
while loop:
choice = ENOC_menu()
print ("\n" +"You selected "+ choice +"\n")
subprocess.call("C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe" + choice, shell=True)
##print ("---" +str(selectedFile))
You have probably already figured this out, but I the problem is in the subprocess.call() line. You are concatenating the powershell.exe path and the target file name together. See here:
>>> scriptToRun = "c:\\users\\Username\\Documents\\WindowsPowerShell\\classtestscript.ps1"
>>> powershellExe = "c:\\windows\\system32\\windowspowershell\\v1.0\\powershell.exe"
>>> print(powershellExe + scriptToRun)
c:\windows\system32\windowspowershell\v1.0\powershell.exec:\users\Username\Documents\WindowsPowerShell\classtestscript.ps1
Above, the two strings are stuck together without a space between them. Windows can't make sense of what you're trying to execute.
Put a space between the two two and subprocess.call() will understand what you're trying to do:
>>> print(powershellExe + ' ' + scriptToRun)
c:\windows\system32\windowspowershell\v1.0\powershell.exe c:\users\Username\Documents\WindowsPowerShell\classtestscript.ps1
I'm working on a Tweet Manager program in python for my programming class. For the assignment, I'm supposed to create a Tweet class that stores the author of a tweet, the tweet itself, and the time the tweet was created. Then, I'm supposed to create a Twitter program that gives users a menu of options to choose from.
When I try to run my Twitter program, it opens without syntax errors, but prints the Menu over and over and over again really rapidly without stopping. I can't figure out what in my code is causing this problem.
Here is my Twitter code:
import Tweet
import pickle
def main():
try:
load_file = open('tweets.dat', 'rb')
tweets = pickle.load('tweets.dat')
load_file.close()
except:
tweet_list = []
while (True):
choice = display_menu()
#Make a Tweet
if (choice == 1):
tweet_author = input("\nWhat is your name? ")
tweet_text = input("What would you like to tweet? ")
print()
if len(tweet_text) > 140:
print("Tweets can only be 140 characters!\n")
else:
print(tweet_author, ", your Tweet has been saved.")
age = 0
tweets = tweet.Tweet(tweet_author, tweet_text)
tweet_list.append(tweets)
try:
output_file = open('tweets.dat', 'wb')
pickle.dump(tweets, output_file)
output_file.close()
except:
print("Your tweets could not be saved!")
#View Recent Tweets
elif (choice == 2):
print("Recent Tweets")
print("--------------")
if len(tweet_list) == 0:
print("There are no recent tweets. \n")
for tweets in tweet_list[-5]:
print(tweets.get_author(), "-", tweets.get_age())
print(tweets.get_text(), "\n")
#Search Tweets
elif (choice == 3):
match = 0
tweet_list.reverse()
if tweet_list == []:
print("There are no tweets to search. \n")
search = input("What would you like to search for? ")
for tweets in tweet_list:
if (search in tweets.get_text()):
match = 1
if match = 1:
print("Search Results")
print("--------------")
print(tweets.get_author(), "-", tweets.get_age())
print(tweets.get_text(), "\n")
elif match == 0:
print("No tweets contained", search, "\n")
#Quit
elif (choice == 4):
print("Thank you for using the Tweet Manager!")
exit()
def display_menu():
print("Tweet Menu")
print("------------")
print()
print("1. Make a Tweet")
print("2. View Recent Tweets")
print("3. Search Tweets")
print("4. Quit")
print()
main()
There's no problem, the code is doing precisely what you told it to.
display_menu does exactly what the name implies: displays the menu. The main function calls that function inside a loop.
At no point do you actually ask for any input corresponding to the menu options.
display_menu always returns None - that's the default if you don't return anything.
Display menu does not retrieve any input into choice... Just displays the menu.
Thus, no if is matched and you loop indefinitely.
Your display_menu function doesn't actually give a value.
Change the last line of that function (print()) to
return input()
or if you are using python 2.x
return raw_input()
I am extremely new to Python, and to programming in general, so I decided to write some basic code to help me learn the ins and outs of it. I decided to try making a database editor, and have developed the following code:
name = []
rank = []
age = []
cmd = input("Please enter a command: ")
def recall(item): #Prints all of the information for an individual when given his/her name
if item in name:
index = name.index(item) #Finds the position of the given name
print(name[index] + ", " + rank[index] + ", " + age[index]) #prints the element of every list with the position of the name used as input
else:
print("Invalid input. Please enter a valid input.")
def operation(cmd):
while cmd != "end":
if cmd == "recall":
print(name)
item = input("Please enter an input: ")
recall(item)
elif cmd == "add":
new_name = input("Please enter a new name: ")
name.append(new_name)
new_rank = input("Please enter a new rank: ")
rank.append(new_rank)
new_age = input("Please input new age: ")
age.append(new_age)
recall(new_name)
else:
print("Please input a valid command.")
else:
input("Press enter to quit.")
operation(cmd)
I want to be able to call operation(cmd), and from it be able to call as many functions/perform as many actions as I want. Unfortunately, it just infinitely prints one of the outcomes instead of letting me put in multiple commands.
How can I change this function so that I can call operation(cmd) once, and call the other functions repeatedly? Or is there a better way to go about doing this? Please keep in mind I am a beginner and just trying to learn, not a developer.
Take a look at your code:
while cmd != "end":
if cmd == "recall":
If you call operation with anything than "end", "recall" or "add", the condition within while is True, the next if is also True, but the subsequent ifs are false. Therefore, the function executes the following block
else:
print("Please input a valid command.")
and the while loop continues to its next lap. Since cmd hasn't changed, the same process continues over and over again.
You have not put anything in your code to show where operator_1, operator_2, and operator_3 come from, though you have hinted that operator_3 comes from the commandline.
You need to have some code to get the next value for "operator_3". This might be from a list of parameters to function_3, in which case you would get:
def function_3(operator_3):
for loopvariable in operator_3:
if loopvariable == some_value_1:
#(and so forth, then:)
function_3(["this","that","something","something else"])
Or, you might get it from input (by default, the keyboard):
def function_3():
read_from_keyboard=raw_input("First command:")
while (read_from_keyboard != "end"):
if read_from_keyboard == some_value_1:
#(and so forth, then at the end of your while loop, read the next line)
read_from_keyboard = raw_input("Next command:")
The problem is you only check operator_3 once in function_3, the second time you ask the user for an operator, you don't store its value, which is why its only running with one condition.
def function_3(operator_3):
while operator_3 != "end":
if operator_3 == some_value_1
function_1(operator_1)
elif operator_3 == some_value_2
function_2
else:
print("Enter valid operator.") # Here, the value of the input is lost
The logic you are trying to implement is the following:
Ask the user for some input.
Call function_3 with this input.
If the input is not end, run either function_1 or function_2.
Start again from step 1
However, you are missing #4 above, where you are trying to restart the loop again.
To fix this, make sure you store the value entered by the user when you prompt them for an operator. To do that, use the input function if you are using Python3, or raw_input if you are using Python2. These functions prompt the user for some input and then return that input to your program:
def function_3(operator_3):
while operator_3 != 'end':
if operator_3 == some_value_1:
function_1(operator_3)
elif operator_3 == some_value_2:
function_2(operator_3)
else:
operator_3 = input('Enter valid operator: ')
operator_3 = input('Enter operator or "end" to quit: ')
looks like you are trying to get input from the user, but you never implemented it in function_3...
def function_3(from_user):
while (from_user != "end"):
from_user = raw_input("enter a command: ")
if from_user == some_value_1:
# etc...