Argv - String into Integer - python

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.

Related

Having trobule with sys.argv() [duplicate]

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.

Why doesn't my Python calculator print the results its functions return? [duplicate]

This question already has answers here:
Class return statement not printing any output
(1 answer)
Why doesn't Python print return values?
(3 answers)
Closed 3 years ago.
I am a beginner with Python and am trying to write my first calculator program. However, the test that I set up for it did not work. It asked me for the operation and the numbers, but it didn't print the result. Why not?
I have tried rewriting it in different ways, but it still doesn't work.
def add(num1, num2):
print(str(num1+num2))
def sub(num1, num2):
return str(num1-num2)
def mul(num1, num2):
return str(num1*num2)
def div(num1, num2):
return str(float(num1)/float(num2))
def main():
operation = input("What operation would you like to perform? add, sub, mul or div: ")
num1 = input("What is number 1? ")
num2 = input("What is number 2? ")
if (operation == 'add'):
add(num1, num2)
main()
I expected it to ask what the operation I wanted to perform was, then to ask what the numbers were, and then to print the result. Instead, it does all of those, except print the result. Please could somebody point out where I have gone wrong. NB: I only put in a case for 'add' because I was just testing it.
it does all of those, except print the result
The simplest answer is that it's because you didn't tell it to. Python only prints things out that you tell it to when you write print(<something>) in your code.
When you write add(num1, num2), it is computing the result, but then you aren't doing anything with that result. You could, for instance, do this:
answer = add(num1, num2)
print(answer)
This declares a variable to store the result, so that it isn't lost. And then prints it.
Beyond the immediate question you have about printing the result, you will find that the value you get from input() is a string, not a number. Your add() function will do num1 + num2 but since these are strings, it is actually concatenating (joining) them, like "3" + "4" = "34" which is not what you want.
You should make be sure to convert your inputs to numbers with int() or float(). And I would recommend not having the str() call inside add(). The print() function can print numbers just fine.
num1 = input("What is number 1? ")
input() returns a string, so you need to convert both inputs to int()s so they can have mathematical operations performed.
Here is a working example of your calculator:
def add(num1, num2):
return num1+num2
def sub(num1, num2):
return num1-num
def mul(num1, num2):
return num1*num2
def div(num1, num2):
return num1/num2
def main():
operation = raw_input("What operation would you like to perform? add, sub, mul or div: ")
num1 = float(input("What is number 1? "))
num2 = float(input("What is number 2? "))
if (operation == 'add'):
print(add(num1, num2))
elif (operation == 'sub'):
print(sub(num1, num2))
elif (operation == 'mul'):
print(mul(num1, num2))
elif (operation == 'div'):
print(div(num1, num2))
else:
print("Error: no such operation")
main()
Note: for your operation, you have to use raw_input instead of input.

Problems converting string to integer splitting two variables in Python 3

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

importing assignment into modul re/expected string or buffer Python,

Well I just started learning Python so I don't understand how to make my code correct (Worth to SAY that I learn it from youtube))). What I want from the code is -- if the assignment num1 has 8 in the end and it should be printed by command print, and if it doesn't just print nothing.
import re
def x():
num1 = 5894652138
vav = re.match(r'[8]''$', num1)
print vav
x()
You don't need to use re here.
To check the last digit in decimal number, you should use the modulos with 10:
num1 = 5894652138
if num1 % 10 == 8:
print num1
def x():
num1 = 5894652138
num2 = str(num1)
if (num2.endswith("8")):
print num1
you could do this to see if 8 is at the end.

Python Calculator, No Answer

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

Categories

Resources