# Some beginner's questions about python



## Niilesh (Apr 2, 2012)

I have started leaning python(3.2) recently. I am using 'A Byte of python'(ver. 1.92) to learn.I selected this book because i have no programming experience(but i have seen about 15 video tutorials of C++ so i know about variables and if statement). It's a good book but i feel is less compressive. Are there any better books available?

Some more questions :
Q.Is IDLE is the right choice for a beginner like me? 
Q.How create executable python programs?
Q.Whenever i run script by pressing F5 in IDLE, it restarts the python shell then run it. Is it normal?(by restarting i do not mean that it again runs it in another window) 
Q.How to run python programs directly from python shell?(by knowing its name and directory)


----------



## coolpcguy (Apr 2, 2012)

> Q.Is IDLE is the right choice for a beginner like me?



IDLE will do fine.



> Q.Is IDLE is the right choice for a beginner like me?


Which OS? If it's Windows there's Py2Exe



> Is it normal?


Not sure I understand this, it runs in the same shell. Then again, I'm on Linux



> Q.How to run python programs directly from python shell?(by knowing its name and directory)




```
execfile('filename')
```


----------



## Niilesh (Apr 2, 2012)

Thanx for answers 


coolpcguy said:


> Not sure I understand this, it runs in the same shell. Then again, I'm on Linux


Yes it runs in the same shell
*i.imgur.com/wsQK2.jpg

BTW you didn't quote properly.


----------



## coolpcguy (Apr 2, 2012)

^ Your link is broken. Seems like imgur is having problems.
(yea, Markdown to BBCode trips me always)


----------



## Niilesh (Apr 3, 2012)

^ I am able to see the pic.
Another question
Q.what's the use of specifying filename and directory in the start of the source code?
like this:

```
#!/usr/bin/python
# Filename: str_format.py
```

Also 


> Are there any better books available?


----------



## coolpcguy (Apr 3, 2012)

> ^ I am able to see the pic.


Yeah, it's fine now, imgur was down earlier,


```
# Filename: str_format.py
```
That's a comment, part of documentation.


```
#!/usr/bin/python
```

That's a she-bang or a hashbang. It tells the shell what interpreter must be loaded to parse the remaining lines. 

*stackoverflow.com/q/3009192/92837 explains it better. 




> Are there any better books available?



For a new comer, I'd recommend Zed Shaw's Learn Python The Hard Way.

Learn Python The Hard Way, 2nd Edition &mdash; Learn Python The Hard Way, 2nd Edition


Ed: As for the picture, yes that's standard.


----------



## Niilesh (Apr 3, 2012)

coolpcguy said:


