Syntax error when creating simple python program - python

Hope you are all well.
Trying to create a Python program which acts as a dictionary however now having some issues with creating an elif statement. Im my IDLE I keep getting signs saying that my syntax is wrong for the elif, I am not quite what I am doing wrong though? I suppose it is an indentation error but what exactly is it?
if choice == "0":
print "good bye"
elif choice == "1":
name = raw_input("Which philosopher do you want to get")
if name in philosopher:
country = philosopher [name]
print name, "comes from" , country
else:
print "No such term"
***elif choice == "2" :*** ***<<I am being told that I have syntax error in this elif element, what am I doing wrong)**
name = raw_input(" What name would you like to enter")
if name not in philosopher:
country = raw_input( "Which country do you want to put your philosopher in")
philosopher [name] = country
print name, "has now been added and he is from", country
else:
print "We already have that name"

Assuming you fix the indentation, the if statements all go in this order for you:
if x:
#do something
elif x:
#do something
if x:
#do something
else:
#do something
elif x:#CAUSES ERROR
#do something
if x:
#do something
else:
#do something
Your elif comes AFTER an else statement. You can't do this. elif MUST go between if and else. Otherwise the compiler doesn't ever catch the elif (Because it just ran through and did the else statement). In other words, you must have your if statements ordered like so:
if x:
#do something
elif x:
#do something
else:
#do something

I think that you are correct as to an indentation problem. Here is what I think you are trying to do:
if choice == "0":
print "good bye"
elif choice == "1":
name = raw_input("Which philosopher do you want to get")
if name in philosopher:
country = philosopher [name]
print name, "comes from" , country
else:
print "No such term"
elif choice == "2" :
name = raw_input(" What name would you like to enter")
if name not in philosopher:
country = raw_input( "Which country do you want to put your philosopher in")
philosopher [name] = country
print name, "has now been added and he is from", country
else:
print "We already have that name"
The key problem is inconsistent indentation, which makes it hard for Python to determine what you want. Until you develop your own style and have a good reason for doing otherwise, a consistent four spaces of indentation per level is a good habit. Let your editor help you indent consistently. Oh, and make sure not to mix tabs and spaces when you indent: that has a way of seeming to work for a bit and then coming back and biting you.

It looks like you want to put your if name in philosopher...No such term" section inside of the block beginning elif choice == "1":. If so, you need to indent one additional time in order for Python to properly group your if, elif and else statements.
if choice == "0":
# code
elif choice == "1":
if name in philospher: # indented twice; can only run if choice == "1"
# code
else:
# code
elif choice == "2":
# code
# rest of code

Related

Creating a Python game, working with returns in-between multiple modules

