I made a calculator in python but when I run it and do for example 123 and 321 I get 123321 instead of 444, What am I doing wrong?
import time
print("Calculator 1.0")
print("made by AnAwesomeMiner")
print("Number 1 in calculation")
x = input()
print("Number 2")
y = input()
print("calculating")
time.sleep(3)
print("why is this not done yet")
time.sleep(3)
print("god this is taking forever")
time.sleep(3)
print("done")
answear = x + y
print(answear)
input() returns string not number . That's why instead of addition , String concatenation is performed.
you need to use int(x) and int(y) for conversion.
use this statement answear = int(x) + int(y)
input returns a string, and when you combine two strings the result is what you are seeing.
>>> x = '123'
>>> y = '321'
>>> x+y
'123321'
So you need to convert them to an integer, like this:
answear = int(x) + int(y)
you can use this :
y=int(input())
This is because you are declaring it as a string. Use a = int(input()). This will cast it into an integer. If you want to insert a decimal number use the float data type.
input() accepts and returns a string object and you need to typecast this into an integer (or float) if you want to perform arithmetic operations on it. Performing a + operation on two strings merely concatenates them.
Instead of input(), use int(input()). This will tell Python that the user is about to enter an integer.
def main():
def add(x,y):
return x + y
def sub(x,y):
return x - y
def mult(x,y):
return x * y
def div(x,y):
return x / y
def remainder(x,y):
return x % y
repeat=True
while repeat:
select=int(input("please select any operation:-\n 1.ADD\n2.SUBTRACT\n3.MULTIPLY\n4.DIVIDE\n5.REMAINDER\nselect here:-"))
num1=int(input("Enter the first number"))
num2=int(input("Enter the second number"))
if select==1:
print(num1,"+",num2,"=",add(num1,num2))
elif select==2:
print(num1,"-",num2,"=",sub(num1,num2))
elif select==3:
print(num1,"*",num2,"=",mult(num1,num2))
elif select==4:
print(num1,"/",num2,"=",div(num1,num2))
elif select==5:
print(num1,"%",num2,"=",remainder(num1,num2))
else:
print("invalid input")
print("Do you want to calculate further?\n press y for continue.\n press any other key to terminate.")
repeat="y" in str(input())
if repeat=="y":
print("Ooo yeh! you want to continue")
else:
print("Tnakyou")
main()
This is a simple problem to fix. When adding to integers or doing any other operation including an input and an int you need to do this:
y = int(input())
x = int(input())
a = y+x
so this put into your code looks like this:
import time
print("Calculator 1.0")
print("made by AnAwesomeMiner")
print("Number 1 in calculation")
x = int(input())
print("Number 2")
y = int(input())
print("calculating")
time.sleep(3)
print("why is this not done yet")
time.sleep(3)
print("god this is taking forever")
time.sleep(3)
print("done")
answear = x + y
print(answear)
Related
I have to make a program using while that:
Will ask for user to put 2 integer numbers
and give back the addition and multiplication
of those 2.
Will check if the numbers are integers.
Will close if the user uses the word stop.
I have made 1 and 2 but am stuck on 3. Here is what I wrote:
while True:
try:
x = int(input("Give an integer for x"))
c = int(input("Give an integer for c"))
if x=="stop":
break
except:
print(" Try again and use an integer please ")
continue
t = x + c
f = x * c
print("the result is:", t, f)
Your code isn't working because you are starting off by defining x as an integer, and for it to equal "stop", it needs to be a string.
What you therefore want to do is allow x to be input as a string, and then convert it to an integer if it isn't stop:
while True:
try:
x = input("Give an integer for x")
if x=="stop":
break
else:
x = int(x)
c = int(input("Give an integer for c"))
except:
print(" Try again and use an integer please ")
continue
t = x + c
f = x * c
print("the result is:", t, f)
Just a slight change is required (and you can be slightly more structured using else in your try block.
You need to input the first value as a string so that you can first test it for "stop" and only then try to convert it to an integer:
while True:
try:
inp = input("Give an integer for x: ")
if inp == "stop":
break
x = int(inp)
c = int(input("Give an integer for c: "))
except:
print("Try again and use an integer please!")
else:
t = x + c
f = x * c
print("the results are", t, f)
I have also fixed up some spacing issues (i.e. extra spaces and missing spaces in your strings).
I know I can't use Goto and I know Goto is not the answer. I've read similar questions, but I just can't figure out a way to solve my problem.
So, I'm writing a program, in which you have to guess a number. This is an extract of the part I have problems:
x = random.randint(0,100)
#I want to put a label here
y = int(raw_input("Guess the number between 1 and 100: "))
if isinstance( y, int ):
while y != x:
if y > x:
y = int(raw_input("Wrong! Try a LOWER number: "))
else:
y = int(raw_input("Wrong! Try a HIGHER number "))
else:
print "Try using a integer number"
#And Here I want to put a kind of "goto label"`
What would you do?
There are lots of ways to do this, but generally you'll want to use loops, and you may want to explore break and continue. Here's one possible solution:
import random
x = random.randint(1, 100)
prompt = "Guess the number between 1 and 100: "
while True:
try:
y = int(raw_input(prompt))
except ValueError:
print "Please enter an integer."
continue
if y > x:
prompt = "Wrong! Try a LOWER number: "
elif y < x:
prompt = "Wrong! Try a HIGHER number: "
else:
print "Correct!"
break
continue jumps to the next iteration of the loop, and break terminates the loop altogether.
(Also note that I wrapped int(raw_input(...)) in a try/except to handle the case where the user didn't enter an integer. In your code, not entering an integer would just result in an exception. I changed the 0 to a 1 in the randint call too, since based on the text you're printing, you intended to pick between 1 and 100, not 0 and 100.)
Python does not support goto or anything equivalent.
You should think about how you can structure your program using the tools python does offer you. It seems like you need to use a loop to accomplish your desired logic. You should check out the control flow page for more information.
x = random.randint(0,100)
correct = False
prompt = "Guess the number between 1 and 100: "
while not correct:
y = int(raw_input(prompt))
if isinstance(y, int):
if y == x:
correct = True
elif y > x:
prompt = "Wrong! Try a LOWER number: "
elif y < x:
prompt = "Wrong! Try a HIGHER number "
else:
print "Try using a integer number"
In many other cases, you'll want to use a function to handle the logic you want to use a goto statement for.
You can use infinite loop, and also explicit break if necessary.
x = random.randint(0,100)
#I want to put a label here
while(True):
y = int(raw_input("Guess the number between 1 and 100: "))
if isinstance( y, int ):
while y != x:
if y > x:
y = int(raw_input("Wrong! Try a LOWER number: "))
else:
y = int(raw_input("Wrong! Try a HIGHER number "))
else:
print "Try using a integer number"
# can put a max_try limit and break
I'm trying to write something that checks if a string is a number or a negative. If it's a number (positive or negative) it will passed through int(). Unfortunately isdigit() won't recognize it as a number when "-" is included.
This is what I have so far:
def contestTest():
# Neutral point for struggle/tug of war/contest
x = 0
while -5 < x < 5:
print "Type desired amount of damage."
print x
choice = raw_input("> ")
if choice.isdigit():
y = int(choice)
x += y
else:
print "Invalid input."
if -5 >= x:
print "x is low. Loss."
print x
elif 5 <= x:
print "x is high. Win."
print x
else:
print "Something went wrong."
print x
The only solution I can think of is some separate, convoluted series of statements that I might squirrel away in a separate function to make it look nicer. I'd be grateful for any help!
You can easily remove the characters from the left first, like so:
choice.lstrip('-+').isdigit()
However it would probably be better to handle exceptions from invalid input instead:
print x
while True:
choice = raw_input("> ")
try:
y = int(choice)
break
except ValueError:
print "Invalid input."
x += y
Instead of checking if you can convert the input to a number you can just try the conversion and do something else if it fails:
choice = raw_input("> ")
try:
y = int(choice)
x += y
except ValueError:
print "Invalid input."
You can solve this by using float(str). float should return an ValueError if it's not a number. If you're only dealing with integers you can use int(str)
So instead of doing
if choise.isdigit():
#operation
else:
#operation
You can try
try:
x = float(raw_input)
except ValueError:
print ("What you entered is not a number")
Feel free to replace float with int, and tell me if it works! I haven't tested it myself.
EDIT: I just saw this on Python's documentation as well (2.7.11) here
isn't this simpler?
def is_negative_int(value: str) -> bool:
"""
ref:
- https://www.kite.com/python/answers/how-to-check-if-a-string-represents-an-integer-in-python#:~:text=To%20check%20for%20positive%20integers,rest%20must%20represent%20an%20integer.
- https://stackoverflow.com/questions/37472361/how-do-i-check-if-a-string-is-a-negative-number-before-passing-it-through-int
"""
if value == "":
return False
is_positive_integer: bool = value.isdigit()
if is_positive_integer:
return True
else:
is_negative_integer: bool = value.startswith("-") and value[1:].isdigit()
is_integer: bool = is_positive_integer or is_negative_integer
return is_integer
I am a beginner in python. My program is to set a number (I am not using random.randint for the moment) and I try to guess it. So here is the code:
def game():
print "I am thinking of a number between 1 and 10!"
global x
x = 7
y = raw_input("Guess!")
while x > y:
y = raw_input("Too low. Guess again!")
while x < y:
y = raw_input("Too high. Guess again!")
if x == y:
return "You got it! The number was" + x + " !"
but when I run this, the program states that x < y, no matter WHAT number I put in.
Please, can someone help me? Thank you.
You need to convert y to an integer before comparing it to x:
y = int(raw_input("Guess!"))
Otherwise, you are comparing variables of different types, and the result is not always intuitive (such as x always being less than y). You can apply the same approach for the other times you ask the user to input y.
You may want this:
def game():
print "I am thinking of a number between 1 and 10!"
global x
x = 7
while True:
y = int(raw_input("Guess! ")) # Casting the string input to int
if x > y:
y = raw_input("Too low. Guess again!")
elif x < y:
y = raw_input("Too high. Guess again!")
elif x == y:
print "You got it! The number was " + str(x) + " !"
break # To exit while loop
game()
Y has to be an integer like x. A simple way to do this is:
y=int(raw_input("etc."))
You cannot compare two different variable types in python! Hope this helps!
Going to feel dumb once I figure this out.
The program I'm writing prompts for an operation (e.g. 9+3) and then prints the result.
Example run:
>>>Enter an operation: 9+3
>>>Result: 12
I'll have four separate functions for the operators +,-,*,/ and another function to receive the user input and print the result after the appropriate function return.
This is my code so far (I'm including only one operator function):
def add(n, y):
result = ""
result = n + y
return result
def main():
op = input("Enter an operation: ")
for i in range(1,len(op)):
n = n[0]
y = y[2]
if (i == "+"):
result = add(n, y)
print("Result: ", result)
print("Bye")
My error in the shell states n and y are not assigned so I'm not parsing them from the input correctly.
Because they are not assigned in the body of the function and not available in the global scope:
def main():
op = input("Enter an operation: ")
for i in range(1,len(op)):
n = n[0] # no n here yet so n[0] won't work
y = y[2] # no y here yet so y[2] won't work
I think you aim to parse the input, and then use those values to perform addition, something like that:
def main():
op = input("Enter an operation: ")
i = op[1]
n = int(op[0])
y = int(op[2])
if i == "+":
result = add(n, y)
print("Result: ", result)
print("Bye")
But it will work only for one digit arguments, so you might think about some proper parsing using regex, but that's for another question.
There are problems with your code:
In main, at n = n[0], you don't have any n defined. So you will get an error. Same for y = y[2].
In add you are adding strings. So you will get '93' as the answer.
For the proper parsing use regex
Or if you want quick to work, less coding version (not recommended if you are learning)
Try this:
def main():
while True:
# just a variable used to check for errors.
not_ok = False
inp = input("Enter an operation: ")
inp = inp.replace('\t',' ')
for char in inp:
if char not in '\n1234567890/\\+-*().': # for eval, check if the
print 'invalid input'
not_ok = True # there is a problem
break
if not_ok: # the problem is caught
continue # Go back to start
# the eval
try:
print 'Result: {}'.format(eval(inp)) # prints output for correct input.
except Exception:
print 'invalid input'
else:
break # end loop
Some regex links: 1 2