> Yeah, it's fine now, imgur was down earlier,
> 
> ```
> # Filename: str_format.py
> ...


I wanted to know whats the point of telling the filename(to fellow readers) ?



coolpcguy said:


> ```
> #!/usr/bin/python
> ```
> That's a she-bang or a hashbang. It tells the shell what interpreter must be loaded to parse the remaining lines.
> *stackoverflow.com/q/3009192/92837 explains it better.


Didn't understand its need will have to read the article on wikipedia



coolpcguy said:


> For a new comer, I'd recommend Zed Shaw's Learn Python The Hard Way.
> Learn Python The Hard Way, 2nd Edition &mdash; Learn Python The Hard Way, 2nd Edition


Its not updated for 3.0 
Worth learning 2.0 after the launch of 3.0 in 2010?



coolpcguy said:


> Ed: As for the picture, yes that's standard.


Ok

Hey can you explain this topic :- Python en:First Steps - Notes


----------



## krishnandu.sarkar (Apr 3, 2012)

Well let's put it like this.

That she-bang has no use in Windows but it's of much use in Linux.

#!/usr/bin/python, asks the system to run the script using that program. Generally programs (read apps for windows) are generally present in /usr/bin/

So python is there in /usr/bin/. So to run python script we need to do...

python file_name.py (in the terminal)

But if we enable the executable bit of that file, and declare that shebang we don't need to run it like that, instead running it by ./file_name.py will execute it, becasue that she-bang already asks the system to execute the file using /usr/bin/python program.

Hope that helps.


----------



## prabhu.wali (Apr 3, 2012)

udacity is a very good source to start learning python Udacity - Free Classes. Awesome Instructors. Inspiring Community.


----------



## coolpcguy (Apr 3, 2012)

You should start with 2.x series, moving to 3.x later isn't that tough. Start with Zerd Shaw's book. Dive into Python IMO is more of a reference for those who know how to do things and want to learn further.



> Didn't understand its need will have to read the article on wikipedia



tl;dr: the file line tells the Linux shell that the file mentioned after #! must be used to interpret the source code after the line. 

Krishnandu.sarkar has explained it fairly well. 



> Hey can you explain this topic :- Python en:First Steps - Notes


What part of it? 

```
#!/usr/bin/env python
```
This one?
This asks the shell what's the location of python binary and uses that location to run it.
in comparison to this:


```
#!/usr/bin/python
```
Where python is run directly from /usr/bin path. The former is preferred because of pyhton (or any other, for that matter) is installed in a location other than the standard, /usr/bin/env will provide the location of python & your script will run, as opposed to the second condition where it'll just fail


----------



## Niilesh (Apr 3, 2012)

krishnandu.sarkar said:


> Well let's put it like this.
> 
> That she-bang has no use in Windows but it's of much use in Linux.
> 
> ...


OK
Thanx.. 



prabhu.wali said:


> udacity is a very good source to start learning python Udacity - Free Classes. Awesome Instructors. Inspiring Community.


I was thinking to join it but its cource had reached the 6th or 7th week so it was pretty late to join..



coolpcguy said:


> You should start with 2.x series, moving to 3.x later isn't that tough. Start with Zerd Shaw's book. Dive into Python IMO is more of a reference for those who know how to do things and want to learn further.


Ok..
It says to use "gedit', should i use it? or use IDLE or Notepad++?


coolpcguy said:


> What part of it?


I first wanted to understand the whole "Executable Python Programs" topic
But now i understand the first part. Explain this :

```
$ echo $PATH
   /usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/home/swaroop/bin
   $ cp helloworld.py /home/swaroop/bin/helloworld
   $ helloworld
   Hello World
```


----------



## Liverpool_fan (Apr 3, 2012)

Niilesh said:


> OK
> I was thinking to join it but its cource had reached the 6th or 7th week so it was pretty late to join..


Just dive in. No worries.



> It says to use "gedit', should i use it? or use IDLE or Notepad++?


Any text editor you like.


> I first wanted to understand the whole "Executable Python Programs" topic
> But now i understand the first path. Explain this :
> 
> ```
> ...


Your $HOME/bin is usually in your path. If you move your script to ~/bin, then you can use your script as an ordinary command without specifying the path.


----------



## Niilesh (Apr 3, 2012)

Liverpool_fan said:


> Your $HOME/bin is usually in your path. If you move your script to ~/bin, then you can use your script as an ordinary command without specifying the path.



So 

```
$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/home/swaroop/bin[B] >This specifies the path of file[/B]
$ cp helloworld.py /home/swaroop/bin/helloworld[B] >this copies it to bin directry[/B]
$ helloworld[B] >This runs it[/B]
Hello World
```
Right?


----------



## Liverpool_fan (Apr 3, 2012)

The first outputs the directory paths which are searched for scripts/programs. Apart from that you're correct.


----------



## coolpcguy (Apr 3, 2012)

> It says to use "gedit', should i use it? or use IDLE or Notepad++?


Whatever you're comfortable with.


```
$ echo $PATH
```

$PATH is the environment variable which mentions the directories the shell will look the file to exist to be able to run without having to mention the full path. 


```
/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/home/swaroop/bin
```

So the shell will look for directories 

 - /usr/local/bin
 - /usr/bin
 - /bin:/usr/X11R6/bin
 - /home/swaroop/bin

In other words, if an executable is located in any of the above directories, you don't have to provide to the full path to the executable. 


```
$ cp helloworld.py /home/swaroop/bin/helloworld
```

Copies helloworld.py to the helloworld file in /home/swaroop/bin/ directory.


```
$ helloworld
```
Runs the file.


----------



## Niilesh (Apr 3, 2012)

