Python Syntax Error: expected an intended block - python

So first i clicked on Run Module
Then this came up
My code
import time
print("First we need to know you.")
print("Enter your name please.")
time.sleep(2)
name = input("Name: ")
print("Welcome, " + name + "!")
time.sleep(3)
criminal = input("Are you a criminal?: ")
if criminal=='Y':
Right here it highlights print as red
print('Oh no')
elif criminal=='N':
print('Thank god!')

You need to indent after an if and the elif:
if criminal=='Y':
print('Oh no')
elif criminal=='N':
print('Thank god!')
Also, don't indent after the import:
import time
print("First we need to know you.")

You have to indent the print('Oh no'):
if criminal=='Y':
print('Oh no')
elif criminal=='N':
print('Thank god!')

Related

how to fix syntax error while if...else statement?

import webbrowser
Character_Name = "Random"
Character_Age = "14"
input("Name of the person you want the ID of.")
print("Here's The Information That I Have: Name:" + Character_Name + ", Age:" + Character_Age + ", Available socialmedia accounts: (insta) www.instagram.com/asenpai369")
a = input("Should i open the link in your web browser?")
if a : "Yes"
webbrowser.open("www.instagram.com/idksoumyadeep")
else:
print("okay, if its a mistype then please type it again")
and the error
else:
^
SyntaxError: invalid syntax
please help thanks in advance :))
It should be
if a == "Yes": webbrowser.open("www.instagram.com/idksoumyadeep")
else: print("okay, if its a mistype then please type it again")
Use indentation after the if and else:
import webbrowser
Character_Name = "Random"
Character_Age = "14"
input("Name of the person you want the ID of.")
print("Here's The Information That I Have: Name:" + Character_Name + ", Age:" + Character_Age + ", Available socialmedia accounts: (insta) www.instagram.com/asenpai369")
a = input("Should i open the link in your web browser?")
if a == "Yes":
webbrowser.open("www.instagram.com/idksoumyadeep")
else:
print("okay, if its a mistype then please type it again")

Is there anyway to use 'return' outside a function block to go back to my variable from 'else'?

I've been facing this problem for a bit now. I know that the 'return' command can't work outside a function, but is there an alternative to this or is there a need to define a new function?:
print("Are you", userage(), "years old?")
userinput = input()
if userinput == "yes":
print("Ok, lets get on with the program")
elif userinput =="no":
print("Oh, let's try that again then")
userage()
else:
print("please answer yes or no")
return userinput
Btw, sorry for all the mistakes I make. I'm still a beginner.
You need to use a while loop here:
while (True):
userinput = input("Are you xxx years old?\n")
if userinput == "yes":
print("Ok, lets get on with the program")
break
elif userinput == "no":
print("Oh, let's try that again then")
else:
print("please answer yes or no")
The loop will ever only break when someone types in yes.

Try Except Block not passing after correct input

I'm new to Python and coding in general, and ran into a bit of a bug in my code. Whenever i type in the wrong input in my Try/Except code block, the console prints "Invalid input" However, whenever i type in the correct phrase in the console, it still says "Invalid input". I looked online to try to fix this issue (notated with ##) with these lines of code, but i still get the same issue.
For example, I would type in "Mad Libs" with correct case and everything, and still get "Invalid input" from my != command. Could this be easily fixed by formatting in a different way? This happens with all 3 games.
How can this issue be addressed? Thanks in advance!
def game_selection(): ##
pass ##
while True: ##
try:
playerChoice = input("So, which game would you like to play?: ")
if playerChoice != "Mad Libs":
print("Invalid input")
elif playerChoice != "Guessing Game":
print("Invalid input")
elif playerChoice != "Language Maker":
print("Invalid input")
continue ##
except:
print("Invalid Input")
game_selection() ##
print("Got it! " + playerChoice + " it is!")
sleep(2)
if playerChoice == "Mad Libs":
print("Initializing 'Mad Libs'.")
sleep(.5)
print("Welcome to MadLibs, " + playerName + "! There are a few simple rules to the game.")
print("All you have to do is enter in a phrase or word that is requested of you.")
playerReady = input("Ready to begin? Y/N")
Because you asked it to answer invalid input anyway in this code
While True: ##
try:
playerChoice = input("So, which game would you like to play?: ")
if playerChoice != "Mad Libs":
print("Invalid input")
elif playerChoice != "Guessing Game":
print("Invalid input")
elif playerChoice != "Language Maker":
print("Invalid input")
continue ##
except:
print("Invalid Input")
The thing is, this code will not work because if I enter "Mad Libs" the first if will not pass and so it will pass to all the others elif. So you can't take this approach.
What I advice you to do is to check if the playerChoice string is in an array
from time import sleep
while True:
playerChoice = input("So, which game would you like to play?:")
allowedGames = ["Mad Libs", "Guessing Game", "Language Maker"]
if playerChoice not in allowedGames:
print('Invalid input!')
else:
break
print("Got it! " + playerChoice + " it is!")
sleep(2)
if playerChoice == "Mad Libs":
print("Initializing 'Mad Libs'.")
sleep(.5)
print("Welcome to MadLibs, " + playerName + "! There are a few simple rules to the game.")
print("All you have to do is enter in a phrase or word that is requested of you.")
playerReady = input("Ready to begin? Y/N")

