I am trying to write a simple program that read only two symbols (=, +). I have done the checks using if block like above:
x = raw_input("Please answer + or =")
if x == '+':
print "plus"
elif x == '=':
print "equal"
else:
print "not valid"
I want to remove the else and do the check with try, except.
for example I want something like:
try:
x = raw_input("Please answer + or =")
if x == '+':
print "plus"
elif x == '=':
print "equal"
except ....:
print "not valid"
Does anyone can help me?
Thank you
values = {"+": "plus", "=": "equal"}
x = raw_input("Please answer + or =")
try:
print values[x]
except KeyError:
print "not valid"
However, I am not sure you should use try / except here because if may be more readable.
This reads only + or = and will continue to repeat until + or = is entered.
while x != "+" and x != "=":
if x == "+":
print "plus"
elif x == '=':
print "equal"
else:
print ''
def wordify():
x = raw_input('Please answer + or =: ')
if x == '+':
print 'plus'
elif x == '=':
print 'equal'
else:
print 'Not valid. Please try again.\n'
wordify()
Now you just run the function.
In [11]: wordify()
Please answer + or =: 8
Not valid. Please try again.
Please answer + or =: -
Not valid. Please try again.
Please answer + or =: +
plus
In [12]: wordify()
Please answer + or =: *
Not valid. Please try again.
Please answer + or =: =
equal
Like everyone else is suggesting, this is not the appropriate case for using try/except.
If this is a function, you can always raise an error:
def somefunction(input):
try:
if input == '+':
return 'plus'
elif input == '=':
return 'equal'
raise ValueError
except ValueError, e:
return e.message
Related
Suppose that I get the values for valid, d ,sn from a function that I introduced in my program. Then I pass it through the following if statement in python to output the result.
I want the program to print the following statements:
print on if the sn >= 0 and 1<d <90.
print off-right if the sn<0.
print off-left if the d>=90
other than that, for anything that is not valid outputs unknown.
Here is what I wrote, how do I include d when checking the statement?
if valid:
if sn >= 0 and 1<d <90:
print(" on ")
else:
print("off")
else:
print("unknown")
if valid:
if sn >= 0 and d > 1 and d < 90:
print(" on ")
elif sn < 0:
print("off-right")
elif d >= 90:
print("off-left")
else:
print("unknown")
Not sure what you want. But most probably you want to do this i guess?
if valid:
if sn >= 0 and (d>1 and d<90):
print(" on ")
else:
if sn<0:
print("off-right")
elif d>=90:
print('off-left')
else:
print("unknown")
This is a self explanatory answer..
If you get confused by 1<d<90 then you can use what i did above
How can I check if input is a letter or character in Python?
Input should be amount of numbers user wants to check.
Then program should check if input given by user belongs to tribonacci sequence (0,1,2 are given in task) and in case user enter something different than integer, program should continue to run.
n = int(input("How many numbers do you want to check:"))
x = 0
def tribonnaci(n):
sequence = (0, 1, 2, 3)
a, b, c, d = sequence
while n > d:
d = a + b + c
a = b
b = c
c = d
return d
while x < n:
num = input("Number to check:")
if num == "":
print("FAIL. Give number:")
elif int(num) <= -1:
print(num+"\tFAIL. Number is minus")
elif int(num) == 0:
print(num+"\tYES")
elif int(num) == 1:
print(num+"\tYES")
elif int(num) == 2:
print(num+"\tYES")
else:
if tribonnaci(int(num)) == int(num):
print(num+"\tYES")
else:
print(num+"\tNO")
x = x + 1
You can use num.isnumeric() function that will return You "True" if input is number and "False" if input is not number.
>>> x = raw_input()
12345
>>> x.isdigit()
True
You can also use try/catch:
try:
val = int(num)
except ValueError:
print("Not an int!")
For your use, using the .isdigit() method is what you want.
For a given string, such as an input, you can call string.isdigit() which will return True if the string is only made up of numbers and False if the string is made up of anything else or is empty.
To validate, you can use an if statement to check if the input is a number or not.
n = input("Enter a number")
if n.isdigit():
# rest of program
else:
# ask for input again
I suggest doing this validation when the user is inputting the numbers to be checked as well. As an empty string "" causes .isdigit() to return False, you won't need a separate validation case for it.
If you would like to know more about string methods, you can check out https://www.quackit.com/python/reference/python_3_string_methods.cfm which provides information on each method and gives examples of each.
This question keeps coming up in one form or another. Here's a broader response.
## Code to check if user input is letter, integer, float or string.
#Prompting user for input.
userInput = input("Please enter a number, character or string: ")
while not userInput:
userInput = input("Input cannot be empty. Please enter a number, character or string: ")
#Creating function to check user's input
inputType = '' #See: https://stackoverflow.com/questions/53584768/python-change-how-do-i-make-local-variable-global
def inputType():
global inputType
def typeCheck():
global inputType
try:
float(userInput) #First check for numeric. If this trips, program will move to except.
if float(userInput).is_integer() == True: #Checking if integer
inputType = 'an integer'
else:
inputType = 'a float' #Note: n.0 is considered an integer, not float
except:
if len(userInput) == 1: #Strictly speaking, this is not really required.
if userInput.isalpha() == True:
inputType = 'a letter'
else:
inputType = 'a special character'
else:
inputLength = len(userInput)
if userInput.isalpha() == True:
inputType = 'a character string of length ' + str(inputLength)
elif userInput.isalnum() == True:
inputType = 'an alphanumeric string of length ' + str(inputLength)
else:
inputType = 'a string of length ' + str(inputLength) + ' with at least one special character'
#Calling function
typeCheck()
print(f"Your input, '{userInput}', is {inputType}.")
If using int, as I am, then I just check if it is > 0; so 0 will fail as well. Here I check if it is > -1 because it is in an if statement and I do not want 0 to fail.
try:
if not int(data[find]) > -1:
raise(ValueError('This is not-a-number'))
except:
return
just a reminder.
You can check the type of the input in a manner like this:
num = eval(input("Number to check:"))
if isinstance(num, int):
if num < 0:
print(num+"\tFAIL. Number is minus")
elif tribonnaci(num) == num: # it would be clean if this function also checks for the initial correct answers.
print(num + '\tYES')
else:
print(num + '\NO')
else:
print('FAIL, give number')
and if not an int was given it is wrong so you can state that the input is wrong. You could do the same for your initial n = int(input("How many numbers do you want to check:")) call, this will fail if it cannot evaluate to an int successfully and crash your program.
Trying to create a fill in the blanks quiz.
If I use a for loop when the answer is incorrect will always return to FIRST element on the list, is there any way to bypass this? or use a different loop?
See my full code below.
IT IS NOT FINAL
Will only work on EASY answer selection.
The issue will appear when answering correctly FIRST blank(Imagine) and failing on the second one.
Any help will be highly apreciatted.
imag = '***1*** there is no heaven, It is ***2*** if you try, No hell below us, Above us only sky, ***1*** all the people living for today, ***1*** there is no ***3***, It is not hard to do, Nothing to kill or die for, And no religion too, ***1*** all the people living life in ***4***.'
imag_ans = ['Imagine', 'easy', 'heaven', 'peace']
blanks = ['***1***', '***2***', '***3***', '***4**']
def level():
print 'Please select Level? (Easy / Medium / Hard)'
global a
a = raw_input()
if a == 'Easy':
return attempts()
if a == 'Medium':
return 'Med'
if a == 'Hard':
return 'Hard'
else :
print 'Invalid option'
print '\n'
return level()
def attempts():
print 'How many attempts will you need?'
global numberofatt
numberofatt = raw_input()
try:
float(numberofatt)
except ValueError:
print "Please enter a number for attempts"
return attempts()
numberofatt = int(numberofatt)
if numberofatt <= 0 :
print 'Please enter a positive number'
return attempts()
else :
return quiz(a)
def quiz(level):
i = 0
global user_ans
global i
print 'Please fill in the blanks, you have ' + str(numberofatt) + ' attempts'
for blank in blanks:
print 'Fill in blank' + blank
user_ans = raw_input()
if user_ans == imag_ans[i]:
i = i + 1
global imag
imag = imag.replace(blank, user_ans)
print "Correct!"
print imag
else :
return att()
n = 1
def att():
if n == numberofatt :
return 'Game Finished'
if user_ans != imag_ans[i]:
global n
n = n + 1
#blank = 0
print 'Try Again'
return quiz(a)
print level()
You could use while loop:
def level():
global a
a = raw_input('Please select Level? (Easy / Medium / Hard): ')
pending = True
while pending:
if a == 'Easy':
pending = False
return attempts()
elif a == 'Medium':
pending = False
return 'Med'
elif a == 'Hard':
pending = False
return 'Hard'
else :
print 'Invalid option'
print '\n'
Something similar could be applied for quiz(). As commented, you should check how global works. Also, revise the indentation (e.g.: in att()).
I know this seems like it should be very simple, but at this point I'm at my wit's end trying to figure this out. I've coded up a calculator in python, but for some reason the ending if-else statement is only firing the else segment.
import sys
import re
#setting values
x = 0
n = '+'
y = 0
#valid input flag
valid = True
#continue operations flag
run = True
again = "k"
#addition function
def add(x, y):
return x + y
#subtraction function
def subtract(x, y):
return x - y
#multiplication function
def multiply(x, y):
return x * y
#division function
def divide(x, y):
return x / y
#continuation loop
while run == True:
#Prompt for and accept input
equation = raw_input("Please insert a function in the form of 'operand' 'operator' 'operand' (x + y): ")
equation.strip()
#Divide input into 3 parts by spaces
pieces = re.split('\s+', equation)
#set part 1 = x as float
x = pieces[0]
try:
x = float(x)
except:
print "x must be a number"
valid = False
#set part 2 = operator
if valid == True:
try:
n = pieces[1]
except:
print "Please use valid formating (x [] y)."
valid = False
#set part 3 = y as float
if valid == True:
y = pieces[2]
try:
y = float(y)
except:
print "y must be a number"
valid = False
#If input is valid, do requested calculations
while valid == True:
if n == '+' :
print equation + " =", add(x,y)
elif n == '-' :
print equation, " =", subtract(x,y)
elif n == '*' :
print equation, "*", y, " =", multiply(x,y)
elif n == '/' :
if y == 0:
print "You cannot divide by zero."
else:
print equation, " =", divide(x,y)
else:
print "Please use an appropriate operator ( + - * / )."
#play again
again = raw_input("Play again? ")
print again
if again == ("yes", "y", "YES", "Yes","yes"):
run = True
print "yes'd"
else:
print "no'd"
run = False
When I run this code, I get two different problems:
If I enter a valid input (ie: 2 + 2), then my output is
"2 + 2 = 4.0"
"2 + 2 = 4.0"
"2 + 2 = 4.0"
repeating forever.
If I enter an invalid input, I get the "Play again? " Prompt, but
no matter what I enter, the else statement fires.
(for instance, in the case that I enter "yes" into "Play again? ", it will print:
"yes" (<-- this is from "print again" line )
"no'd" (<-- this is from "else: print "no'd" )
I dont know how to solve either of these problems at this point, so any help would be greatly appreciated.
Edit: Thank you everyone, I wish I could check mark all of you for helping me understand different things about what I did wrong.
In while valid == True:, you never change the value of valid, so it's always True and the loop is infinite. I don't see why it's even a loop - change it to if like the blocks above it and it will behave as expected.
Also, in if again == ("yes", "y", "YES", "Yes","yes"):, change == to in and it will behave as expected.
Perhaps you should replace this code:
while valid == True:
if n == '+' :
print equation + " =", add(x,y)
elif n == '-' :
print equation, " =", subtract(x,y)
elif n == '*' :
print equation, "*", y, " =", multiply(x,y)
elif n == '/' :
if y == 0:
print "You cannot divide by zero."
else:
print equation, " =", divide(x,y)
else:
print "Please use an appropriate operator ( + - * / )."
With this...
if valid:
Or...
while valid == True:
# Insert your previous code here.
break
You could also just simply set valid to false at the bottom of your loop too. That would work.
I think valid is constantly true in this case. You have also written while valid is true, which means it will keep iterating over the loop until valid is equalled to false. It appears that within this block of code in the while loop, valid isn't switched to false.
while valid == True: should probably be if valid == True
and for your second problem:
if again == ("yes", "y", "YES", "Yes","yes"): should probably be:
again = again.lower();
if again == "yes" or again == "y":
Your answer is looping because of
while valid == True:
Replace the loop with the if statement
You get "no'd" because of
if again == ("yes", "y", "YES", "Yes", "yes"):
Here you are equating string with a tuple, instead of checking whether the string is contained within a tuple. Try this instead:
if again in ("yes", "y", "YES", "Yes""):
There was no problem until I tried to make an input go through validity check and if invalid ask again for input
i'm counting on you for ideas thanks in advance :)
a=0
def reinp(a,b):
while True:
if a in [1,2,3,4,5,6]: #checking for valid input
return int(a)
break
a=input(b)
else:
return print("error")
tried, not working either
def reinp(a,b):
for c in [1,2,3,4,5,6]:
if int(c)==int(a):
return int(a)
break
else:
a=input(b)
a=reinp(a,'Test: ')
This one is the first to make a problem
def reinp2(a,b): #trying to check if it's a number and can be turned to float if not ask again
while check(a):
a=input(b)
return float(a)
def check(a):
try:
float(a)
return False
except ValueError:
return True
Right now the problem is after the check it never breaks free from any while loop
i tried in place of while True:if...break,
while correct:
if... correct=False
didn't work
and it just asks again and again even a condition is met...
there is no raw_input in python 3.2 so i can't use that either
reinp2() is there so if there a solution found for reinp() the same could apply for reinp2() as well a and b are just variables ans[n]=reinp2(ans[n],"Input n: ") the same with reinp() just for another type of variable (one that can be float as well)
The code as it is now show no syntax errors
P.S. i'm using Python 3.2
[EDIT: Deleted original answer, since no longer relevant with fixed formatting on question]
The problem with reinp is that a will be a string, and you're checking it against integers.
...so change:
if a in [1,2,3,4,5,6]: #checking for valid input
to:
if a in ['1','2','3','4','5','6']: #checking for valid input
If you still have a problem with reinp2, perhaps you can show some code that demonstrates the issue. It looks fine to me.
P.S. It's complete i just wanted all of you who helped to know it's running without is any glitches i even customized it so it could receive initial data :) if someone need a permutation solver you know where to find it :)
If someone wants the script:
from math import *
ans=['n','k','choice',0,0,0,0,0]
n,k=0,1
a=['''1 For Permutations P (from n) = n
2 For Variations V (k emelments from n-th class) = n!/(n-k)!
3 For Combinations C (k emelments from n-th class) = n!/(k!(n-k)!) = ( n )
4 Use last answer. ( k )
5 Second Memory
6 Clear memory
Your choice is : ''',
'''+ to add
- to substract
* to multiply
/ to divide
You will undertake?: ''',
"The answer is: "]
def perm():
global ans
ans[n]=reinp2(ans[n],"Input n: ")
if ans[5]==0:
ans[3]=factorial(ans[n])
ans[6]=ans[3]
return print(a[2], ans[6])
else:
ans[4]=factorial(ans[n])
ans[6]=ops(ans[3],ans[4],ans[5])
return print(a[2], ans[6])
ans[n]=''
ans[k]=''
def var():
global ans
ans[n]=reinp2(ans[n],"Input n: ")
ans[k]=reinp2(ans[k],"Input k: ")
if ans[5]==0:
ans[3]=factorial(ans[n])/(factorial(ans[n]-ans[k]))
ans[6]=ans[3]
return print(a[2], ans[6])
else:
ans[4]=factorial(ans[n])/(factorial(ans[n]-ans[k]))
ans[6]=ops(ans[3],ans[4],ans[5])
return print(a[2], ans[6])
ans[n]=''
ans[k]=''
def comb():
global ans
ans[n]=reinp2(ans[n],"Input n: ")
ans[k]=reinp2(ans[k],"Input k: ")
if ans[5]==0:
ans[3]=factorial(ans[n])/((factorial(ans[n]-ans[k]))*(factorial(ans[k])))
ans[6]=ans[3]
return print(a[2], ans[6])
else:
ans[4]=factorial(ans[n])/((factorial(ans[n]-ans[k]))*(factorial(ans[k])))
ans[6]=ops(ans[3],ans[4],ans[5])
return print(a[2], ans[6])
ans[n]=''
ans[k]=''
def ent():
global ans,a
ans[2]=reinp(ans[2],a[0])
if ans[2]==5:
if ans[3]!=0:
ans[7]=ans[3]
print(ans[7])
ent()
if ans[2]==6:
clear()
print("Done!")
ent()
if ans[3]==0 and ans[2]==4:
print('The memory is empty...')
ent()
elif ans[3]!=0 and ans[2]==4:
ans[3]=ans[3]
ans[5]=reinp1(ans[5],a[1])
if ans[5] == '+' :
ans[5]='add'
print("Adding")
elif ans[5] == '-' :
ans[5]='sub'
print("Substracting")
elif ans[5] == '*' :
ans[5]='mul'
print("Multiplication")
elif ans[5] == '/' :
ans[5]='div'
print("Dividing")
ans[2]='choice'
ent()
if ans[2]==1:
perm()
elif ans[2]==2:
var()
elif ans[2]==3:
comb()
clear1()
ent()
def ops(a,b,c):
if c=='add':
return a+b
if c=='sub':
return a-b
if c=='mul':
return a*b
if c=='div':
return a/b
def reinp(a,b):
while True:
a=input(b)
if str(a) in ['1','2','3','4','5','6']:
return int(a)
break
else:
print('There was an error please try again:')
def reinp1(a,b):
while True:
a=input(b)
if a in ["+", "-", "*", "/"]:
return a
break
def reinp2(a,b):
while check2(a):
a=input(b)
return float(a)
def check2(a):
try:
float(a)
return False
except ValueError:
return True
def clear():
ans[0]='n'
ans[1]='k'
ans[2]='choice'
ans[3]=0
ans[4]=0
ans[5]=0
ans[7]=ans[6]
ans[6]=0
def clear1():
ans[0]='n'
ans[1]='k'
ans[2]='choice'
ent()