What if multiple instances of the file is present in different directories? Will it run all of them. and How will it copy the files with same extension(and name) to same folder?

Also PATH is a command that is registered in linux terminal or the python shell?


----------



## ico (Apr 3, 2012)

Niilesh said:


> What if multiple instances of the file is present in different directories? Will it run all of them. and How will it copy the files with same extension(and name) to same folder?


If /usr/local/bin is before $HOME/usr/bin when you output $PATH and the executable with the same name exists in both, then /usr/local/bin will get priority as it comes first. Just a hypothetical example.



Niilesh said:


> Also PATH is a command that is registered in linux terminal or the python shell?


It's an environment "variable" used by the OS.

Check out %TEMP%, %PATH% and the likes in Windows.


----------



## Niilesh (Apr 3, 2012)

ico said:


> If /usr/local/bin is before $HOME/usr/bin when you output $PATH and the executable with the same name exists in both, then /usr/local/bin will get priority as it comes first. Just a hypothetical example.


OK



ico said:


> It's an environment "variable" used by the OS.
> 
> Check out %TEMP%, %PATH% and the likes in Windows.


OK, Thanks for the example


----------



## $$Lionking$$ (Apr 4, 2012)

Hey guys - I also have a noob query.. 

I'm thinking of learning a scripting language good enuf to put it up on my resume... and I was hoping to learn python.. 

But I already have some experience with haskell so what shud I do??! Haskell Or python?? Also why is that every developer/programmer who is using Linux knows python?! :O I just don't get it!!!

TIA.


----------



## krishnandu.sarkar (Apr 4, 2012)

Well python is the new generation language. It's really easy to grasp for newbies even with no programming background experience.

Also it's cross-platforrm and scalability feature made it more popular.

Sent from my LG-P500 using Tapatalk 2 Beta-5


----------



## nbaztec (Apr 4, 2012)

$$Lionking$$ said:


> Hey guys - I also have a noob query..
> 
> I'm thinking of learning a scripting language good enuf to put it up on my resume... and I was hoping to learn python..
> 
> But I already have some experience with haskell so what shud I do??! Haskell Or python??


I'd say you can learn both. That's the beauty of Python.


$$Lionking$$ said:


> Also why is that every developer/programmer who is using Linux knows python?! :O I just don't get it!!!


Python(or any scripting language for that matter) synergizes well with Linux and it's powerful command line shell. Plus you can use Django on Linux easily. Same can't be said for Windoze users who have been accustomed to mouse clicks and fancy buttons.


----------



## $$Lionking$$ (Apr 4, 2012)

@krishnandu - Ok, that makes sense... thanks! 

nbaztec - Mayne, I dont want to do both!!  

I think Ill delay learning both..


----------



## nbaztec (Apr 4, 2012)

$$Lionking$$ said:


> @krishnandu - Ok, that makes sense... thanks!
> 
> nbaztec - Mayne, I dont want to do both!!
> 
> I think Ill delay learning both..



Then I'd recommend Python.


----------



## abhijangda (Apr 4, 2012)

Go for Python. It is Object Oriented, has a very large library, many bindings of Widget Toolkits are available like PyQt, wxPython, PyGTK, can be used to develop a GUI application or a Web Application. Python is one of the most widely used scripting language. Many softwares and web applications/sites are created in Python. Moreover, it has a clean syntax and increases programmers productivity exponentially. Just go for Python, these are just a small number of plus points of Python.


----------



## Niilesh (Apr 4, 2012)

Hey which habit is better to develop  - to write in double quotes or in single?


----------



## nbaztec (Apr 4, 2012)

^Depends. I use single quotes whenever my string has double quotes and vice versa. Triple double quotes for documentation. Triple single for raw text. Rest of the time it's double quotes for me. It all boils down to personal taste IMO.


----------



## Niilesh (Apr 4, 2012)

Hey guys when I type ./file_name.py in the terminal it says '.' is not recognized.
Does it only run in linux?


nbaztec said:


> ^Depends. I use single quotes whenever my string has double quotes and vice versa. Triple double quotes for documentation. Triple single for raw text. Rest of the time it's double quotes for me. It all boils down to personal taste IMO.


Hmm..
So I would have to chose myself?


