Using Python 3.4 in Idle. Why am I getting this error message...
ValueError: invalid literal for int() with base 10: '4 4'
when converting my input statement into an integer. I'm trying to put int in my input statement vs using
num1 = int(num1)
num2 = int(num2)
The first way works, but why doesn't the second way? The second way would work if I ran this code:
number = int(input("Number?"))
print(number)
So why doesn't it work the second way?
First way works:
#Ask the user to input 2 values and store them in variables num1 num2
num1, num2 = input("Enter 2 numbers: ").split()
#Convert the strings into regular numbers Integer
num1 = int(num1)
num2 = int(num2)
# Type problems and store in a variable
sum = num1 + num2
difference = num1 - num2
product = num1 * num2
quotient = num1 / num2
remainder = num1 % num2
print("{} + {} = {}".format(num1,num2,sum))
print("{} - {} = {}".format(num1,num2,difference))
print("{} * {} = {}".format(num1,num2,product))
print("{} / {} = {}".format(num1,num2,quotient))
print("{} % {} = {}".format(num1,num2,remainder))
This way doesn't work. I only put this piece of the code to show what I did differently. Besides this line and the other way to convert the string into an integer (num = int) the rest of the code is the same.
2nd way:
num1, num2 = int(input("Enter 2 numbers: ")).split()
Your second way is trying to convert 4 4 into an int which it can't do, you need to apply int to each individual number as a string, so your code becomes:
num1, num2 = map(int, input('Enter 2 numbers: ').split())
On a side note - by calling your variable sum later on you're shadowing the builtin sum which may lead to problems further down the line - I normally use total.
You can also make use of the functions in the operator module to make it a bit simpler:
import operator as op
num1, num2 = map(int, input('Enter 2 numbers: ').split())
for symbol, func in (
('+', op.add), ('-', op.sub), ('*', op.mul),
('/', op.truediv), ('%', op.mod)
):
print('{} {} {} = {}'.format(num1, symbol, num2, func(num1, num2)))
# or print(num1, symbol, num2, '=', func(num1, num2))
Entering 4 4 will give you:
4 + 4 = 8
4 - 4 = 0
4 * 4 = 16
4 / 4 = 1.0
4 % 4 = 0
Related
I'm new to python and trying to understand recursion. I'm trying to write a code where someone inputs 2 numbers (Num1, Num2). A calculation will take place until Num1 is greater than Num 2. The result of the calculation's final value should then be outputted.
This is my code:
def Recursive(Num1, Num2):
if Num1 > Num2:
return(10)
else:
if Num1 == Num2:
return(Num1)
else:
return(Num1+Recursive(Num1 * 2, Num2))
Num1=input("Enter number 1: ")
Num2=input("Enter number 2: ")
print("Final value: ", Recursive(Num1, Num2))
This is the output that comes out:
Enter number 1: 1
Enter number 2: 15
That's it. There's no output of my print statement. I'm confused as to what I'm doing wrong here and what I should do.
def Recursive(Num1, Num2):
if Num1 > Num2:
return 10
if Num1 == Num2:
return Num1
print(Num1, Num2)
return Num1 + Recursive(Num1 * 2, Num2)
Num1=int(input("Enter number 1: "))
Num2=int(input("Enter number 2: "))
print("Final value: ", Recursive(Num1, Num2))
This should be working code, the reason why your code was not working was because without the int in Num1 = int( input("") ) the program was reading the number as a string. As a result instead of getting 2 from Num1 * 2 when Num1 is 1 you got 11 as it was multiplying a string instead of an integer.
# Here is an example
a = input("Input a number: ")
b = int(input("input a number: "))
print(f"a is a:{type(a)}\n b is a:{type(b)}")
print(f"{a * 2}\n{b * 2}")
Copy the code above input the two numbers and it should give you a better understanding of what I just said.
I'm pretty new at python and I've been playing with argv. I wrote this simple program here and getting an error that says :
TypeError: %d format: a number is required, not str
from sys import argv
file_name, num1, num2 = argv
int(argv[1])
int(argv[2])
def addfunc(num1, num2):
print "This function adds %d and %d" % (num1, num2)
return num1 + num2
addsum = addfunc(num1, num2)
print "The final sum of addfunc is: " + str(addsum)
When I run filename.py 2 2, does argv put 2 2 into strings? If so, how do I convert these into integers?
Thanks for your help.
sys.argv is indeed a list of strings. Use the int() function to turn a string to a number, provided the string can be converted.
You need to assign the result, however:
num1 = int(argv[1])
num2 = int(argv[2])
or simply use:
num1, num2 = int(num1), int(num2)
You did call int() but ignored the return value.
Assign the converted integers to those variables:
num1 = int(argv[1]) #assign the return int to num1
num2 = int(argv[2])
Doing just:
int(argv[1])
int(argv[2])
won't affect the original items as int returns a new int object, the items inside sys.argv are not affected by that.
Yo modify the original list you can do this:
argv[1:] = [int(x) for x in argv[1:]]
file_name, num1, num2 = argv #now num1 and num2 are going to be integers
Running int(argv[1]) doesn't actually change the value of argv[1] (or of num1, to which it is assigned).
Replace this:
int(argv[1])
int(argv[2])
With this:
num1 = int(num1)
num2 = int(num2)
and it should work.
The int(..), str(...) etc functions do not modify the values passed to them. Instead, they return a reinterpretation of the data as a different type.
For example I am the user and I input 1 then 3 then 7 then 5
I will get the output 16 but how can I also show the numbers I inputed i.e 1,3,7,5
You could simply store all inputs in a list and print them at the end.
inputs = []
#for each input
inputs.append(userinput)
for value in inputs:
print(value)
if you want your numbers to be in the 1,3,7,5 format use
numbers = ",".join(str(value) for value in inputs)
print(numbers)
You can use variable to store user inputs, Below is sample code for sum of two numbers
n1 = int(input())
n2 = int(input())
s = n1 + n2
print(n1, n2, s)
MOST COMMON CODE:
Suppose you have this following code :
num1 = int(input())
num2 = int(input())
num3 = num1+num2
print(num3)
Now,you want num1 and num3 to be displayed,so u just have to do the following,thats it.
num1 = int(input())
num2 = int(input())
num3 = num1+num2
print(num3)
print(num1)
print(num2)
Check this:
>>> inputs = [input('Enter Number [%d]:' % (i+1)) for i in range(4)]
Enter Number [1]:1
Enter Number [2]:3
Enter Number [3]:5
Enter Number [4]:7
>>> print('{}={}'.format('+'.join(inputs), sum(map(int,inputs))))
1+3+5+7=16
a = input('number: ').split()
print (a, sum(int(_) for _ in a))
I am very much interested in Python and I decided to learn it.
I covered many things but I am stuck when try to make a Calculator in which we just need to type the numbers and the operation type
For Example- 10 ^ 2
The thing that happens is I get no answer. And i use Command Prompt
for the output.
My Code looks like this:
# Calculator
print " "
print " Calculator "
print " "
num = int(raw_input(">> ")).split()
num1 = int(num[0])
op = num[1]
num2 = int(num[2])
if (op=='+'):
print ">>>", num1 + num2
elif (op=='-'):
print ">>>", num1 - num2
elif (op=='*'):
print ">>>", num1 * num2
elif (op=='/'):
print ">>>", num1 / num2
elif (op=='^'):
print ">>>", pow(num1,num2)
elif (op=='%'):
print ">>>", num1 % num2
I use Python 2.7.
Please Help Me For The Same.
You have to remove the int cast, that is
num = raw_input(">> ").split() # remove the int cast
Output will then be:
>> 10 ^ 2
>>> 100
Change
num = int(raw_input(">> ")).split()
To
num = raw_input(">> ").split()
If you enter 2 ^ 10, for example, num will now be the array ['2', '^', '10'] and the rest of your code will work.
If you do int() on your raw_input it will not work since you are trying to convert a string like "2 ^ 10" to an int.
num = int(raw_input(">> ")).split()
should be changed to
num = (raw_input(">> ")).split()
you cannot split a number at least for what I know
My task is to create a maths quiz for primary school children. this is what I have done so far:
import random
import math
def test():
num1=random.randint(1, 10)
num2=random.randint(1, 10)
ops = ['+', '-', '*']
operation = random.choice(ops)
num3=int(eval(str(num1) + operation + str(num2)))
print ("What is {} {} {}?".format(num1, operation, num2))
userAnswer= int(input("Your answer:"))
if userAnswer != num3:
print ("Incorrect. The right answer is {}".format(num3))
return False
else:
print ("correct")
return True
username=input("What is your name?")
print ("Welcome "+username+" to the Arithmetic quiz")
correctAnswers=0
for question_number in range(10):
if test():
correctAnswers +=1
print("{}: You got {} answers correct".format(username, correctAnswers))
What I now need to do is make my program only create questions with positive answers. e.g nothing like 3-10=-7
I've tried searching everywhere online but I cant find anything so I've turned to you guys for help. Any help will be appreciated :)
What I would recommend is:
#Random code...
if num1<num2:
num1, num2 = num2, num1
#Rest of program
So that 3 - 7 = -4 becomes 7 - 3 = 4
The reason I recommend doing this is that the answer would still be the same as the previous equation, just positive instead of negative, so you are still testing the same numbers.
Keep the larger number on the left of the expression, also use operator instead of eval:
from operator import add, sub, mul
def test():
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
d = {"+": add, "-": sub, "*": mul}
operation = random.choice(list(d)))
num1 = max(num1, num2)
num2 = min(num1, num2)
num3 = d[operation](num1, num2)
print("What is {} {} {}?".format(num1, operation, num2))
userAnswer = int(input("Your answer:"))
if userAnswer != num3:
print("Incorrect. The right answer is {}".format(num3))
return False
else:
print("correct")
return True
username = input("What is your name?")
print("Welcome {} to the Arithmetic quiz".format(username))
correctAnswers = sum(test() for question_number in range(10))
print("{}: You got {} answers correct".format(username, correctAnswers))
Or as #jonclements suggests sorting will also work:
num2, num1 = sorted([num1, num2])
On another note you should really be using a try/except to verify the user input and cast to an int otherwise the first value that cannot be cast to an int your program will crash.
You can choose the numbers such that num2 will be between 1 and num1 like:
num1=random.randint(1, 10)
num2=random.randint(1, num1)
or that num1 > num2:
n1=random.randint(1, 10)
n2=random.randint(1, 10)
num1 = max(n1,n2)
num2 = min(n1,n2)
i would go with the first option. no extra variables, no extra lines.
after the code that chooses the random numbers you can add this while loop:
while num3<0:
num1=random.randint(1, 10)
num2=random.randint(1, 10)
ops = ['+','-','*']
operation = random.choice(ops)
num3=int(eval(str(num1) + operation + str(num2)))
It will enter this loop every time the answer is negative. This will ensure that the answer is positive when the program quits the loop.
A change in one line should do it:
if num1 > num2:
num3=int(eval(str(num1) + operation + str(num2)))
else:
num3=int(eval(str(num2) + operation + str(num1)))