Noob with a syntax error in dictionary (python) - python

I am trying to learn Python following the tutorial from Programming with Mosh.
I have created a program that starts up and greets me and then asks me to select an item on a list. Each list item is a "sub-program" that the tutorial covers. So I have two sub-programs in my program:
A chat translator that should return text and, via a dictionary, convert :) and :( to emojis
Then also a square calculator.
The problem I am facing is that my chat translator runs into a syntax error in the dictionary. This is where the error happens, at the first quotation mark in line 2 of the dictionary:
C:\Users\smelt\PycharmProjects\HelloWorld\venv\Scripts\python.exe C:/Users/smelt/PycharmProjects/HelloWorld/venv/app.py
File "C:\Users\smelt\PycharmProjects\HelloWorld\venv\app.py", line 41
":(": emoji.emojize(":frowning_face:")
^
SyntaxError: invalid syntax
Part of the code the error happens in:
def emoji_converter(message):
words = message.split(" ")
emojis = {
":)": emoji.emojize(":smiling_face:"),
":(": emoji.emojize(":frowning_face:")
}
output = ""
for word in words:
output += emojis.get(word, word) + " "
return output
This is my entire code:
first_name = "Henrik"
last_name = "Skaaning"
program_on = True
calculator_on = False
emoji_converter_on = False
def greet_user(first_name, last_name):
# Standard greeting to user
print(f"""Hi {first_name} {last_name}!
Welcome back!
""")
if program_on:
while program_on:
greet_user(first_name, last_name)
selection = input(f"""This is Training program for Henrik Skaaning.
please enter a number to select a program to run
1: Emoji converter
2: Square calculator
enter "quit" to quit program...
selection> """)
if selection == "1":
emoji_converter_on = True
print(f'Emoji converter on')
while emoji_converter_on:
import emoji
def emoji_converter(message):
words = message.split(" ")
emojis = {
":)": emoji.emojize(":smiling_face:"),
":(": emoji.emojize(":frowning_face:")
}
output = ""
for word in words:
output += emojis.get(word, word) + " "
return output
message = input("message> ")
if message != "help":
if message != "quit":
print(emoji_converter(message))
if message == "help":
print(f"""This is a simple emoji converter developed by Henrik Skaaning.
Type a text in the command line with an emoji to return the text and emoji.
Type "help" in the command line to return the help-menu.
Type "quit" in the command line to quit the application. """)
if message == "quit":
emoji_converter_on = False
print(f'Emoji converter shutting off')
if selection == "2":
calculator_on = True
print(f'Square calculator on')
while calculator_on:
def square(number):
return int(number) * int(number)
number = input("commandline> ")
if number == "quit":
program_on = False
calculator_on = False
print(f'Executing')
if number != "quit":
if number != "help":
if number.isnumeric() != True:
print(f"Sorry! That isnt a command i understand")
if number == "help":
print(f"""This is a simple square calculator developed by Henrik Skaaning.
Type a number in the command line to return the square of that number
Type "help" in the command line to return the help-menu.
Type "quit" in the command line to quit the application. """)
if number.isnumeric():
result = square(number)
print(f' The result is {result}')
if program_on == False:
print(f'Program shut down')
print(f'Done...')

While it is possible to define a function within another function, and sometimes using a closure makes things easier, this code has a really long mainline with a function defined within a while loop. This code would be better and easier to understand if it was written with the functions separated. Otherwise, as you now know, it can be hard to debug.
The actual problem is that you have confused the syntax for a Python dict and JSON. A dict requires symbol / value pairs, while JSON requires string / value pairs.
Below is a reorganized program for you. The bug was not corrected.
first_name = "Henrik"
last_name = "Skaaning"
program_on = True
calculator_on = False
emoji_converter_on = False
def emoji_converter(message):
words = message.split(" ")
emojis = {
":)": emoji.emojize(":smiling_face:"),
":(": emoji.emojize(":frowning_face:")
}
output = ""
for word in words:
output += emojis.get(word, word) + " "
return output
def greet_user(first_name, last_name):
# Standard greeting to user
print(f"""Hi {first_name} {last_name}!
Welcome back!
""")
if program_on:
while program_on:
greet_user(first_name, last_name)
selection = input(f"""This is Training program for Henrik Skaaning.
please enter a number to select a program to run
1: Emoji converter
2: Square calculator
enter "quit" to quit program...
selection> """)
if selection == "1":
emoji_converter_on = True
print(f'Emoji converter on')
while emoji_converter_on:
import emoji
message = input("message> ")
if message != "help":
if message != "quit":
print(emoji_converter(message))
if message == "help":
print(f"""This is a simple emoji converter developed by Henrik Skaaning.
Type a text in the command line with an emoji to return the text and emoji.
Type "help" in the command line to return the help-menu.
Type "quit" in the command line to quit the application. """)
if message == "quit":
emoji_converter_on = False
print(f'Emoji converter shutting off')
if selection == "2":
calculator_on = True
print(f'Square calculator on')
while calculator_on:
def square(number):
return int(number) * int(number)
number = input("commandline> ")
if number == "quit":
program_on = False
calculator_on = False
print(f'Executing')
if number != "quit":
if number != "help":
if number.isnumeric() != True:
print(f"Sorry! That isnt a command i understand")
if number == "help":
print(f"""This is a simple square calculator developed by Henrik Skaaning.
Type a number in the command line to return the square of that number
Type "help" in the command line to return the help-menu.
Type "quit" in the command line to quit the application. """)
if number.isnumeric():
result = square(number)
print(f' The result is {result}')
if program_on == False:
print(f'Program shut down')
print(f'Done...')
Now that you know you need a symbol instead of strings like ":)" and ":(", can you fix it yourself?
Hint: use string substitution instead of a dict. Convert all ":)" strings to ":smiling_face:", and ":(" strings to ":frowning_face:", like:
message.replace(":)", ":smiling_face:").replace(":(", ":frowning_face:")
The corrected program should be noticeably shorter.

The code you have posted is not the code you ran to generate that error message. It does not give a syntax error and the line in the error is now on line 33 not 41 as in the stacktrace.
My guess is that you missed the comma after the first dict entry
emojis = {
":)": emoji.emojize(":smiling_face:")
":(": emoji.emojize(":frowning_face:")
}
gives the error you got.

Related

Why is PyCharm giving error in input() and print() functions - 'Unresolved Reference'?

All of my other files (leaving a sopecific) in the project are without error.
Its as shown, only 'Magic-I' is having a problem with print() and input()
I shall give you the whole code:
outcome = {
"hi": "Hello",
"hello": "Hi",
"what's your name": "Magic-I !",
"this": "'this' what?",
"you are mad": "You too.....LEL !!!",
"your hobby": "Solving problems",
"fuck off": ".........",
"i like you": "Me too",
}
help = '''
'calculate' - addition ; subtraction ; multiplication ; division.
'car game' - simple car simulator.
'guess game' - launch a simple guessing game.
'rbi' - launch RBI.
'bye' - exit AI
||type 'help' whenever you need to know these commands||
*It also chat*
'''
print("----------------------------------------------------------------------------------------------------------")
print("\nThis is an AI - 'MAGIC I' !")
print("It chats and complete several other tasks !")
print("\nSome key features (type these to access them): ")
print(help)
k = ""
while True:
res = input("\n> ").lower()
if res in outcome:
k = outcome.get(res)+" !"
print(k)
elif "name" in res:
print("Magic-I !")
elif "fuck" in res:
print('........')
elif "parent" in res:
print("Rakshit")
elif "master" in res:
print("Rakshit")
elif "coder" in res:
print("Rakshit")
elif "programmer" in res:
print("Rakshit")
elif "calc" in res:
import calculator
calculator.calculator()
elif 'car' in res:
import CarGame
elif 'guess' in res:
import GuessGame
elif 'rbi' in res:
import RBI
elif 'ac' in res:
print("Turn it on !!!")
elif 'help' in res:
print(help)
elif res == "bye":
print("Bye..!")
break
elif res == "":
print("You haven't typed anything..!")
else:
print("No.!")
this is the code......if you want something else i can give you...please help !!!
Folder:
Hey, when I tried to fix the print() problem it was showing install print() package, something like that...when I clickd it, I got an error:
maybe you should remove the pythonpath variable in your ~/.bash_profile
you can do that by using:-
#export PYTHONPATH=/usr/local/lib/python2.7/site-packages/
I found the solution by changing the text quotations in my input and print, instead of :
variable = input("Some Text")
Try this :
variable = input('Some Text')
It worked well with single quotes in my code

SyntaxError while trying to do my hangman game in Python

I'm trying to make a Hangman game using a TextFile as database for the words (but that is not why I am here for)
I'm trying to execute my script to start the game, so I can try it but I keeps throwing me the following SyntaxError:
SyntaxError: unexpected character after line continuation character
here is the code:
import os
import random
#creation of the program
if not os.path.exists('hangman_folder'):
print("folder created in dir: " .format(os.getcwdb()))
os.makedirs('hangman_folder')
os.chdir('hangman_folder')
else:
print("folder already on file")
os.chdir('hangman_folder')
#words database
words_list = ["love", "crazy", "man", "natural", "girl"]
#function that is going to sort all the interesting words
# def detect_words():
def check_if_char(theChar, theWord):
howManyChars = len(theWord)
splitWord = list(theWord)
attempts = 0
success = 0
for i in range(howManychars):
position = i + 1
if theChar == splitWord[position]:
return position
print("yes! the letter is in the word ")
else:
attempts += 1
if attempts >= howManyChars:
failing = True
def hangItUp(hp):
hp -= 1
print("Your character is not on the string. Hanging him up!")
print("{} attempts remaining " .format(hp))
if hp <= 0:
userResponse = input("Game Over! Waiting for your response...")
if userResponse == "try again":
print("restarting the game.")
else:
print("Bye bye...")
def discover_the_word(usedChar, wordToDiscover, blankList):
revealedList = blankList
wordSplitted = list(wordToDiscover)
for letter in wordSplitted:
if usedChar == letter:
revealedList[revealedList.index(letter)] = usedChar
return revealedList
def listToString(s):
str1 = ""
for element in s:
str1 += element
return str1
#the entire game
def hangman_game():
#game starting, setting up the variables
lives = 6
selectedWord = random.choice(words_list) #selecting a random word
countBlankSpaces = len(selectedWord)
blankSpaces = []
#creating the blank spaces to guess the word
for i in range(countBlankSpaces):
blankSpaces.append("_")
yourWord = input("guess with a word")
if check_if_char(yourWord, selectedWord) == True:
blankSpaces = discover_the_word(yourWord, selectedWord, blankSpaces)
if listToString(blankSpaces) == selectedWord:
print("Congratulations! You win the Game")
else:
hangItUp(lives)
#checking in which directory are we
print(os.getcwdb())
hangman_game()
I finished this piece of code and tried to run it but I just can't find that "unexpected character after line continuation character", I just can't find in which line the error is.
You may change your IDE or something to get more information of your error. Mine(VScode) gives an error message of invalid syntax (<unknown>, line 32). There us no operator like => in Python.

Syntax Error Python 3.3.3 No Reason Given

my program keeps throwing up a syntax error with no reason given with this code and I cannot figure out why for the life of me. I've deduced that the error-causing lines are the ones I have hashed-out
#char = ord(message[i])-96
#key = ord(keyword[i])-96
They are in lines 15 and 16 of the code. Please help me!!!
option = input("Do you want to encrypt or decrypt? (E/D): ")
keyword = input("Enter your keyword: ")
message = input("Enter your message: ")
while len(keyword)<len(message):
keyword=keyword+keyword
keyword=keyword[:len(message)]
newMessage = ""
for i in range(len(message)):
char = ord(message[i])
key = ord(keyword[i])
if char==32:
newMessage = newMessage+" "
elif char<97 or char>122:
message = input("Enter your message: ")
#char = ord(message[i])-96
#key = ord(keyword[i])-96
elif option == "E":
if char+key>26:
newMessage = newMessage+chr(char+key-26)
else:
newMessage = newMessage+chr(char+key)
else:
if char-key<1:
newMessage = newMessage+chr(char-key+26)
else:
newMessage = newMessage+chr(char-key)
print(newMessage)
You are ending your if and subsequent elif with those two lines. As a result, elif option == "E": makes no sense as there is no preceding if statement before it. You either have to indent:
elif char<97 or char>122:
message = input("Enter your message: ")
char = ord(message[i])-96
key = ord(keyword[i])-96
Or begin a new if statement with your subsequent elif:
if option == "E":
if char+key>26:
newMessage = newMessage+chr(char+key-26)
else:
newMessage = newMessage+chr(char+key)
You have not indented (put 4 space before) the two lines. As your are in a if statement you have to put them.

Continuous results from a single function call

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...

Importing function in python

I am trying to create menu where user can choose which part of the program he/she wants to run. When I am importing function computer automatically runs it rather to wait for user input. What shall I do to run function only when called? My code:
import hangman
menu = raw_input("""Welcome to Menu, please choose from the following options:
1. Hangman game
2.
3.
4. Exit
""")
if menu == 1:
hangman()
elif menu == 2:
"Something"
elif menu == 3:
"Something"
elif menu == 4:
print "Goodbye"
else:
print "Sorry, invalid input"
The code for hangman.py looks like that:
import random
words = ["monitor", "mouse", "cpu", "keyboard", "printer",]
attempts = [] # Stores user input
randomWord = random.choice(words) # Computer randomly chooses the word
noChar = len(randomWord) # Reads number of characters in the word
print randomWord , noChar
print "Hello, Welcome to the game of Hangman. You have to guess the given word. The first word has", noChar, " letters."
def game():
guess = raw_input ("Please choose letter")
attempts.append(guess) # Adds user input to the list
print (attempts)
if guess in randomWord:
print "You have guessed the letter"
else:
print "Please try again"
while True:
game()
chance = raw_input ("Have a guess")
if chance == randomWord:
print "Congratulations, you have won!"
break
Without seeing hangman.py, I would assume that it directly contains the code for running the hangman game, not wrapped in a function. If that's the case, you created a module, no function (yet).
Wrap that code in
def run_hangman():
# Your existing code, indented by 4 spaces
# ...
import it like this:
from hangman import run_hangman
and finally call the function like this:
run_hangman()
So here is the start menu:
import hangman
option = raw_input('1) Start Normal\n2) Quick Start\n3) Default') # '\n' is a new line
if option == '1':
hangman.main()
elif option == '2':
hangman.run_hangman('SKIP')
elif option == '3':
handman.run_hangman('Default User')
Inside your hangman code you want to have it modulated. You should have somthing like this:
def main():
stuff = raw_input('Starting new game. Please enter stuff to do things')
run_hangman(stuff)
def run_hangman(options):
if options == 'SKIP':
important_values = 5
vales_set_by_user = 'Player 1'
else:
values_set_by_user = options
rest_of_code()

Categories

Resources