----------



## krishnandu.sarkar (Apr 4, 2012)

Yes that thing is only for linux. (Its already written in the book you are following)

Sent from my LG-P500 using Tapatalk 2 Beta-5


----------



## gopi_vbboy (Apr 5, 2012)

python is good for linux...you see so many google services using python on custom linux distro...but it sucks in.windows due to so many abstractions to execute..not so power ful on windows


----------



## nbaztec (Apr 5, 2012)

Niilesh said:


> Hey guys when I type ./file_name.py in the terminal it says '.' is not recognized.
> Does it only run in linux?
> 
> Hmm..
> So I would have to chose myself?


On Linux:
./     : Current Directory 
../    : Parent Directory
~/    : Home Directory

Of these windows supports only _../_ for parent directory.
_./foo.txt_ on windows directly corresponds to _foo.txt_ (enter $HOME environment variable)


----------



## Niilesh (Apr 5, 2012)

krishnandu.sarkar said:


> Yes that thing is only for linux. (Its already written in the book you are following)
> 
> Sent from my LG-P500 using Tapatalk 2 Beta-5


Ok that means She-bang has no use in windows?(in python)
BTW i left that book, I am now following "lean python the hard way" as suggested by coolpcguy.

One more thing  - I wanted to know if by default when *.py files are opened it will be executed by python 2.x
If in the she-bang i will refer to the path of python 3.x. then run ./file_name.py then what will happen.
Also how do you specify path in the shebang?(I mean do one has to mention the drive letter?)
Is this right? -

```
#!C:\python32 python
```


----------



## krishnandu.sarkar (Apr 5, 2012)

Well she-bang is not the feature of python. Its a feature of unix.

If you provide path of python3 in she-bang it'll execute with python3.

Sent from my LG-P500 using Tapatalk 2 Beta-5


----------



## Niilesh (Apr 5, 2012)

nbaztec said:


> On Linux:
> ./     : Current Directory
> ../    : Parent Directory
> ~/    : Home Directory
> ...



$HOME environment variable = "~/" or its "$HOME" only?
Can you give an example (for windows)?

Also What's Home Directory?
If a folder has path like this - C:\a\b\c\d\e\f
Then the home directory will be C:\ or C:\a ?


----------



## krishnandu.sarkar (Apr 5, 2012)

None. Home in linux is somewhat similar to my documents in windows.

In windows every user has their own my documents, on the other side every linux has their own home directory.

Sent from my LG-P500 using Tapatalk 2 Beta-5


----------



## Niilesh (Apr 5, 2012)

krishnandu.sarkar said:


> Well she-bang is not the feature of python. Its a feature of unix.
> 
> If you provide path of python3 in she-bang it'll execute with python3.
> 
> Sent from my LG-P500 using Tapatalk 2 Beta-5


OK...



krishnandu.sarkar said:


> None. Home in linux is somewhat similar to my documents in windows.
> 
> In windows every user has their own my documents, on the other side every linux has their own home directory.
> 
> Sent from my LG-P500 using Tapatalk 2 Beta-5



OK.(again)


----------



## $$Lionking$$ (Apr 5, 2012)

abhijangda said:


> Go for Python. It is Object Oriented, has a very large library, many bindings of Widget Toolkits are available like PyQt, wxPython, PyGTK, can be used to develop a GUI application or a Web Application. Python is one of the most widely used scripting language. Many softwares and web applications/sites are created in Python. Moreover, it has a clean syntax and increases programmers productivity exponentially. Just go for Python, these are just a small number of plus points of Python.



That makes sense....... so python is easy or what?? 
coz if i go for it this will be my first object oriented language....


----------



## krishnandu.sarkar (Apr 5, 2012)

^^Python is really easy to grasp.


----------



## abhidev (Apr 5, 2012)

$$Lionking$$ said:


> That makes sense....... so python is easy or what??
> coz if i go for it this will be my first object oriented language....



its powerful though and any language you learn won't be a waste of time...so go for it


----------



## doomgiver (Apr 5, 2012)

krishnandu.sarkar said:


> ^^Python is really easy to grasp.





abhidev said:


> its powerful though and any language you learn won't be a waste of time...so go for it



