I am trying to make a simple average calculation but trying my best to run on CMD.
So far this is what I've came out
import sys
myList = [a,b,c]
myList[0] = int(sys.argv[1])
myList[1] = int (sys.argv[2])
myList[2] = int(sys.argv[3])
print 'Average:' + sum(myList) / len(myList)
my question is; how do set a variable in a list to give them a value?
EDIT:
import sys
myList = [a,b,c]
a = int(sys.argv[1])
b = int (sys.argv[2])
c = int(sys.argv[3])
print 'Average:' + sum(myList) / len(myList)
whats wrong with this code?
EDIT:
I want to allow users to run this program with three input arguments by passing three values to the program: a, b and c.
Edit:
this is my final edit, anyone can help me with this
import sys
a = float(sys.argv[1])
b = float(sys.argv[2])
c = float(sys.argv[3])
if a == str or b == str or c == str:
print 'Your input is invalid'
else:
print 'Average: %.2f ' % ((a + b + c) / 3)
You could create an empty list and use method append.
3 / 2 equals 1 in Python 2 so you want to work with floats.
You can't concatenate floats and strings so you want to use % or format.
Here is your code after corrections:
my_list = []
my_list.append(float(sys.argv[1]))
my_list.append(float(sys.argv[2]))
my_list.append(float(sys.argv[3]))
print 'Average: %s' % (sum(my_list) / len(my_list))
Or shorlty:
my_list = map(float, sys.argv[1:])
print 'Average: %s' % (sum(my_list) / len(my_list))
Or if you want to unpack arguments in separate variables:
a, b, c = map(float, sys.argv[1:])
print 'Average: %s' % ((a + b + c) / 3)
Are you looking for something like:
import sys
my_list = [float(arg) for arg in sys.argv[1:]]
print('Average: {}'.format(sum(my_list) / len(my_list))
[float(arg) for arg in sys.argv[1:]] is a list-comprehension (one-liner for that returns a list). It parse args into float (float(arg)) and loop from the second element of sys.argv (first is name of you script file).
Float type is forced because Python trunk results of division if both numerator and denominator are int.
Btw, PEP8 required snake_case (my_list, not myList) and string concat should never be done with +, but with format or join().
Related
I am trying to print the equation with the variables
I have already tried to put all symbols in quotes
import random
import random
def ask():
a = raw_input("do you want the equation to be easy, medium, or hard: ")
b = int(raw_input("what is the number that you want to be the answer: "))
if(a == "easy"):
d = random.randint(1, 10)
e = random.randint(2, 5)
round(b)
print C = b - d + e - (e/2) + ((d - e) + e/2)
I wanted it to print out the equation with all the variables and symbols
when i type this in i get a syntax error
You cannot print out strings not in quotes. Put the bits you want to print out exactly as written in quotes, and print variables as is. For example:
print 'C =', b, '-', d, '+', e, '-', (e/2), '+', ((d - e/2)
Play around with that and see how you go. You'll want to think about how to do it differently if e.g. d-e/2 is negative.
Also round(b) will do nothing, it does not operate in-place.
try to put your equation in str() first,then print string
so that it will display equation before result.
then print out results
Here's what I think you want as a full solution. It accepts a single equation string as an input It then fills out that equation with the input variables, prints the resulting equation, and then evaluates it to provide a result:
import random
equation = "b - c + e - (e/2) + ((d- e) + e/2)"
b = 12
c = 24
d = random.randint(1, 10)
e = random.randint(2, 5)
# Expand the vlaues into the equation
equation = equation.replace('b', str(b)).replace('c', str(c)).replace('d', str(d)).replace('e', str(e))
# Print the equation
print "C = " + equation
# Evaluate the equation and print the result
C = eval(equation)
print "C = " + str(C)
Sample result:
C = 12 - 24 + 2 - (2/2) + ((6- 2) + 2/2)
C = -6
This code is just a demonstration of what can be done. You could take these ideas and generalize this to expand a map of variable names and values into an arbitrary expression without hard-coding the variable names. The map and equation could come, for example, from a file.
The following code is there to add given integer, double and concatenate the string to the user's input integer, double and string respectively.
The code is given below, but it gives no output. What's the error in it.
i = 4
d = 4.0
s = 'Hackerrank'
a = int(input())
b = long(input())
c = raw_input()
print(a + i)
print(b + d)
print(s+c)
Kindly point out the errors and let me know the reason for it not working too!
Consider reading https://realpython.com/learn/python-first-steps/
And to quickly check your code use https://repl.it/languages/python3
You have several errors in your original code. here is the corrected version:
i = 4
d = 4.0
s = 'Hackerrank'
a = int(input())
b = float(input())
c = input()
print(a + i)
print(b + d)
print(s+c)
A little note: You can add a prompt to your calls to input() so the user knows what to type:
a = int(input("type int "))
b = float(input("type float "))
c = input("please type something")
Finally, if you want to run it with python3 in terminal do:
python3 name_of_file.py
Hello ANIRUDH DUGGAL
First read this best website before start Python 3,
1. https://www.tutorialspoint.com/python3/
2. https://docs.python.org/3/tutorial/
3. https://learnpythonthehardway.org/python3/
Difference between python 2 and python 3,
1. http://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html
2. https://www.quora.com/What-are-the-major-differences-between-Python-2-and-Python-3
Your code perfectly works on version python 2 but if you use the Python 3 so it does not work because in Python 3 is something different syntax so first read Python 3 basic fundamentals(Syntex, inbuilt function,...etc).
Using python2:
#!/usr/bin/python
# Using python 2
i = 4
d = 4.0
s = 'Hackerrank'
a = int(input("Enter the integer number: "))
b = long(input("Enter the long number: "))
c = str(raw_input("Enter the string: "))
print("Output1: %d" % (a + i))
print("Output1: %f" % (b + d))
print("Output1: %s" % (s+c))
Using python3:
#!/usr/bin/python
# Using python 3
i = 4
d = 4.0
s = 'Hackerrank'
a = int(input("Enter the integer number: "))
b = float(input("Enter the long number: "))
c = str(input("Enter the string: "))
print("Output1: %d" % (a + i))
print("Output1: %f" % (b + d))
print("Output1: %s" % (s+c))
I hope my answer is useful for you.
in python 3 it is just input() and change the long to float
Hey I have this function in python3 , can anyone explain why it is giving 1 as output instead of the number as reverse
def reverse(a , rev):
if a > 0:
d = a % 10
rev = (rev * 10) + d
reverse(a/10 , rev)
return rev
b = input("Enter the Number")
x = reverse(b , 0)
print(x)
You need to:
use integer division (//)
capture the value returned from the recursive call, and return it
convert the string input to number (int())
Corrected script:
def reverse(a, rev):
if a > 0:
d = a % 10
rev = (rev * 10) + d
return reverse(a//10, rev)
return rev
b = input("Enter the Number")
x = reverse(int(b), 0)
print(x)
I'm not sure why you're doing it like that. Seems like the following is easier
def rev(a):
return int(str(a)[::-1])
Anyway, I believe you should use "//" instead of "/" for dividing without the rest in python 3?
When I run the code below I get an error. I have looked here on StackOverflow, but I ended up not solving my problem.
print "insert value"
value = raw_input ()
flag = False
i = 0
while flag:
if value == 1:
flag = True
elif value % 2 == 0:
value = value / 2
else:
value = value * 3
value = value + 1
i = i + 1
print "After", i, "attempts the conjecture has been demonstrated"
I get an error in the elif logical test value% 2 == 0 which says
not all arguments converted during string formatting
I think the problem is in the variable type but I tried the input function and forcing the int type, value = int (input (....)), but that also didn't work.
In IDLE this worked for me
value = int(raw_input ())
converting raw input into integer
while True:
if value == 1:
break
elif value % 2 == 0:
value = value / 2
else:
value = value * 3
value = value + 1
i = i + 1
a bit simpler way to do while without having arbitrary flag
iScrE4m has shown how to fix your program, but I'll explain why you got that
TypeError: not all arguments converted during string formatting
error message.
When the Python interpreter sees % after a string it interprets the % as the string interpolation operator, which is used to convert data and insert it into a string.
For example
a = 2
b = 3
print "%d + %d = %d" % (a, b, a + b)
output
2 + 3 = 5
In your code, value is a string so the interpreter tries to do string interpolation on value % 2 but then it sees that value isn't a valid format string to format the data 2, so it gives you that TypeError.
In modern code use of %-style string formatting is discouraged and the str.format method is preferred. The equivalent to the above example is:
print "{0} + {1} = {2}".format(a, b, a + b)
In Python 2.7 and later you can omit the field numbers:
print "{} + {} = {}".format(a, b, a + b)
I have a few more comments on your code.
When calling a function in Python it's conventional to not put a space after the function name.
There's no need to use print to print a prompt before calling raw_input: you can (and should) supply the prompt as an argument to raw_input.
When performing integer division you should use the integer division operator //. A single slash works ok in Python 2, but in Python 3 it won't behave as expected here because it will perform a floating-point division. Eg, 10 / 2 will result in 5.0.
When you need to perform a single operation on a variable and save the result of that operation back to the same variable you can use an augmented assignment operator. Eg,
instead of i = i + 1 you can write i += 1;
instead of value = value // 2 you can write value //= 2.
Also, instead of
value = value * 3
value = value + 1
you could do
value *= 3
value += 1
However, when performing multiple operations on a variable it's a little more compact and efficient to do them on one line. So it would be more usual to do:
value = value * 3 + 1
Putting it all together, here's a re-worked version of your code.
value = int(raw_input("Enter value: "))
i = 0
while True:
if value == 1:
break
elif value % 2 == 0:
value //= 2
else:
value = value * 3 + 1
i += 1
print "After {} attempts the conjecture has been demonstrated.".format(i)
This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 4 years ago.
I have this python program that adds strings to integers:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: " + a + b
a = int(a)
b = int(b)
c = a + b
str(c)
print "a + b as integers: " + c
I get this error:
TypeError: cannot concatenate 'str' and 'int' objects
How can I add strings to integers?
There are two ways to fix the problem which is caused by the last print statement.
You can assign the result of the str(c) call to c as correctly shown by #jamylak and then concatenate all of the strings, or you can replace the last print simply with this:
print "a + b as integers: ", c # note the comma here
in which case
str(c)
isn't necessary and can be deleted.
Output of sample run:
Enter a: 3
Enter b: 7
a + b as strings: 37
a + b as integers: 10
with:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: " + a + b # + everywhere is ok since all are strings
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: ", c
str(c) returns a new string representation of c, and does not mutate c itself.
c = str(c)
is probably what you are looking for
If you want to concatenate int or floats to a string you must use this:
i = 123
a = "foobar"
s = a + str(i)
c = a + b
str(c)
Actually, in this last line you are not changing the type of the variable c. If you do
c_str=str(c)
print "a + b as integers: " + c_str
it should work.
Apart from other answers, one could also use format()
print("a + b as integers: {}".format(c))
For example -
hours = 13
minutes = 32
print("Time elapsed - {} hours and {} minutes".format(hours, minutes))
will result in output - Time elapsed - 13 hours and 32 minutes
Check out docs for more information.
You can convert int into str using string function:
user = "mohan"
line = str(50)
print(user + "typed" + line + "lines")
The easiest and least confusing solution:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: %s" % a + b
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: %d" % c
I found this on http://freecodeszone.blogspot.com/
I also had the error message "TypeError: cannot concatenate 'str' and 'int' objects". It turns out that I only just forgot to add str() around a variable when printing it. Here is my code:
def main():
rolling = True; import random
while rolling:
roll = input("ENTER = roll; Q = quit ")
if roll.lower() != 'q':
num = (random.randint(1,6))
print("----------------------"); print("you rolled " + str(num))
else:
rolling = False
main()
I know, it was a stupid mistake but for beginners who are very new to python such as myself, it happens.
This is what i have done to get rid of this error separating variable with "," helped me.
# Applying BODMAS
arg3 = int((2 + 3) * 45 / - 2)
arg4 = "Value "
print arg4, "is", arg3
Here is the output
Value is -113
(program exited with code: 0)