I am coding a to-do app, but while matching the menu() function it gives a Syntax Error, the function returns the number of the option the user selected, this is the code:
# Imports
import time, os, random
from colorama import Fore, Back, Style
# Functions
def menu():
print(f"{Fore.BLUE}To-Do List!")
print(Style.RESET_ALL)
print(f"{Fore.GREEN}[1] ADD ITEM")
print(f"{Fore.RED}[2] REMOVE ITEM")
print(f"{Fore.BLUE}[3] SEE LIST")
option = int(input("Selection > "))
return option
# Variables
newItem = {
"name": "",
"description": "",
"date": "",
"priority": ""
}
todo = []
# Code
match menu():
case 1:
os.system("clear")
print(f"{Fore.GREEN}ADD ITEM TO LIST")
print(Style.RESET_ALL)
newItem["name"] = input("Item name > ")
newItem["description"] = input("Item description > ")
newItem["date"] = input("Item date > ")
newItem["priority"] = input("Item priority (low/med/high) > ")
todo.append(newItem)
print(todo)
input()
How can I solve it?
I tried changing the variable and using the match() statement a different way, it still has the same error.
As #CryptoFool allready mentioned in the comments, the match statement was added in python 3.10. Means, previous versions won't work.
Make shure to install a python version greater or equeal as 3.10, or use a workaround
Related
I recently was trying to work on a twist to a program I am writing for my first program really. And I have everything working if the user is told to enter some values each time the game runs.
However, I was thinking that it should have a default set of characters that my program/game would use every time. My first goal was to get this to just give every player the same default 3 characters. But eventually this would need to have a have a list expanded of at least the character names.
My trouble comes in that I have taken a if loop that gathered the data each time if they said they have new characters to create, and have tried to modify it to the best of my knowledge to use a list and have it use the position in the loop to get that list number.
Then pass that data down the same paths I had created in the class. But it seems to be just skipping this section which right now I cant see why(I am sure this is a inexperienced moment) Or I am trying to access the list incorrectly? Anyway help on this would be huge, I have included my code below.
I have added commented lines to indicate the section of code that appears to be skipping.
And clarification I hope on this question is Is the for in loop the right way to solve this issue? And if so am I accessing this the correct way?
print ("Welcome to Chose your own adventure python edition")
print ("")
players = []
playerCharacters = []
def playerNames():
playerNum = int(input("How many players are playing? "))
if playerNum > 4:
print("I am sorry, unfortunately only four players are permitted.")
return
for playerId in range(playerNum):
newPlayerName = input(f"What is player {playerId + 1}'s name?")
players.append(newPlayerName)
print(f"Welcome: {' & '.join(players)}!")
def characters():
charAmount = 3
for index, player in enumerate(players):
playerCreate = input("{} (player {}), do you have a character to create. (y/n)".format(
player, str(index+1)))
if playerCreate.lower() =="y":
charAmount = int(input("How many characters does this player begin the game with?"))
for x in range(0,(charAmount)):
getCharName = input("Enter Next Char name ")
getCharDice = input("Please enter the number of dice this char will use. ")
getCharRole = input("Please enter the villagers role. ")
charData = {
"name": getCharName,
"diceCount": getCharDice,
"role": getCharRole,
"playerName": player
}
newCharacter = Character(characterData=charData)
newCharacter.printSummary()
playerCharacters.append(newCharacter)
if playerCreate.lower() == "n":
defaultCapture = input("Would you like to begin with the default charatures. (y/n)?" )
if defaultCapture.lower() == "y":
###Beginning of skipped code
for x in range (0,3):
DefaultCharName = ["Bob", "Sally", "Tommy"]
DefaultDiceCount = 1
DefaultRole = ['Builder', "Recruiter" , "Nothing"]
charData = {
"name": DefaultCharName(x),
"diceCount": DefaultDiceCount,
"role": DefaultRole(x),
"playerName": player
}
DefaultCharacters = Character(characterData=charData)
DefaultCharacters.printSummary()
playerCharacters.append(DefaultCharacters)
###End of skipped section
if defaultCapture.lower == "n":
print("Well it looks as though you dont really want to play.")
continue
print("Summary ==========================")
for player in playerCharacters:
print("{characterName} Controlled by {playerName}".format(
playerName=player.playerName,
characterName=player.name ))
return
class Character:
name = "default name"
playerName = "john/jane doe"
diceCount = "1"
role = "vanillaPaste"
def __init__(self, characterData):
self.playerName = characterData['playerName']
self.role = characterData['role']
self.diceCount = characterData['diceCount']
self.name = characterData['name']
def printSummary(self):
print("{player} summary: \r\n \r\nCharacters:\r\nName: {characterName} \r\nDice: {dice} \r\nRole: {role} \r\n"
.format(
characterName=self.name,
player=self.playerName,
dice=self.diceCount,
role=self.role
);
playerNames()
characters()
While your code is, like the comments say, a little too long for a minimal SO question, in this case it's an easy fix.
Just before your "start of skipped section", you have
if defaultCapture.lower == "y":
which is missing the parentheses to actually call .lower(), to lower-case the string. (Comparing a function to a string would always be false.)
That expression should be
if defaultCapture.lower() == "y":
try to check the indentation of the for loop and when you enter something, do not have spaces. You should use
defaultCapture.lower().split =="y"
OR
defaultCapture.lower().split.contains("y")// Add the brackets()
How Can I call a Python Script From anonther Python Script
I tried using os system and tried using this
def run(runfile):
with open(runfile,"r") as rnf:
exec(rnf.read())
print ("Welcome")
print ("Programs.")
print ("1. Vowel Counter")
print ("2. Basic Calculator")
print ("3. Odd Even")
program = int(input("Select a Program by Choosing its number: "))
programs = ["1", "2", "3"]
if program == "1" :
execfile('VowelCounter.py')
There's no Error but it wont run the other py file
Even though python has the capabilities to run external script using exec and execfile, the more pythonic way of doing is by importing packages.
But I understand that you target can only be known at run time, you could use importlib, to import a package dynamically.
A sample is given below
# Order should be re arranged as per your need
programs = {
"1": {'package': "VowelCounter", "desc": "1. Vowel Counter"},
"2": {'package': "BasicCalculator", "desc": "2. Basic Calculator"}
}
for item in programs.values():
print(item['desc'])
program_idx = input("Select a Program by Choosing its number: ")
imp_module = importlib.import_module(programs[program_idx]['package'])
main_method = getattr(imp_module, "main")
main_method()
You are reading the program variable as int here
program = int(input("Select a Program by Choosing its number: "))
Then you are checking the value as string
if program == "1" :
It must be
if program == 1 :
I think that should be the problem. If not you will get the real problem after this!
import os
print("Welcome")
print("Programs.")
print("1. Vowel Counter")
print("2. Basic Calculator")
print("3. Odd Even")
program = input("Select a Program by Choosing its number: ")
programs = ["1", "2", "3"]
program_files = {'1': 'VowelCounter', '2': 'BasicCalculator', '3': 'OddEven'}
if program in "123" :
cmd = f'python {program_files[program]}.py'
print('Running -->', cmd)
os.system(cmd)
This question already has answers here:
How can I select a variable by (string) name?
(5 answers)
Closed 4 months ago.
I am trying to make my function take an name from the user which would check if the name is in a whitelist before executing a function that prints draws out information from a pre-defined list of the same name but the entered input is being processed as a string by the function instead of the name of the list. How do I get it to take in the input as the name of the list?
hydrogen = ["Hydrogen", "H", "1", "1.0"]
helium = ["Helium", "He", "2", "4.0"]
universe = ["hydrogen", "helium"]
elementname_print = "Element Name: "
elementsymbol_print = "Element Symbol: "
atomicnumber_print = "Atomic Number: "
relativeatomicmass_print = "Relative Atomic Mass: "
def printelement(element):
print(f" \n-------------------------")
print(elementname_print + element[0])
print(elementsymbol_print + element[1])
print(atomicnumber_print + element[2])
print(relativeatomicmass_print + element[3])
print("-------------------------")
userinput = input("-->")
if userinput in universe:
printelement(userinput)
else:
print("Sorry that element cannot be found.")
Result:
--> hydrogen
Element Name: h
Element Symbol: y
Atomic Number: d
Relative Atomic Mass: r
You should, rather than defining your elements in global scope as hydrogen = ..., define them inside a dictionary keyed by their name.
elements = {"hydrogen": ["Hydrogen", "H", "1", "1.0"],
"helium": ["Helium", "He", "2", "4.0"]}
the lookup then becomes much easier.
def print_element(element_name):
element = elements[element_name]
# the rest as written
Note that you can clean up your code quite a bit:
elements = {"hydrogen": ["Hydrogen", "H", "1", "1.0"],
"helium": ["Helium", "He", "2", "4.0"]}
def print_element(element_name):
element = elements[element_name]
name, symbol, number, mass = element
print(f"""
----------------------
Element Name: {name}
Element Symbol: {symbol}
Atomic Number: {number}
Relative Atomic Mass: {mass}
----------------------""")
userinput = input("-->")
if userinput in elements:
print_element(userinput)
else:
print("Sorry that element cannot be found.")
There are ways to make your chosen solution work (eval will do it, but introduce huge security risks. globals() will do it, but introduce a large performance overhead), but they're all ugly. Writing an ugly hack is objectively worse than using the right approach in the first place
You can eval the string input to the corresponding variable :
printelement(eval(userinput))
Rest code remains the same.
P.S : This is a quick hack, using eval is unsafe.
Basically your need to get a list corresponding to the user input. Use globals():
lst = globals()[userinput]
So in your example, if user types in 'hydrogen', this will give the list hydrogen. Now do your printings.
Complete example:
hydrogen = ["Hydrogen", "H", "1", "1.0"]
helium = ["Helium", "He", "2", "4.0"]
universe = ["hydrogen", "helium"]
elementname_print = "Element Name: "
elementsymbol_print = "Element Symbol: "
atomicnumber_print = "Atomic Number: "
relativeatomicmass_print = "Relative Atomic Mass: "
def printelement(element):
print(f" \n-------------------------")
print(elementname_print + element[0])
print(elementsymbol_print + element[1])
print(atomicnumber_print + element[2])
print(relativeatomicmass_print + element[3])
print("-------------------------")
userinput = input("-->")
if userinput in universe:
lst = globals()[userinput]
printelement(lst)
else:
print("Sorry that element cannot be found.")
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 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...