thats why its called python.
once you catch its tail, it'll wrap around you and not let go.


----------



## Niilesh (Apr 6, 2012)

Hey Guys strip this code as small as you can

```
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
# we could do these two on one line too, how?
input = open(from_file)
indata = input.read()
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()
output = open(to_file, 'w')
output.write(indata)
print "Alright, all done."
output.close()
input.close()
```

I could only think of this - 

```
from_file = raw_input('input? ')
to_file = raw_input('output? ' )
indata = open(from_file).read()
open(to_file, 'w').write(indata)
```

The writer says it can be done in one line

Hey did i combine these the two lines like the writer wanted?

```
input = open(from_file)
indata = input.read()

to
indata = open(from_file).read()
```
also it gave an error while closing the file, saying something like that nothing is opened. Can someone explain what the line does?

Also what's the need to close the files? To free up RAM? don't the files get closed when the script ends? So, it's only useful when opening big or many files?



doomgiver said:


> thats why its called python.
> once you catch its tail, it'll wrap around you and not let go.


----------



## nbaztec (Apr 6, 2012)

> Hey did i combine these the two lines like the writer wanted?
> 
> ```
> input = open(from_file)
> ...


I think yes, but the correct way ought to be

```
indata = (input=open(from_file)).read();
```
This way you get the file in input so you can close it later.




> also it gave an error while closing the file, saying something like that nothing is opened. Can someone explain what the line does?


Make sure the file exists.



> Also what's the need to close the files? To free up RAM? don't the files get closed when the script ends? So, it's only useful when opening big or many files?


Free RAM - not exactly. Whenever you open a file you effectively own a resource - A resource that you _should_ release when you are done with it. In scripts/programs you might need to close that file so that other parts of your code (or other programs) can use it since you have acquired a lock to that resource. Also, if you open a file in "write" mode, close() flushes out all buffers in the RAM (since you're actually working on the file in a memory buffer) and begins write to the disk (in simple terms saving your work back to disk).


----------



## Niilesh (Apr 6, 2012)

nbaztec said:


> I think yes, but the correct way ought to be
> 
> ```
> indata = (input=open(from_file)).read();
> ...


OK,But i my way is better 
Your last line made me realise my mistake



nbaztec said:


> Make sure the file exists.


I was confused. when i give this command - "indata.close()" it gives an error that string object cannot be closed! So it automatically closed it after getting the data? 
Also how do you close to_file after this? - "open(to_file, 'w').write(indata)"



nbaztec said:


> Free RAM - not exactly. Whenever you open a file you effectively own a resource - A resource that you _should_ release when you are done with it. In scripts/programs you might need to close that file so that other parts of your code (or other programs) can use it since you have acquired a lock to that resource. *Also, if you open a file in "write" mode, close() flushes out all buffers in the RAM (since you're actually working on the file in a memory buffer) and begins write to the disk (in simple terms saving your work back to disk).*


So without closing it you cannot write?

Hey I was able to strip down the code into 1 line

```
open(raw_input('output? ' ), 'w').write(open(raw_input('input? ')).read())
```
Now the problem is it asks for output before input. Anyway to get the correct order?


----------



## nbaztec (Apr 9, 2012)

Niilesh said:


> I was confused. when i give this command - "indata.close()" it gives an error that string object cannot be closed! So it automatically closed it after getting the data?
> Also how do you close to_file after this? - "open(to_file, 'w').write(indata)"


You don't close _indata_. You close _input _- the file handle. And no you cannot use _open(...).write(...).close()_ since _open()_, not _write()_, returns the file handle.




Niilesh said:


> OK,But i my way is better


There's no my way or your way. It's the correct way and yours is not it.




Niilesh said:


> Hey I was able to strip down the code into 1 line
> 
> ```
> open(raw_input('output? ' ), 'w').write(open(raw_input('input? ')).read())
> ...


One day you'll realize how bad it is *NOT* to close an underlying stream, release an allocated buffer, dispose an object, close an established connection, heck! even force gc() a managed object. One-liners (think Perl), however, pretty they may be must not come at the cost of writing bad code. Till then check the following code:

```
f = open('foo', 'w')
f.write('hi');
g = open('foo', 'w')
g.write('hello')
```
The output I get is 
	
	



```
hillo
```
And kindly explain to yourself why this is happening. And I'm not even getting on the multi-threaded part yet.


But since you like hacky one-liners anyway here's your solution.

```
[open(raw_input('output? ' ), 'w').write(l) for l in open(raw_input('input? '), 'r')]
```

Bad code is bad code. No excuses. Period.


----------



## Liverpool_fan (Apr 9, 2012)

Note: In Python the file is closed when the last reference to the file object is garbage collected.

This will do for ya  one line code: (Hacky as hell, but whatever, tested in Py3)

```
inp = open(input('input? ')).read() and open(input('output? '), 'w').write(inp)
```


----------



## nbaztec (Apr 9, 2012)

Liverpool_fan said:


> Note: In Python the file is closed when the last reference to the file object is garbage collected.



If there's one thing I've learnt it's - never trust the garbage collector. There's no guarantee when it will be invoked. It's there for our convenience not so that we become lazy programmers.


----------



## ico (Apr 9, 2012)

krishnandu.sarkar said:


> None. Home in linux is somewhat similar to my documents in windows.
> 
> In windows every user has their own my documents, on the other side every linux has their own home directory.


Actually similar to C:\Users\<Username> rather than "My Documents".


----------



## Liverpool_fan (Apr 9, 2012)

nbaztec said:


> If there's one thing I've learnt it's - never trust the garbage collector. There's no guarantee when it will be invoked. It's there for our convenience not so that we become lazy programmers.



Well you have to trust the garbage collector sometimes as well, after all it lays the foundation of the language. In CPython implementation, the file is closed while the object is garbage collected. In fact by using a file object with "with", python programmers are encouraged to let the file object deference outside its scope and not to explicitly close the file object. Indeed explicitely closing the file randomly can generate plenty of problems. (What if you close the file twice, etc.)


```
with open(filename, mode) as file_object:
   # Your code here
   pass
```
See you don't explictly close the file here and let the GC do the job. (All right "with" does the job here for you as well but still).

You are correct not to trust the GC when you there is no specification and guarantee how a GC will behave, in those circumstances assumptions lead to programmers shooting themselves on the foot. But otherwise with clear cuts specs and implementation, it's fine.


----------



## nbaztec (Apr 9, 2012)

Liverpool_fan said:


> Well you have to trust the garbage collector sometimes as well, after all it lays the foundation of the language. In CPython implementation, the file is closed while the object is garbage collected. In fact by using a file object with "with", python programmers are encouraged to let the file object deference outside its scope and not to explicitly close the file object. Indeed explicitely closing the file randomly can generate plenty of problems. (What if you close the file twice, etc.)
> 
> 
> ```
> ...


with is semantically similar to using in C# and both essentially work in the same way. While using requires the enclosed object to implement the IDispose interface [method: void Dispose()], with requires the object to provide __enter__() and __exit__() (same principle). Both are built into their native languages to call the appropriate methods when leaving the block/scope. There's no question of relying on gc here, since with/using do the job by cleaning up in __exit__()/Dispose(). Agreeably, this is the best way to use handles in both Python & C#, or for that matter, any object implementing these methods/interface. But for others, you gotta do it old skool. 



> You are correct not to trust the GC when you there is no specification and guarantee how a GC will behave, in those circumstances assumptions lead to programmers shooting themselves on the foot. *But otherwise with clear cuts specs and implementation, it's fine*.


Exactly my point. If you know what you're doing and what _is_ actually required, you won't be having any issues.


----------



## krishnandu.sarkar (Apr 9, 2012)

ico said:


> Actually similar to C:\Users\<Username> rather than "My Documents".



Ya that's what I meant..!! But couldn't explain it correctly.

Thanks for that


----------



## ©mß (Apr 29, 2013)

So,I am learning Python(v2.7.4) in school.


So while I was practicing,I thought if i could write the line "print Input1+Input2" 
along with the line "print Answer is".
I tried to do it so but it gave a syntax error.
So, can lines be written as I am trying to write?

Also, tell me how to upload image as OP did.
I want the image to appear rather than the link.


----------

