Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 An Overview of Python - Tutorial 2: Input and Output
Index -> Programming, Python -> Python Tutorials
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
apython1992




PostPosted: Sun Mar 20, 2011 2:17 pm   Post subject: An Overview of Python - Tutorial 2: Input and Output

Hello again! This is a continuation from my last tutorial, where we discovered what kind of language Python is and how we can go about getting it. If you haven't read that yet, be sure to check it out! Of course, if you already have Python and know full well of its power, then you can just start here. While I mentioned at first that these tutorials are aimed at attracting programmers to high-level languages, I've noticed that there are a lot of you Turing students here, and I think this would also be an excellent way of helping you take the leap into bigger and better. My humble opinion states that Python is an excellent next step to take after Turing! Python is also an excellent first language, so entirely new programmers can hop on board too. So forward we go - open up a terminal/command prompt window, type in the "python" command and behold the prompt of the interactive interpreter.

Hey, a calculator!
As we went through before, Python's interactive interpreter lets you type in python statements one at a time and immediately see the output. If you have never experienced using interactive prompts of any kind, it might be hard to immediately understand why it's so useful and when you could possibly ever need it. But trust me, once you see how it works and start to get a feel for it, you'll really find it useful to write small sections of code just to test something. Well, let's start getting a feel for it. In the window, try typing a simple mathematical expression, and see what you get.
code:
>>> 2 * 3
6
>>>

Awesome! While not necessarily programming-specific, you can kind of see how this gets pretty handy. Try a few more:
code:
>>> 2 + 3 * 4
14
>>> (2 + 3) * 4
20
>>> 7 / 3
2
>>> 7.0 / 3
2.3333333333333335
>>>


So as you can see, Python follows the conventional order of operations as expected. And as you can see Python shares the same division rules like C, C++, and many other languages -> an int divided by an int yields an int, but if one of the numbers is a float, the result will also be a float. However, later versions of Python provide a very convenient method of dealing with division without having to typecast. Of course, Python is backwards compatible, so we can have this functionality in Python2x:
code:
>>> from __future__ import division
>>> 7 / 3
2.3333333333333335
>>> 7 // 3
2
>>>


Wait, what just happened? Since Python is so readable, it's quite easy to guess that we're importing a feature from future versions of Python to use in our current version. Yay! By the way, if you're wondering why we decided to stick with Python2x, it's because Python3x is still very new and a lot of third party libraries haven't caught up, so it's best to wait until it's a little more mature.
So a little more on import: think of this as Python's #include, if you're a C/C++ programmer. The import statement allows you to include a module outside the language's core for some additional functionality; for example, the "import math" statement allows you to use some mathematical functions (like basic trig) that aren't part of the language's core. The "from __future__ import [feature]" statement is slightly different because it acts as a directive to the interpreter to use a feature from future versions of Python. That's pretty neat! As you can see, now we retain floating point accuracy even with two integers when we use the normal division operator, and whenever we need to have the result floored to the nearest whole number we can use the '//' operator. from __future__ statements must always be the first of any "import" statements.

Finally, some programming: The Print Statement
Since this tutorial is really only going to deal with input and output, we'll stick to using the interactive prompt for now. In the next tutorial, we'll start talking about control flow and switch over to writing real programs that we can save and run.

In Python, the print keyword is used to tell the interpreter that whatever comes after it should be output to the console. This is like Turing's put, C's printf(), and C++'s cout. Pretty straightforward, right? Right on. Let's try a couple of examples:
code:
>>> print "Hello, world!"
Hello, world!
>>> print 300
300
>>> print 7.894
7.894
>>> print 300 + 7.894
307.894
>>> print (3 + 9) / 4
3
>>> print "Hello! My name is Andrew, and I'm", 18, "years old!"
Hello! My name is Andrew, and I'm 18 years old!
>>> print "Hello! My name is Andrew, and I'm {0} years old!".format(18)
Hello! My name is Andrew, and I'm 18 years old!
>>>