No matter how many times I google variations of my question, I cannot seem to find a solution. I am a beginner programmer, trying to build a game that randomly generates events as you progress through the stages. The problem I am running into are return statements, and passing the values between different modules. Each method for each file are inside of classes. They are all static methods, and calling these methods is not my problem. It is transferring the value of the variables. I'm not sure where I am going wrong, whether it is how I am structuring it, or if I just don't understand how these return statements work.
This is the first File I am starting from. Print statements will be filled out after everything functions properly.
def story():
print("---Intro Story Text here--- ... we will need your name, Traveler. What might it be?")
user_prompt = Introduction.PlayerIntroduction
name = user_prompt.player_info(1)
print(f"Welcome {name}!")
print(f"----After name is received, more story... how old might you be, {name}?")
age = user_prompt.player_info(2)
This is the file I am trying to get the values from. File: Introduction, Class: PlayerIntroduction
#staticmethod
def player_info(funct_select):
if funct_select == 1:
name = PlayerIntroduction.get_player_name()
player_name = name
elif funct_select == 2:
age = PlayerIntroduction.get_player_age()
player_age = age
return player_name, player_age
#staticmethod
def get_player_name():
print("\n\n\nWhat is your name?")
players_name = input("Name: ")
while True:
print(f"Your name is {players_name}?")
name_response = input("Yes/No: ")
if name_response == "Yes" or name_response == "yes":
name = "Traveler " + players_name
break
elif name_response == "No" or name_response == "no":
print("Let's fix that.")
PlayerIntroduction.get_player_name()
else:
print("Please respond with 'Yes' or 'No'.")
return name
#staticmethod
def get_player_age():
print("\n\n\nHow old are you?")
age = input("Age: ")
while True:
print(f"Your age is {age}?")
age_response = input("Yes/No: ")
if age_response == "Yes" or age_response == "yes":
break
elif age_response == "No" or age_response == "no":
print("Let's fix that.")
PlayerIntroduction.get_player_age()
else:
print("Please respond with 'Yes' or 'No'.")
return age
I would like to use the values for "name" and "age" throughout multiple modules/multiple methods within my program. But in order to get those values, I need to assign a variable to the function call.. Resulting in prompting the user to re-enter their name/age at later stages in the game. My idea to combat this was in the first method of this module, creating a conditional statement "if 'example' == 1: 'run the name prompt' and elif == 2: run age prompt, thinking the initial run with the arguments defined would run these prompts, store the values into the variables (name, age), and finally pass the values to the new variables that are NOT assigned to the function call (p_name, p_age), avoiding triggering the user prompt over and over. Ultimately, this failed, and as the code sits now I am getting:
UnboundLocalError: local variable 'player_age' referenced before assignment
Why is this? The only instance 'player_age' is called that is reachable at this point is in the return statement, indented in-line with the conditional statement. The code should read (If I understand incorrectly, please explain) from top to bottom, executing in that order. The 'if' condition is met, so it should run that. If I were to define 'player_name' and 'player_age' as null at the top of this method to avoid this error, then every time I would need to reference these values initially entered by the user, they would be re-assigned to 'null', negating everything I am trying to do.
Thank you all for your patience, I tried to explain what I was doing and my thought process the best I could. Any feedback, criticism, and flaws within my code or this post are GREATLY appreciated. Everything helps me become a better programmer!! (:

User input for gender not functioning

I am attempting to make a game that I made via Rpg Maker MV in python but I've hit a road block in the if statement or rather the gender input. The code is meant to have the user input either "Boy" or "Girl" and depending on that the variable "gender" will be set for pronouns. How ever the console is saying This
This is the code
import time
print ("Elvoria")
print ("Start")
input = input()
if input == ("Start"):
print ("Always Great To See New People")
time.sleep(1)
print ("Now Are You A Boy Or Girl")
genderin = input()
if input == ("Boy"):
gender = 1
elif input == ("Girl"):
gender = 2
else:
print ("Error")
You need to check the input using the variable name genderin that you defined, instead of input == ("Boy").
EDIT: Also, you are mirroring the built-in method input() with the variable name input and you should not do that. Rename your variable to e.g. start_input.
import time
print ("Elvoria")
print ("Start")
start_input = input()
if start_input == "Start":
print ("Always Great To See New People")
time.sleep(1)
print ("Now Are You A Boy Or Girl")
genderin = input()
if genderin == "Boy":
gender = 1
elif genderin == "Girl":
gender = 2
else:
print ("Error")
You're defining the variable "input" on line 4 to be a string, given from the "input" function. This overrides the keyword. Then, on line 9, you're calling "input" again. Since you've replaced the built-in function with a string, an error is thrown (the error "not callable" means that you're trying to treat a non-function like a function).
Here's your code sample, without overriding built-in methods:
import time
print ("Elvoria")
print ("Start")
user_input = input()
if user_input == ("Start"):
print ("Always Great To See New People")
time.sleep(1)
print ("Now Are You A Boy Or Girl")
genderin = input()
if genderin == ("Boy"):
gender = 1
elif genderin == ("Girl"):
gender = 2
else:
print ("Error")
You should avoid using input as a varible name, since a built-in function with that name already exists, input(). So just change it's name to something else. Secondly, you're storing the gender input (boy/girl) in genderin, but then checking input, when you should be checking genderin. So the code after fixing these would look something like this:
import time
print ("Elvoria")
print ("Start")
choice = input()
if choice == "Start":
print("Always Great To See New People")
time.sleep(1)
print("Now Are You A Boy Or Girl?")
genderin = input()
if genderin == "Boy":
gender = 1
elif genderin == "Girl":
gender = 2
else:
print("Error")
I have used choice for demonstration purposes, you can use a different name if you want, just remember to make sure that a python built-in with that name doesn't exist. Also, no need to put ("Start") in the if statement, use "Start" instead (same goes for other if/elif statements)
You have also used print ("example") (space between print and brackets), i've rarely ever seen someone using this, most people use print("example") instead.
Finally a tip -> You can make the string lowercase, genderin = genderin.lower() to manage case sensitivity, i.e, both boy and Boy will be valid inputs, etc.

errors with Elif expected indented block

I'm trying to create a menu for my application, the menu has 4 options and each of these options should return with the correct information when the user has entered the chosen value. i keep getting an error with the Elif statements.
I am a newbie so please understand where am coming from.
much appreciation.
when i indent the while ans: i will receive an error says invalid syntax after indenting the elif ans==2.
elif ans==2 <--- this error keeps saying indention block error or syntex invalid when i indent it.
def print_menu(self,car):
print ("1.Search by platenumber")
print ("2.Search by price ")
print ("3.Delete 3")
print ("4.Exit 4")
loop=True
while loop:
print_menu()
ans==input("Please choose from the list")
if ans==1:
print("These are the cars within this platenumber")
return platenumber_
while ans:
if ans==2:
elif ans==2:
print("These are the prices of the cars")
return price_
elif ans==3:
print("Delete the cars ")
return delete_
elif ans==4:
return Exit_
loop=False
else:
raw_input("please choose a correct option")
You have a while loop without a body. Generally speaking, if there is an indentation error message and the error is not on the line mentioned, it's something closely above it.
loop=True
while loop:
print_menu()
ans = int(input("Please choose from the list"))
if ans==1:
print("These are the cars within this platenumber")
# return some valid information about plate numbers
elif ans==2:
print("These are the prices of the cars")
# return some valid information about pricing
elif ans==3:
print("Delete the cars ")
# Perform car deletion action and return
elif ans==4:
# I am assuming this is the exit option? in which case
# return without doing anything
else:
# In this case they have not chosen a valid option. Send
# A message to the user, and do nothing. The while loop will run again.
print("please choose a correct option")
Also, your code is a bit confusing to me. It looks like you're going to return car_ no matter what, which means your loop will only execute once. Also, = is assignment and == is equality. Be careful.

