I have a small code which is just for me to get more used to python and I have encountered a problem with try and except.
I am trying to get the code below to ask a question and receive an answer using raw_input. If you know what the syntax error in line 22 is? (except ValueError)
Thank you very much.
def start():
print("Type start")
prompt_sta()
def prompt_sta():
prompt_0 = raw_input ("Enter command start")
try:
if prompt_0 == "start":
prompt_sta()
elif prompt_0 == "begin":
print ("You must learn to follow commands")
prompt_sta()
elif promt_0 == "help":
print ("Commands:")
print ("Help")
print ("start")
print ("begin")
prompt_sta()
else:
print ("Please enter a valid command.")
prompt_sta()
print ("Type start")
**except ValueError:**
def outside_house():
print("There is a strange man outside.")
Just in case the error that IDEL is showing has ** on both sides and if you know any better ways for doing what I am trying to do please tell me. Thanks
You need to provide a body for except: statements:
try:
a = "something"
except ValueError:
pass # empty body
Related
I'm creating a simple login program. It asks you for a username, then the password. If you type the correct password, you're in, else, you get a genial request to repeat your password. here is the code:
while True:
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
break
break
else:
print ("Incorrect. You have",turns," more turns")
now the thing is, it gives me an error message: incorrect syntax for else: print ("incorrect... I know this is meant an issue because I wrote two 'breaks', the latter out of the for loop... which means it will break the while True loop at the start whether or not I go into the loop... which means the 'else' statement is out of the loop (sorry, I am not the best explainer at these things)... which gives the error message. But I don't understand how I should fix this problem... can anyone help?
I hope you understood me!
This could be triviallized by using a function and returning from it once you reach that if statement.
def func():
while True:
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
return
else:
print ("Incorrect. You have",turns," more turns")
However, if you insist on not having a function, you can basically have a flag in your code that you set to true inside that if block. Before continuing the outer loop, you should check if this flag is set to True, if it is, you can safely break.
while True:
success = False
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
success = True
break
else:
print ("Incorrect. You have",turns," more turns")
if success:
break
Note should be taken for nested loops and such intense nesting for what is essentially a trivial problem. Please try to use a singular loop with your conditions.
You need to swap the else and break and change the break's indentation. If the user gets the correct username you want to test the password at most 5 times and then quit
while True:
turns= 5
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
break
else:
turns -= 1
print ("Incorrect. You have",turns," more turns")
break
So in this case you run the for loop and then break
Well I have written your concept in my own way. Hope this works for you
turns = 5
while turns != 0:
username = input('Enter Username: ')
password = input(f'Enter password for {username}: ')
if username == 'test#test.test' and password == 'beta123':
print('Hello developer')
turns = 0 # Breaking while loop if user get access within number of "turns"
else:
turns = turns - 1 # Or turns -= 1
print('Incorrect username or password')
print(f'You have {turns} turns for gaining access')
i wrote an script , i want to know how to prevent when user enter number i show a message 'number is not OK! just string') .
Thanks.
#! /usr/bin/ipython3
a=input('Please enter your Name : ')
if a=='mohammadreza':
print(" ")
print ('i found you finally')
print(" ")
elif a=='':
print ('Null name is not ok!')
else:
print ('No you are not that person')
You have a string. And if you want to check if it is a number, you can use the following code:
a.replace('.','',1).isdigit()
So you can create a new elif like this:
elif a.replace('.','',1).isdigit():
print("number is not OK! just string")
problem here is input always return a string. isdigit handle this for you but it fails with floats (this is the reason behind "replace . solution").
Another approach could be:
#!/usr/bin/env python
def is_a_number(s):
'''try to convert a string to int and float'''
try:
int(s)
return True
except:
pass
try:
float(s)
return True
except:
pass
return False
def main():
a=input('Please enter your Name : ')
if a=='foo':
print ('i found you finally')
elif is_a_number(a):
print('number is not OK! just string')
elif a=='':
print ('Null name is not ok!')
else:
print ('No you are not that person')
if __name__ == '__main__':
main()
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.
My error-handling code is not working. I'm trying to do following: if user enters any input other than 1, 2 or 3, then the user should get error message and the while-loop should start again.
However my code is not working. Any suggestion why?
def main():
print("")
while True:
try:
number=int(input())
if number==1:
print("hei")
if number==2:
print("bye")
if number==3:
print("hei bye")
else:
raise ValueError
except ValueError:
print("Please press 1 for hei, 2 for bye and 3 for hei bye")
main()
You can also use exception handling a bit more nicely here to handle this case, eg:
def main():
# use a dict, so we can lookup the int->message to print
outputs = {1: 'hei', 2: 'bye', 3: 'hei bye'}
print() # print a blank line for some reason
while True:
try:
number = int(input()) # take input and attempt conversion to int
print(outputs[number]) # attempt to take that int and print the related message
except ValueError: # handle where we couldn't make an int
print('You did not enter an integer')
except KeyError: # we got an int, but couldn't find a message
print('You entered an integer, but not, 1, 2 or 3')
else: # no exceptions occurred, so all's okay, we can break the `while` now
break
main()
I am working on a program that will extract a text from a file like so:
NAME OF PROGRAM: text.txt
CONTENTS OF FILE:
1: 101010100101010101 1010010101010101 101010101010101
2: 0101010101 1010011010 10101010 10101010 10101010
3: 0001000101010 10101010 10101010 1010101010 10101
START LINE: 1
END LINE: 2
results.txt generated.
I am at the part where the program will ask for the name of the program and I plan to use exceptions when the name of the program has the length of zero.
The program should have ran like:
NAME OF PROGRAM:
THE NAME OF THE PROGRAM SHOULD NOT BE LESS THAN 1! [LEN_ERROR]
But the program run like so:
NAME OF PROGRAM:
THERE'S SOMETHING WRONG WITH YOUR INPUT! [INP_ERROR]
Here's the code:
class Program:
"""
Author : Alexander B. Falgui (alexbfalgui.github.io)
Program Name : Text Extractor
Description : Takes an integer or string as an input and generates a
text file with the extracted data.
Note: This program can be used, shared, modified by anyone.
"""
def __init__(self):
self.menu_file_loc = "menu"
return self.load_files()
def load_files(self):
#self.menu_file = open(self.menu_file_loc)
#self.read_mf = self.menu_file.read()
return self.main_menu()
def main_menu(self):
#print(self.read_mf)
print(""" [1] Extract Data\n [2] Exit""")
while (True):
try:
self.menu_input = input("CHOOSE AN OPTION> ")
if (self.menu_input == 1):
try:
self.program_name = raw_input("\nNAME OF THE PROGRAM: ")
self.program_name = open(self.program_name)
except IOError:
if (len(program_name) == 0):
print("THE NAME OF THE PROGRAM SHOULD NOT BE LESS THAN"),
print(" 1! [LEN_ERROR]")
print("%s does not exist" % self.program_name)
elif (self.menu_input == 0):
print("\n")
break
except SyntaxError:
continue
except NameError:
print("SOMETHING'S WRONG WITH YOUR INPUT. [INP_ERROR]\n")
# Run the program
Program()
Why did the program print the wrong exception and what can I do to fix that?
Please don't do except SyntaxError: continue, because you will silently go over any kind of syntax error.
To get more information about what's going wrong, you should except NameError as e to investigate further. See also https://docs.python.org/2/tutorial/errors.html
You should change the except NameError-part to the following:
except NameError as e:
print e
print("SOMETHING'S WRONG WITH YOUR INPUT. [INP_ERROR]\n")
and you will see what really goes wrong.
I'm not sure why you added those two exception handler at the end but you are getting a Name Exception because your refer to the program_name variable instead of self.program_name
Change your line if (len(program_name) == 0): to if (len(self.program_name) == 0): and it should work.