So as you can see, the print statement is pretty flexible. It will output any value, no matter the type. In a couple of later tutorials, you'll see that you can even print representations of objects. We tried printing mathematical expressions too - really, they just resolve to a single value, which print can handle! In the last two examples, you can also see that it's possible to print mixed types of values as well. The first example uses commas to separate values (string, int, string), where the second example uses string formatting. With string formatting, wherever you see the curly braces with a number, that means that a value of any type will be substituted by any values that are pumped in to format(). You can have any number inputs to format(), which correspond with the numbers inside the curly braces. Example:
code:
>>> print "First: {0}, Second: {1}, Third: {2}, Fourth: {3}".format(1, 2, 3, 4)
First: 1, Second: 2, Third: 3, Fourth: 4
>>>

In this way, you can see that the numbers inside the curly braces index the inputs to format, so {0} really says "Use the first input of format". This should be pretty straight forward even if you've never learned about sequences of any kind yet. We'll see more uses of string formatting coming up:

Getting User Input
Great, so now we're totally bored. One and a half tutorials and all we know how to do is print stuff to the screen. Show us how to get user input please, for the sake of all of us!

Well, okay! Getting input is very easy in Python. There are really two main ways to do it: using input() or raw_input(). Both of these are implemented in the same way. We always want to store input into a variable, so we can refer to the value later. In Python, it looks like this:
code:
var = input([prompt])

and
code:
var = raw_input([prompt])


Here, "prompt" is simply a string that should tell the user what to input, like "Please enter your name: ". This is really nice, because it combines the prompt output and the storage of input into one line. Handy! To show you the main difference between input() and raw_input(), consider these examples:
code:
>>> age = input("Please enter your age: ")
Please enter your age: 18
>>> print age
18
>>> age = raw_input("Sorry, I forgot already. What is your age again? ")
Sorry, I forgot already. What is your age again? 18
>>> print age
18
>>> name = raw_input("Great. And what is your name? ")
Great. And what is your name? Andrew
>>> name = input("I forgot already. Wow. Name again, please? ")
I forgot already. Wow. Name again, please? Andrew
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'Andrew' is not defined
>>>


Woah, back up. What happened? Well, as you can see, there were no problems when we asked the user (me!) to enter his age. It worked with both input() and raw_input(). But when we asked for my name...it was a little different. It worked just dandy when using raw_input(), but the interpreter barked at us when we tried using input(). Why? When using input(), it expects to receive a numerical value only, like an integer or a float. So when we gave it a string, it didn't know how to handle it. With raw_input(), all input is treated as a string. For this reason, I suggest ALWAYS using raw_input(). It's an easy way to keep your programs fool-proof, and you can deal with proper type-casting internally instead of worrying about whether the user might accidentally hit a '\' before hitting enter. Use raw_input(), and then if you need to actually use it as a number you can always convert it by using int([value]) or float([value]). So we're going to go ahead and wipe input() from our memories.

An exercise: Using the interactive prompt, ask the user for a name and age, and use string formatting to produce a single line of output structured as follows:

code:
Hello, [name], nice to meet you! I'm [age] too!


I know. This is really easy. But I do want to see new programmers venturing into Python as well, so I apologize if this is a slow start for you. Keep checking back though, new tutorials are coming and you can skip over whatever you want!

Now, here's something I'm going to start doing for every tutorial: a challenge question for new Pythoneers, where I will donate 10 bits to the first member who can answer correctly. And please, exercise discretion: if you have experience at all with Python, Ruby, or anything like that, don't be a jerk! Let the newbies give this a go. If you know languages like C, C++ or Java but have never used Perl, Python, or Ruby, you're allowed in on this too.

Challenge 1: What does the statement
code:
print "Age: {0}".format(18)
imply about the nature of all data in Python?

And by the way, this is the first time I've ever done any kind of tutorial, so feel free to harass me a little bit. My goal here is to teach. I love teaching, and I want to see the Python community here grow. So if there's something you think I should do differently or add, let me know! That's all for this tutorial guys. Stick around, it's gonna get real fun real fast. Next up is writing and running real programs with control flow.
Sponsor
Sponsor
Sponsor
sponsor
SNIPERDUDE




PostPosted: Mon Mar 21, 2011 1:38 pm   Post subject: RE:An Overview of Python - Tutorial 2: Input and Output

Very nice tutorial, good to see more on Python here
Display posts from previous:   
   Index -> Programming, Python -> Python Tutorials
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 2 Posts ]
Jump to:   


Style:  
Search: