Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
coding
#1
I'm a raw beginner and am new here.
The console returns (4,9,16), with the brackets.
The next problem is at line number 5 where I have been repeating, i.e. square(1), square(2), square(3).
Which code should I use without repeating square?

def  square(number):
   return number*number

result=square(2),square(3),square(4)
print (result)
Reply
#2
It depends on how you want the results.
one option would be to create a for loop to create the values passed to the function square
Reply
#3
First, please use the code tags, otherwise we lose indentation which is remarkably important in Python.

Your line
result=square(2),square(3),square(4)
gives a result that is a "tuple" - that is why the parentheses. The 3 numbers are parts of one thing, kind of like a list or array.

What I think you are wanting to do is to create a loop that prints the 3 values. Look up for, while, and tuples in the documentation Here
Reply
#4
Thank you for helping me. I was not quite familiar with how to insert code as is. From the reply I have also detected that I did not ask my questions properly. Question 1: the console returns (4,9,16). How do I make it not return the brackets? Question 2: At line 5 I would like to add more numbers,ie, 6,7,8,9 and 10 but adding square before each shall be too long and very repetitive. What would be the short code for that?

def square(number):
    return number*number


result=square(2),square(3),square(4)
print(result)
Reply
#5
def square(number):
    return str(number*number)
 
result = []
for i in range(2, 11):
   result.append(square(i))
print ','.join(result)
Reply
#6
Or,
def square(number):
    return number*number
for num in range(1,10):
    print(square(num), end=', ')
print(square(10))
The end= parameter makes it so the print statement puts a comma and space after each number. You don't want to do that for the last item so it is handled as a special case.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020