How to have if and elif in functions

First off. My code:
UserInput = ("null") #Changes later
def ask_module(param, param2):
elif UserInput == (param):
print(param2)
while True:
UserInput = input()
UserInput = UserInput.lower()
print()
if UserInput == ("test"):
print("test indeed")
ask_module("test2", "test 2")
I am not that good at coding, so this is probably something that I have done really wrong
This post seems a bit duchy, since I almost just have code,
but I have absolutely no idea on how to make this work.
What the code looks like without shortening:
while True:
UserInput = input()
UserInput = UserInput.lower()
print()
if UserInput == ("inventory"):
print("You have %s bobby pin/s" %bobby_pin)
print("You have %s screwdriver/s" %screwdriver)
elif UserInput == ("look at sink"):
print("The sink is old, dirty and rusty. Its pipe has a bobby pin connected")
else:
print("Did not understand that")
EDIT: I see that it might be hard to see what I'm asking.
I'm wondering how I can shorten my original code
If all your elif blocks have the same pattern, you can take advantage of this.
You can create a dictionary for the text you want to print and then do away with the conditionals.When it comes to choosing which one to print, you simply fetch the relevant text using its corresponding key. You use the get(key, default) method. If there is no key in the dictionary, the default value will be returned. For example,
choices = {'kick': 'Oh my god, why did you do that?',
'light him on fire': 'Please stop.',
'chainsaw to the ribs': 'I will print the number %d',
}
user_input = input().lower()
# individually deal with any strings that require formatting
# and pass everything else straight to the print command
if user_input == 'chainsaw to the ribs':
print(choices[user_input] % 5)
else:
print(choices.get(user_input, 'Did not understand that.'))
I found a solution, just stop using elif entirely.
Example:
userInput = "null"
def ask_question(input, output):
if userInput == (input):
print(output)
else: pass
while True:
userInput = input()
ask_question("test","test")
ask_question("test2", "test2")
ask_question("test3", "test3")

Simple Phonebook

this is some simple code I wrote for a phonebook.
It does not seem to work though, and I do not know why.
I am very new to python, and I am sure there are many errors.
def startup(contactlist = {}):
print "Welcome to Contacts+\n"
print "Please enter your name"
name = raw_input()
print "Hi " + name + " would you like to check your existing contacts or make new ones?"
print "To make new contacts type in 'New'"
print "To check existing contacts type in 'Contacts'"
choose = ""
choose = raw_input()
if choose == "'New'" or choose == "'new'" or choose == "New" or choose == "new":
newcontact()
elif choose == "'Contacts'" or choose == "'contacts'" or choose == "Contacts" or choose == "contacts":
checkcontact()
def newcontact():
startup(contactlist = {})
print "To create a new contact please first input the name"
contactname = raw_input()
print "Next enter the phone number"
contactnumber = raw_input()
print "Contact created!"
contactlist[name] = number
def checkcontact():
startup(contactlist = {})
print contactlist
startup()
Have you tried to run this...?
This if/elif statement shouldn't be indented:
if choose == "'New'" or choose == "'new'" or choose == "New" or choose == "new":
newcontact()
elif choose == "'Contacts'" or choose == "'contacts'" or choose == "Contacts" or choose == "contacts":
checkcontact()
And why do you have:
startup(contactlist = {})
in the beginning of newcontact() and checkcontact() function?
Four things you can do right now to make your code better:
Go read about this gotcha in Python. We tricked you. (We're sorry! We had good reasons.) You can't really do that with lists and dicts, and you have to use a Python idiom involving None to do it right.
Use raw_input's first argument. Instead of print('Hey user!'); raw_input(), just write raw_input('Hey user!').
Learn the in keyword. Whenever you find yourself saying if x == 'x' or x == 'y' or x == 'z', it's probably easier to write if x in 'xyz' (strings are iterable, remember?). You can also get rid of two of those cases by stripping off quotes the user might enter if you don't want them -- choose.strip("'").
Fix your function calls. Functions in Python can be called in two ways, using positional arguments f(a, b, c) or keyword arguments f(a, b=0, c=2). Calls like startup(contactlist={}) are just explicitly setting that argument to the empty dict, its default value, so this is always equivalent to startup() the way you have it defined.

Categories

Resources