How do I print to the stdout in python 3? - python

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

Related

Python Print statements don't work

a = input('enter a ')
b = input('enter b ')
c = input('enter c ')
def is_right_angled(a, b, c):
a, b, c = sorted([a, b, c]) #sort inputs smallest to largest
pathag=(a * a + b * b - c * c) #< 0.1 #a ^2 + b ^2 - c ^2 should = 0 approx
if pathag<0.1: # test "pathag" to to see if close
print ("This is a right triangle")
else: # if "pathag" not close, not "right"
print ("This is NOT a right triangle")
return abs(a * a + b * b - c * c) < 0.1
There could be a couple issues specific to the print function not working (I think you might also want to revisit some of the logical assumptions driving your is_right_angled function.)
1) An input function creates a string variable. You will need to explicitly convert this to an int or float variable in order for your function to correctly work with these variables.
a = float(input('enter a '))
2) You are not actually calling the function in the above code. Be sure to call it or the code won't run. Add this to the end of your script:
is_right_angled(a, b, c)

Average calculator to run python scripts with arguments

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().

Function returning 1 instead of the reverse of the Number

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?

python: list index out of range error in code

I'm pretty new to python, and really stuck at this.
Basically, I'm supposed to make a check code to check the last alphabet of the NRIC. My code works fine so long as there are 7 numbers (like there are supposed to be). However, my teacher just helped me find out that my code doesn't work whenever the number starts with 0. Below is my code.
def check_code():
nricno = int(input("Please enter your NRIC(numbers only). If you don't type an nric number, this code will fail."))
NRIC = [ int(x) for x in str(nricno) ]
a = NRIC[0]*2
b = NRIC[1]*7
c = NRIC[2]*6
d = NRIC[3]*5
e = NRIC[4]*4
f = NRIC[5]*3
g = NRIC[6]*2
SUM = int(a + b + c + d + e + f +g)
remainder = int(SUM % 11)
leftovers = int(11 - remainder)
rightovers = leftovers - 1
Alphabet = "ABCDEFGHIZJ"
checkcode = chr(ord('a') + rightovers)
print(checkcode)
check_code()
This is the way the NRIC is supposed to be calculated, in the image below.
NRIC calculation help.
When you convert the string input into an int, the leading zero is stripped away (e.g. "0153444" -> 153444). When you convert back to a string again in the list comprehension, you won't get the zero back, so you end up with an NRIC list of [1, 5, 3, 4, 4, 4] instead of [0, 1, 5, 3, 4, 4, 4]. If you remove the int call, like this, you won't lose the leading zero.
# Change this:
nricno = int(input("Please enter your NRIC(numbers only)..."))
# To this:
nricno = input("Please enter your NRIC(numbers only)...")
Here's a compact way to calculate the NRIC check code. If an invalid string is passed to the function a ValueError exception is raised, which will cause the program to crash. And if a non-string is passed TypeError will be raised. You can catch exceptions using the try:... except syntax.
def check_code(nric):
if len(nric) != 7 or not nric.isdigit():
raise ValueError("Bad NRIC: {!r}".format(nric))
weights = (2, 7, 6, 5, 4, 3, 2)
n = sum(int(c) * w for c, w in zip(nric, weights))
return "ABCDEFGHIZJ"[10 - n % 11]
# Test
nric = "9300007"
print(check_code(nric))
output
B
Edit: This code verifies if the input is made of 7 digits.
def check_code():
while True:
nricno = input("Please enter your NRIC(numbers only). If you don't type an nric number, this code will restart.")
if len(nricno) == 7 and nricno.digits == True:
print ("Works")
continue
else:
print("Error, 7 digit number was not inputted and/or letters and other characters were inputted.")
a = NRIC[0]*2
b = NRIC[1]*7
c = NRIC[2]*6
d = NRIC[3]*5
e = NRIC[4]*4
f = NRIC[5]*3
g = NRIC[6]*2
SUM = int(a + b + c + d + e + f +g)
remainder = int(SUM % 11)
print(remainder)
leftovers = int(11 - remainder)
rightovers = leftovers - 1
Alphabet = "ABCDEFGHIZJ"
checkcode = chr(ord('a') + rightovers)
print(checkcode.upper())
check_code()
When you force your input as an int, the leading 0 will be interpreted as an error in Python 3. For example, int(0351) would not yield either 0351 or 351 but would just cause an error stating invalid token.
You should not force the input to be an int, but instead add an assert statement stating that the value inputted must be a 7 digit integer (or a regular statement as you've done if you prefer).
Change this:
nricno = int(input("Please enter your NRIC(numbers only). If you don't type an nric number, this code will fail."))
To this:
nricno = input("Please enter your NRIC(numbers only). If you don't type an nric number, this code will fail.")

TypeError: cannot concatenate 'str' and 'int' objects [duplicate]

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)

Categories

Resources