Python "if" statement not working - python

I was writing a complex program and I was getting an if statement...
(this isn't the complex code, this is just an example)
print("The 24 game will give you four digits between one and nine")
print("It will then prompt you to enter an ewuation one digit at a time.")
import random
a = random.randint(1,9)
b = random.randint(1,9)
c = random.randint(1,9)
d = random.randint(1,9)
print(a,b,c,d)
f=input("Enter one of the above numbers")
if f==a:
print("ok")
elif f != a:
print("No")
No matter what I type it always outputs "NO".

It would work after converting the user input string to a number:
if int(f) == a:
print("ok")

Related

basic calculator, multiple input and choice through functions

as you can tell by my code, i want to make a basic calculator, you get asked what you want to do first then asked 2 input 2 numbers to be worked out by the code. I am having a problem where the code returns nothing and doesnt even attempt to use the functions it is meant to.
##Simple Calculator program##
print("Welcome to my basic calculator program")
print("In this program you will be asked to input what function you want to do then")
print("select 2 numbers, where the program will then do the mathematic operation on those 2 numbers")
#Class containing the functions and basic caluclation
class calculator_class():
print("Please select a function by entering these :")
print("Addition")
print("Subtraction")
print("Multiplication")
print("Division")
#this is a function which asks the user to choose what operator to choose before choosing their number
def userchoice():
userchoices = str(input())
if userchoices in ["Addition","Subtraction","Multiplication","Division"]:
return(
if userchoices == "Addition":
print(addition())
elif userchoices == "Subtraction":
print(subtraction())
elif userchoices == "multiplication":
print(multiplication())
elif userchoices == "division":
print(division())
else:
print(invalid_choice())
print(userchoice())
#here the user chooses the 2 numbers
print("Please select 2 numbers to calculate")
usernumber1 = int(input("Please input your first number here : "))
usernumber2 = int(input("Please input your second number here : "))
#Functions of which contain addition, subtraction, multiplication and division
def addition():
print("A D D I T I O N")
print("Just calculating...")
print(usernumber1 + usernumber2)
def subtraction():
print("S U B T R A C T I O N")
print("Just calculating...")
print(usernumber1 - usernumber2)
def multipliction():
print("M U L T I P L I C A T I O N ")
print("Just calculating...")
print(usernumber1 * usernumber2)
def division():
print("D I V I S I O N ")
print("Just calculatin...")
print(usernumber1 / usernumber2)
def invalid_choice():
print("You did not pick a valid option, please try again")
You have many wrong approaches in this code.
More easier to type just a one sign (* for example) instead of typing "multiplication"
It is better to apply .lower() for every user input
input in python is always str, so str() in userchoices = str(input()) is redundant
int() for input() may lead to error (int('1.2') # error), so put such code in try/except block

Errors pertaining to the "!==" function in Python

I'm currently trying to make a program in Python that basically asks you math problems. For some reason, there's a lot of errors, and I have no idea why, such as the "!==" function, which seems to be incorrect. There might also be some other issues as I've only just started Python. Could someone direct me to how to use the !== function correctly and also my other issue: Making my input for "addition, subtraction, or multiplication" into a possible command?
# import random
import time
choice = 0
counterright = 0
counterwrong = 0
def add_question_to_file(a, b):
with open("wrong_answers.txt", 'a') as f:
f.write(f"{a} {operation} {b}\n")
def test(a,operation,b):
user_input = int(input(f"{a} {operation} {b} = "))
if user_input == a + b:
print("You got it right!")
counterright += 1
while user_input != a + b:
if user_input == a + b:
print("You got it right!")
counterwrong += 1
break
else:
add_question_to_file(a, b)
print("Try Again!")
user_input = int(input(f"{a} + {b} = "))
def get_question():
a = random.randint(1, 10)
b = random.randint(1, 10)
with open("calc_log.txt", 'a') as f:
if a<b: #insures a is always greater than b
a, b = b, a
f.write(f"{a} {operation} {b}\n")
def check_operation():
if operation !==t "+" or "-" or "*"
print("Sorry, that's invalid. You have to choose of the three operations!")
t1=time.perf_counter() #
m = input("What mode would you like to use? Review/Normal. Choose Normal if this is your first time!")
operat ion = input("Which operation would you like to use? +,-,or *?")
if m == "review":
with open("wrong_answers.txt", 'r') as f:
for line in f:
a, operation, b = line.split()
test(int(a), int(b))
elif m == "normal":
num_questions = int(input("How many questions would you like to do? "))
for i in range(num_questions):
print(f"You are on question {i + 1}: ")
get_question()
t2=time.perf_counter() #
print("It took you", t2-t1, "seconds for you to solve this problemset") #
print ("You got",counterright,"correct and",counterwrong,"wrong.")
The reason !== isn't working is because this is not an operator in python. Try using !=. It means not equal too.
The does not equal function in python is !=. The double equal sign (==) is only used when you want to check for equality. I hope this helps!

Checking user input to see if it satisfies two conditions

As part of a larger menu-driven program, I'd like to test user input to see if that input:
is an integer AND
if it is an integer, if it is within the range 1 to 12, inclusive.
number = 0
while True:
try:
number = int(input("Enter a whole number between 1 and 12 >>> "))
except ValueError:
print("Invlaid input, please try again >>> ")
continue
else:
if not (1<= number <=12):
print("Need a whole number in range 1-12 >>> ")
continue
else:
print("You selected:",number)
break
I'm using Python 3.4.3, and wanted to know if there's a more succinct (fewer lines, better performance, more "Pythonic", e.g.) way to achieve this? Thanks in advance.
You don't need anything bar one if in the try:
while True:
try:
number = int(input("Enter a whole number between 1 and 12 >>> "))
if 1 <= number <= 12:
print("You selected:", number)
break
print("Need a whole number in range 1-12 >>> ")
except ValueError:
print("Invlaid input, please try again >>> ")
Bad input will mean you go straight to the except, if the input is good and is in your accepted range, the print("You selected:", number) and will be executed then we break or else print("Need a whole number in range 1-12 >>> ") will be executed if is outside the range.
Your code looks pretty good to me. Minor fix-ups (spelling, indentation, unnecessary continues):
while True:
try:
number = int(input("Enter a whole number between 1 and 12 >>> "))
except ValueError:
print("Invalid input, please try again >>> ")
else:
if 1 <= number <= 12:
print("You selected: {}".format(number))
break
else:
print("Need a whole number in range 1-12 >>> ")
Use isdigit() to check for non-digit characters. Then you shouldn't need to catch the exception. There's only one if and it uses operator short-circuiting to avoid doing int(blah) if blah contains non-digits.
while True:
num_str = raw_input("Enter a whole number between 1 and 12 >>> ")
if num_str.isdigit() and int(num_str) in range(1,13):
print("You selected:",int(num_str))
break
else:
print("Need a whole number in range 1-12 >>> ")
I don't think you need a whole try/except block. Everything can be fit into a single condition:
number = raw_input("Enter a whole number between 1 and 12 >>> ")
while not (number.isdigit() and type(eval(number)) == int and 1<= eval(number) <=12):
number = raw_input("Enter a whole number between 1 and 12 >>> ")
print("You selected:",number)

Python calculator - How can I make this better

im pretty new to programming. I made this calculator in python and I was wondering how can I make it more efficient because it seems a bit inefficient to me. I'm still really unfamiliar with python and some programming concepts so it would be nice to get an idea of different ways I may do this. Perhaps there is a better way for me to set up the functions or maybe a way that they can be put into different classes?
Thanks for any responses
def add():
a = int(raw_input("Enter a number!: \n"))
b = int(raw_input("Enter a number!: \n"))
c = a + b
if a + b == c:
print c
menu()
return c
def sub():
a = int(raw_input("Enter a number!: \n"))
b = int(raw_input("Enter a number!: \n"))
c = a - b
if a - b == c:
print c
menu()
return c
def mul():
a = int(raw_input("Enter a number!: \n"))
b = int(raw_input("Enter a number!: \n"))
c = a * b
if a * b == c:
print c
menu()
return c
def div():
a = float(raw_input("Enter a number!: "))
b = float(raw_input("Enter a number!: "))
c = a / b
if a / b == c:
print c
menu()
return c
def square():
a = int(raw_input("Enter a number!: \n"))
c = a * a
if a * a == c:
print c
menu()
return c
def menu():
print """
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Square
6. Exit
"""
choices = [1, 2, 3, 4, 5, 6]
choice = int(raw_input("Enter a number!: \n"))
while True:
if choice == 1:
print add()
elif choice == 2:
print sub()
elif choice == 3:
print mul()
elif choice == 4:
print div()
elif choice == 5:
print square()
elif choice == 6:
exit()
else:
for choose in choices:
if choice != choices:
print "Please enter a number 1 - 6!"
menu()
menu()
First, in the else case where the user entered an invalid menu number, you don't need these lines:
for choose in choices:
if choice != choices:
After all, you already know choice is not valid.
Second, when the user enters 6, rather than exit() you should just return. The program will still end. It's often considered "rude" for a function to call exit() directly--let the caller decide what to do when the function ends.
Third, you don't need to call menu() when your operators succeed. It's strange that you do, since menu() contains its own infinite loop anyway. It's just redundant.
Finally, you can collapse all the two-argument math functions into one, by passing in the actual operation as an argument. The operator module makes this easier.
Putting all these ideas together, here's the new code:
import operator
def dobinaryop(op):
a = float(raw_input("Enter a number!: \n"))
b = float(raw_input("Enter a number!: \n"))
return op(a, b)
def square():
a = float(raw_input("Enter a number!: \n"))
return a * a
def menu():
while True:
print """
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Square
6. Exit
"""
choice = int(raw_input("Enter a number!: \n"))
if choice == 1:
print dobinaryop(operator.add)
elif choice == 2:
print dobinaryop(operator.sub)
elif choice == 3:
print dobinaryop(operator.mul)
elif choice == 4:
print dobinaryop(operator.div)
elif choice == 5:
print square()
elif choice == 6:
exit()
else:
print "Please enter a number 1 - 6!"
menu()
You could streamline this even further by putting the various operators into a list and indexing by choice, but that's getting slightly arcane for not much benefit given you only have four such operators, plus two special cases and bounds checking.
There are couple of things which you are repeating in all the functions. Like asking user to input two numbers a & b using raw_input multiples times. They can be put into another method say getTwoNumbers() which will take two inputs from user and return the two numbers. This method (i.e getTwoNumbers())need to be invoked in the function(s) which is/are performing binary operation. Also you are storing the result into another variable c, which can be ommited and hence comparison with binary operation with the variable c is also not required. It is better if you can perform return a+b or return a-b etc, based on the current binary operation you want to perform.
Put functions and related index in a dictionary. Use that dictionary to decide which function to execute.
And get duplicated part of every function out. I think these solutions will get your code better.

Generating a prime number bigger than a number found in a list

What isn't working below: I can't make the genPrim function work, as I get the "TypeError: 'int' object is not subscriptable".
A few observations:
1. What my program should do is first input a number into a list and then apply the other functions on that number.
2. The problem is that I can't seem to use that number from the list to do so. How can I do it? I was first thinking about asking for its position, but when going for the genPrim, both genPrim and Prim work because they are interdependent but they ask for the same thing.
def Adauga(L):
n = int(input("Give number:"))
L = L + [n]
return L
#Verify if number is prime
def Prim(L):
poz = int(input("Position of number: "))
n = L[poz]
if n<2 :
return False
NrDiv=0
for a in range (2,int(n/2+1)):
if n%a==0:
NrDiv=NrDiv+1
if (NrDiv==0):
return True
else:
return False
#Generate prime number
def genPrim(L):
poz = int(input("Give number: "))
a = L[poz]
b=a+1
while Prim(b)==False:
b=b+1
return b
#Display menu
def AfisMeniu():
print()
print("1.Add number")
print("2.Check if number is prime")
print("3.Generate prime number")
print("0.End of program")
i = int(input("Your option: "))
return i
def Main():
"""
Start the program
"""
L = []
Opt = AfisMeniu()
while (Opt != 0):
if Opt == 1:
L=Adauga(L)
elif Opt ==2:
L=Prim(L)
print (L)
elif Opt ==3:
L=genPrim(L)
print (L)
else:
print ("Wrong!")
Opt = AfisMeniu()
print()
print("End of program")
Main()
You are getting that error because genPrim returns an int, but Main() assigns that result to L, so L no longer contains a list of numbers, just that single int.
Similarly, Prim() returns a boolean (True or False) but Main() assigns that to L, too.
FWIW, the basic logic of your Prim() function is correct, but it's a very inefficient way to test if a number is prime. At the very least you should change it to return False as soon as it has found one divisor, i.e. when n%a==0.
I've managed to make the third option work, as in generating a prime number. However, what I would also like is to make the second option work as well, the prime verification.
My idea is modifying the code in the Main() function, by taking the len of the position, however I can't really make it work.
elif Opt ==2:
L=Prim(L)
poz1=int(len(L))
print (L[poz1])
Or perhaps, should I attempt a different method?

Categories