Is there anyway way to shorten this?

Very beginner programmer here in the process of learning. I am just wondering if this simple code I have typed is the most optimal way to do it.
with open('guest_book.txt', 'a') as file_object:
while True:
name=input("What is your name?")
print("Welcome " + name + ", have a nice day!")
file_object.write(name + " has visited! \n")
another = input("Do you need to add another name?(Y/N)")
if another == "y":
continue
elif another == "n":
break
else:
print("That was not a proper input!")
while True:
another = input("Do you need to add another name?(Y/N)")
if another == "y":
a = "t"
break
if another == "n":
a = "f"
break
if a == "t":
continue
else:
break
My questions is in the if statements. When I ask the input("Do you need to add another name?(y/n)", is what I have typed the best way to re-ask the question if I get an answer other than y or n. Basically I want the question to be repeated if I don't get either a yes or no answer, and the solution I found does not seem like the most optimal solution.
You are basically there. You can simply:
with open('guest_book.txt', 'a') as file_object:
while True:
name=input("What is your name?")
print("Welcome " + name + ", have a nice day!")
file_object.write(name + " has visited! \n")
another = input("Do you need to add another name?(Y/N)")
if another == "y":
continue
elif another == "n":
break
else:
print("That was not a proper input!")
continue
You can use function to write your all logic at one place.
def calculate(file_object):
name=raw_input("What is your name?")
print("Welcome " + name + ", have a nice day!")
file_object.write(name + " has visited! \n")
another = raw_input("Do you need to add another name?(Y/N)")
if another == "y":
calculate(file_object)
elif another == "n":
return
else:
print("That was not a proper input!")
calculate(file_object)
if __name__=='__main__':
with open('guest_book.txt', 'a') as file_object:
calculate(file_object)
You can do it this way, but there will not be any invalid input for saying no. It will only check for saying y
with open('guest_book.txt', 'a') as file_object:
another = 'y'
while another.lower() == 'y':
name=input("What is your name?")
print("Welcome " + name + ", have a nice day!")
another = input("Do you need to add another name?(Y/N)")

local variable referenced before assignment python issue

So I'm coding a small project and I'm struggling with a certain aspect so far.
Here is the code:
import re
def clientDetails():
print("Welcome to the InHouse Solutions Room Painting Price Calculator")
print("STEP 1 - CLIENT DETAILS")
print("Please enter your full name")
userName = input(">>>")
print("Please enter your post code")
postCode = input(">>>")
print("Is your house a number, or a name?")
nameOrNumber = input(">>>")
if nameOrNumber == "number" or nameOrNumber == "Number":
print("Please enter your house number")
houseNumber = input(">>>")
elif nameOrNumber == "Name" or nameOrNumber == "name":
print("Please enter your house name")
houseName = input(">>>")
else:
print("Invalid")
house = (houseNumber) + (houseName)
address = (postCode) + ", " + (house)
print("Thank you for your information")
print (userName)
print (address)
print (" ")
print ("Is this information correct? Pleast enter Yes or No")
clientDetailsCorrect = input(">>>")
if clientDetailsCorrect == "no" or clientDetailsCorrect == "No":
clientDetails()
clientDetails()
Not sure what's going wrong as I haven't actually referenced the variable anywhere else. Someone help.
It would help if you posted the traceback.
That said, this line is the likely source of the problem:
house = (houseNumber) + (houseName)
The way your code is currently written, only one of houseNumber or houseName will be defined. So Python is likely complaining about the missing one.
Given how your code looks so far, it's probably better to just do:
print("Please enter your house name or number")
house = input(">>>")
And remove the house = (houseNumber) + (houseName) line.
Try this:
def clientDetails():
print("Welcome to the InHouse Solutions Room Painting Price Calculator\n")
print("STEP 1 - CLIENT DETAILS")
print("Please enter your full name")
userName = raw_input(">>>")
print("Please enter your post code")
postCode = raw_input(">>>")
print("Please enter your hose number or name")
house = raw_input(">>>")
address = "{}, {}".format(postCode, house)
print("Thank you for your information.\n")
print (userName)
print (address)
print (" ")
print ("Is this information correct? Pleast enter Yes or No")
clientDetailsCorrect = raw_input(">>>")
if clientDetailsCorrect.lower().startswith('n'):
clientDetails()
Using raw_input is better, it will input everything as a string. Also it will allow users to not type quotations to input text (I assume you will run this from CLI). If you later on need to separate houses that are numbers from names Python has very good string methods you can use to do so many wonderful things, I used a couple of them to simplify your code :)
N

Categories

Resources