1
def copy_file(from_file,to_file):
    content = open(from_file).read()
    target = open(to_file,'w').write(content)
    print open(to_file).read()

def user_input(f1):
    f1 = raw_input("Enter the source file : ")

user_input(f1)
user_input(f2)

copy_file(user_input(f1),user_input(f2))

What is the mistake in this ? I tried it with argv and it was working.

Golddidit
  • 19
  • 4
  • 1
    You have drastically changed the nature of the question with the changes you've edited in, and this is with an answer to the original below. Unless you legitimately made some sort of mistake, this is frowned upon. If you did make a mistake, please let the answerer below know about it. – jpmc26 Jan 23 '15 at 12:24

1 Answers1

1

You're not calling the function user_input (by using ()). (fixed in question by OP).

Also, you need to return a string from user_input. currently you're trying to set a variable f1 which is local to the function user_input. While this is possible using global - I do not recommend this (this beats keeping your code DRY).

It's possible to do something similar with objects by changing their states. String is an object - but since strings are immutable, and you can't have the function change their state - this approach of expecting a function to change the string it's given is also doomed to fail.

def user_input():
    return raw_input("Enter the source file :").strip()

copy_file(user_input(),user_input())

You can see user_input does very little, it's actually redundant if you assume user input is valid.

Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
  • I think changing `f1` is more a pass-by-value problem than it is a mutability problem. (Although, the technical term is "pass-by-object-reference," apparently.) The OP is trying to reassign the variable, which is exactly how you "modify" a string. – jpmc26 Jan 23 '15 at 12:26
  • @jpmc26 any comments? I've edited to explain it's possible using `global` first, but not a good idea. – Reut Sharabani Jan 23 '15 at 12:33
  • Thanks, Sorry, I am still at a very nascent stage, its just been two days. I am basiclly unable to understand the underlying concept of "pass-by-object" and "pass-by-reference" terms. Can you suggest some resource that I can read to grasp these concepts? – Golddidit Jan 23 '15 at 12:38