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""):
Related
I am creating an Among Us ripoff (for fun!) and the while True & if/elif/else statements will only return false (not An Impostor) with the inputs. I had created a list for the names and 2 random elements from the list will be chosen as An Impostor. However, whenever I input a name that is The Impostor, it will only return
(player) was not An Impostor.
Here is my code;
import sys, time, random
names = ["player1", "player2", "player3", "player4", "player5", "player6", "player7", "player8", "player9", "player10"]
print("Players: ")
for x in names:
print(x)
print('—————————————————————————')
impostor1 = random.choice(names)
impostor2 = random.choice(names)
crewmates = 8
impostors = 2
tries = 6
while True:
talk = input("Guess who The Impostor(s) are. " + str(crewmates) + " Crewmates are left. " + str(impostors) + " Impostors are left. You have " + str(tries) + " tries left.")
if talk in names:
print(talk + " was voted for.")
time.sleep(0.1)
if talk != impostor1 or talk != impostor2:
notimp = talk + " was not An Impostor. "
names.remove(talk)
for y in notimp:
sys.stdout.write(y)
sys.stdout.flush()
time.sleep(0.05)
crewmates -= 1
tries -= 1
elif talk == impostor1 or talk == impostor2:
wasimp = talk + " was An Impostor. "
names.remove(talk)
for v in wasimp:
sys.stdout.write(v)
sys.stdout.flush()
time.sleep(0.1)
impostors -= 1
else:
print("That player was either ejected or is not a valid player.")
However, whenever I put the Impostor in the input, it says it isn't An Impostor?
I think this line is the source of the problem:
if talk != impostor1 or talk != impostor2:
Let's say impostor1 is player1 and impostor2 is player2 and someone input in player1, according to Python Boolean expression operator or that if statement will evaluate like this:
if player1 != impostor1 evaluated to False because player1 is indeed equals to impostor1.
So far so good, but because the first test is a False, Python simply evaluates and returns the right side operand which may be either True or False. In your case Python will evaluate if talk != impostor2 and return True, thereafter executes the nested block.
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.
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
I am trying to use a while statement like so:
o = 0
while o == 0:
try:
n = int(raw_input("Which number do you want to begin with?"))
o = 1
except:
o = 0
print "Please use a valid number."
However, when I try to use variable n later, it gives me the "local variable 'n' referenced before assignment' UnboundLocalError. That means that n cannot be recognized as a variable in the def I am using, because it only exists in the while statement? Is this possible?
The whole code:
import time
from sys import argv
import os
os.system("cls")
print "Welcome to Number counter 2.0!"
a = True
def program():
global a
if a == False:
os.system("cls")
o = 0
while o == 0:
try:
n = int(raw_input("Which number do you want to begin with?"))
o = 1
except:
o = 0
print "Please use a valid number."
if n == "/historyKeep false":
if a == False:
print "Command historyKeep is already set to false."
else:
a = False
print "Command set successfully."
elif n == "/historyKeep true":
if a == True:
print "Command historyKeep is already set to true."
else:
a = True
print "Command set successfully."
if n == "/historyKeep false":
n = raw_input("Which number do you want to begin with?")
elif n == "/historyKeep true":
n = raw_input("Which number do you want to begin with?")
d = raw_input("How many seconds between each number?")
d = int(d)
total_s = n * d
while n > 0:
print n
time.sleep(d)
n = n - 1
print "Done in", total_s, "seconds in total!"
end_q = raw_input("Exit or retry? (e/r)")
if end_q == "e":
os.system("cls")
print "Exiting."
time.sleep(0.5)
os.system("cls")
print "Exiting.."
time.sleep(0.5)
os.system("cls")
print "Exiting..."
time.sleep(0.5)
os.system("cls")
exit(0)
elif end_q == "r":
program()
program()
You set a = True at the beginning. You then test if a == False and only set n if it is. But then you test n == "/history.... n has not been set at this point.
You need to make sure n is assigned before you use it. It is not enough to just mention it in a branch that is not taken.
n is not defined in the scope that you are trying to use it to fix this define it outside of the while loop and the if statement the while loop is in:
global a
n = 0
Then when you ask the user for what number to start with, that value will replace 0, and you should be good to go. Also instead of declaring global a, why not just make a an input argument for the program() function?
Just to make sure, declare n outside of the loop first:
n = None
while True:
try:
n = int(raw_input("Text..."))
break
except:
print("Please enter a valid number!")
Note: Usually, you would use break to exit a loop. This is because your method requires an extra variable, which uses more memory (not much, but if you keep doing it, it will stack up).
# program to test truth tables v2
import time
import sys
x = 0
while x == 0:
x = str(raw_input("Please enter True or False..."))
x = x[0].upper()+ x[1:]
if x == "True":
x = True
elif x == "False":
x = False
else:
print 'invalid input!'
x = 0 # very difficult but this works now!
print x
y = 0
while y == 0:
y = str(raw_input("Please enter True or False again..."))
y = y[0].upper()+ y[1:]
if y == "True":
y = True
elif y == "False":
y = False
else:
print 'invalid input!'
y = 0
problem = 0
while problem == 0:
problem = input("Please enter number: \n1 for AND, 2 for OR, 3 for NAND, 4 for NOR...")
if problem == 1:
print "I'm thinking.."
time.sleep(2.5)
print "the answer is..."
time.sleep(1.0)
print x, "AND", y, "is", x and y
elif problem == 2:
print "I'm thinking.."
time.sleep(2.5)
print "the answer is..."
time.sleep(1)
print x, "OR", y, "is", x or y
elif problem == 3:
print "I'm thinking.."
time.sleep(2.5)
print "the answer is..."
time.sleep(1)
print x, "NAND", y, "is", not(x and y) # not working for false/false or false/true
elif problem == 4:
print "I'm thinking.."
time.sleep(2.5)
print "the answer is..."
time.sleep(0.5)
print x, "NOR", y, "is", not(x or y) # not working for false/false
else:
print 'invalid input'
problem = 0
I thought this project worked then once I had tested all the combos, I found that there is a problem with the elif in the first while loop. See the comments in the last section. Any help gratefully received
The problem in your first while loop is that 0 == False. Toss that in the interpreter and see.
Here's my guess. You need to turn your booleans into strings. For example, in the first while loop, you set x equal to True and False instead of "True" and "False." Because Python sees booleans True and False as 1 and 0, respectively, your while loop variables (x and y) remain equal to zero in the case of False. It's likely causing you to repeat whenever the user inputs False
Try it and see. Let me know. And whatever you do, keep practicing!! You'll get it.
EDIT: Yep that was the problem. Here's your working code.
import time
import sys
x = 0
while x == 0:
x = str(raw_input("Please enter True or False..."))
#x = x[0].upper()+ x[1:]
print "THIS IS X: {}".format(x)
if x == "True":
x = "True"
elif x == "False":
x = "False"
else:
print 'invalid input!'
x = 0 # very difficult but this works now!
print x
y = 0
while y == 0:
y = str(raw_input("Please enter True or False again..."))
y = y[0].upper()+ y[1:]
if y == "True":
y = "True"
elif y == "False":
y = "False"
else:
print 'invalid input!'
y = 0
problem = 0
while problem == 0:
problem = input("Please enter number: \n1 for AND, 2 for OR, 3 for NAND, 4 for NOR...")
if problem == 1:
print "I'm thinking.."
time.sleep(2.5)
print "the answer is..."
time.sleep(1.0)
print x, "AND", y, "is", x and y
elif problem == 2:
print "I'm thinking.."
time.sleep(2.5)
print "the answer is..."
time.sleep(1)
print x, "OR", y, "is", x or y
elif problem == 3:
print "I'm thinking.."
time.sleep(2.5)
print "the answer is..."
time.sleep(1)
print x, "NAND", y, "is", not(x and y) # not working for false/false or false/true
elif problem == 4:
print "I'm thinking.."
time.sleep(2.5)
print "the answer is..."
time.sleep(0.5)
print x, "NOR", y, "is", not(x or y) # not working for false/false
else:
print 'invalid input'
problem = 0
The other posters have it right -- Python sees 0 and False as the same thing, at least truth-wise. We humans know that they are not the same thing type-wise, of course, and you can force Python to tell the difference by using "is" instead of "==", so the line should become...
while y is 0: # <-- change that line there
y = str(raw_input("Please enter True or False again..."))
y = y[0].upper()+ y[1:]
This is a "strict comparison" that compares both the value (which Python thinks are the same) and type (False is a Boolean, 0 is a Number)