unwanted result from a function and if else [duplicate] - python

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 6 months ago.
I'm trying to create a simple program using function and if else. Even though there is no errors, my program doesn't give expected result
value1 = float(input("Enter your first number:"))
value2 = float(input("Enter your second number:"))
question= input("choose mode:" )
add = True
def nor_cal(num1, num2):
if question == add:
total = num1+num2
print("the total is: ")
print(total)
else:
print("Invalid operator")
result1 = nor_cal(value1, value2)
print(result1)
when i run the program, it shows like this:
Enter your first number:2
Enter your second number:3
choose mode:add
Invalid operator
None
I don't know where i'm wrong please help !

The bug is in the line if question == add:, what you're asking the program to do is to compare the variable question (which is "add") to the variable add (which is True).
You're going to want to use if question == "add": instead.

Related

Exception if user enters a string instead of an integer [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I am trying to make my program print(invalid input, try again) if the user types a string instead of an integer.
num_dice = 0
while True:
if num_dice < 3 or num_dice > 5 or num_dice:
num_dice = int(input("Enter the number of dice you would like to play with 3-5 : "))
print("")
print("Please enter a value between 3 and 5.")
print("")
continue
else:
break
You can simply use the isnumeric keyword to check if it is an absolute number or not.
Example:
string1="123"
string2="hd124*"
string3="helloworld"
if string1.isnumeric() is True:
#Proceed with your case.
inputs=string1
Documentation reference : https://www.w3schools.com/python/ref_string_isnumeric.asp
P.S. this will require you changing your input to string format, as isnumeric validates only string.
This below part I mean.
num_dice = str(input("Enter the number of dice you would like to play with 3-5 : "))

python...how to convert 'user inputted ' function arguments to integers for use in calculation [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 years ago.
I was hoping on some input concerning the use of 'user inputted' arguments as variable value amounts to be used in a calculation within a function... this will no doubt be a very simple issue but I am new to python and so far my attempts at fixing it have been flawed.
The function is a simple calculation of adding two numbers together solely for the purpose of introducing new students to functions.
I have no issues with the function working as intended when I feed hard coded values as integers into the parameters (which are included in this example code)
but when I try to pass 'user input' argument values in when actually running the program the function simply concatenates the two values rather than adding them, this is (I presume) because the input values are in the format of a 'string'.
I have tried introducing 'int' statements after the 'input' statements within the argument variable code but this results in an error 'invalid literal for int()' I have also tried this at different points of the function code itself with no luck..... so how would I go about making sure the values are recognised as integers before or during calculation? Thanks
def getSum(num1, num2):
calc = num1 + num2
return calc
num1 = input("Type in your first number to add: ")
num2 = input("Type in your second number to add: ")
result1 = getSum(num1, num2)
answer = getSum(10, 5)
answer2 = getSum(155, 56668)
print(answer)
print(answer2)
print(result1)
int() should work correctly if the user only enters integer values - otherwise you have to wrap it with a try and catch block
try:
num1 = int(input("Type in your first number to add: "))
num2 = int(input("Type in your second number to add: "))
catch Exception as ex:
pass //do nothing
Just introduce int() for num1 and num2 in line2.
So the new code will be:
def getSum(num1, num2):
calc = int(num1) + int(num2)
return calc
num1 = input("Type in your first number to add: ")
num2 = input("Type in your second number to add: ")
result1 = getSum(num1, num2)
answer = getSum(10, 5)
answer2 = getSum(155, 56668)
print(answer)
print(answer2)
print(result1)

Not equal statement, not working [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 years ago.
I am making a small quiz that has different difficulties, when doing my easy section my if statement always prints incorrect even with the correct answer - i am still new to python it might be a very easy thing to solve
How can I know if this is a duplicate if i don't know what is wrong
here is my code
def easy():
score = 0
print("Welcome to the easy section!")
print("****************************")
print("Random Access Memory(1)")
print("Radical Amazonian Mandem(2)")
qe1 = input("What does RAM stand for?: ")
if qe1 == 1:
score = score + 1
print("Well done, next question:")
if qe1 != 1:
print("Incorrect, next question:")
else:
easy()
input function return a string, you should cast it to int:
qe1 = int(input("What does RAM stand for?: "))

Inputting using a function [duplicate]

This question already has answers here:
How do I pass a variable by reference?
(39 answers)
Closed 6 years ago.
I'm just starting out with Python.I'm making a basic calculator.
When I input a number ,I have to do it like this :
Number= int(input("Enter your number"))
And I was thinking if I could make a function ,like this:
def inputting (Number):
Number= int(input("Enter your number")
And then call it whenever inputting.But I have to define a variable before I use it in a function,and that can only be done by assigning a value.
And instead of the value entered , it takes the value previously assigned when I use it later.
def inputting (Number):
Number= int(input("Enter your number")
FirstNum= none
inputting(FirstNum)
print (FirstNum)
and instead of printing the value I'd typed in there, it just prints none
How do I make this work?
You need to use return:
def inputting(my_number):
return int(my_number)
Or:
def inputting():
return int(input("Enter your number"))
my_number = inputting()

python code has a name error in a while loop [duplicate]

This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 7 years ago.
this is all of my code so far. the function works if I input x manually. I'm also just starting out so any general info on how to generally make it more pythonic would be apreciated
def iseven(x):
if x % 2 == 0:
return x," is even"
else:
return x," is odd"
it = (1)
while it >= 0:
number = input("What number: ")
print iseven(number)
new_num = input("another number? answer (Y/N):")
if new_num == "Y":
it += 1
else:
it = 0
this is the error
NameError: name 'Y' is not defined
You may want to avoid input in such cases where you're processing general input and prefer raw_input:
https://docs.python.org/2/library/functions.html#raw_input
This avoid the eval that's taking place that's causing your error - it's looking in the program's scope for something named "Y". If you type "it", here, for example, it will evaluate the code, which is generally unsafe (though fairly benign here I suppose).
https://docs.python.org/2/library/functions.html#eval
Just change the line:
new_num = input("another number? answer (Y/N):")
to:
new_num = raw_input("another number? answer (Y/N):")
You need to change: while it >= 0: to while it: as well so that you can be able to exit the loop if you select N on prompt.

Categories