Scientific Linux

  Reply to this topicStart new topicStart Poll

> Python Lesson 3
 Posted: Aug 5 2011, 10:43 AM
Quote Post


Group: Members
Posts: 47
Member No.: 180
Joined: 15-May 11



First up I'd like to apologise for the huge delay in this lesson, I haven't given up, don't worry. I have been busy these lessons will be continuing. Okay so before we get started really I hope you've grasped lesson 1 & 2 and done the exercises, the answers to some of lessons 2 exercises are:

8) What number is 1101 in 2s complement?

9) Whats the number 1011.0100?

10) Whats the number 1011.101?

Okay! So this lesson I think its time to get down to some real material now we have some theory out of the way and we can assign variables and such. For this lesson we will do basic input and output (just stdout and stdin).


Okay well whats all this stdout and stdin nonsense then? Well stdout is short for standard output in and for this just assume the terminal, while that isn't technically always the case its good enough for what we're doing.

First we'll look at standard output and we'll do this with the trusty program we all must right at some point... hello world!


>>> print "Hello World"
Hello World

Lets look what's going on, we have print which we haven't seen before and then a string which we should all be familiar with. In python 2.x (x just meaning any version) print is statement and everything after it will be sent to standard out (the terminal). After it happens to be "Hello world" and so that's sent to the terminal. we can also print numeric valus


>>> print 72

But for the same reasons in the previous lessons we couldn't mix data types also here we can't


>>> print "Hello " + 72
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

So you're most likely thinking how do I print numbers maybe I want to do some maths and then print "Answer: " and you might remember str() function from previous lessons and yep that does indeed work:


>>> print "Hello " + str(72)
Hello 72

It's not really the done thing in python, it just doesn't look very neat and nice though its not wrong and if you choose to do that that's fine. There are string formatting which is a neat little thing I haven't yet shown you. It works by putting a place holder in the string and then passing the arguments after, python in the backend will then convert them.


>>> print "Hello %s" % 72
Hello 72

So this might look a little scary, we have % signs all over the place and you're wondering how this is at all nicer than simply making 72 a string and adding it. Well the % is the place holder, the s after stands for string so %s is a string place holder. There are other place holders for example %i which is integer and f for float but I don't suggest you use them, python without you having to see's you have 72 (an integer) yet put a place holder for a string so it casts 72 and then inserts it. Since we're only displaying things to the user a cast will be made at a lower level so doing much else but %s isn't really needed. You also are more prone to make mistakes for example if you do %i yet pass a string it can't make that an integer so it'd fail.


>>> print "Hello %i" % "bob"
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str

When we want to fill a string with multiple things we enclose the things we pass in parenthesis ():


>>> print "I need to install version %s of %s on my computer" % (6.1, "Scientific Linux")
I need to install version 6.1 of Scientific Linux on my computer

Cool eh? Well I think so smile.gif You can also print variables and format strings with variables so:


>>> version = 6.1
>>> distro = "Scientific Linux"
>>> print distro
Scientific Linux
>>> print "I love version %s of %s" % (version, distro)

You will see why this is really important when we get further into python, at the moment assigning variables most likely seems a little silly, why not just use the value but its worth it as variables can be easily changed but the print statement can stay the same.


You might have guessed stdin is standard input, this is when you type into the terminal. You can do this with a function so that's like str() but instead of making an integer, float, etc.. into a string this asks the user for some input. The function is called raw_input, and what goes inside the parenthesis is the text you would like to be shown for example:


>>> raw_input("What is your name: ")
What is your name: Jessica

So whats gone on is I have run the function raw_input which gets input of the user, I have also while doing this output "What is your name: "... I typed Jessica and it returned back 'Jessica' which i could have stored in a variable or printed (bit pointless to print as I've just entered it, but it's possible). So lets see if we can store the answer in a variable:


>>> name = raw_input("What is your name: ")

So we've done that but, it looks a bit silly, I mean... We've inputted it but nothing really is shown to us, the programmer so if you're so much inclined you also can print the name and check its really there smile.gif


>>> print name

Okay now lets do something funky and take three inputs and find the mean average (add them all up and divide by how many there are) now this gets a bit tedious in the interpreter and you can put this in a file and run it but for now lets stick with it:


>>> n1 = raw_input("Number 1: ")
Number 1: 7
>>> n2 = raw_input("Number 2: ")
Number 2: 2
>>> n3 = raw_input("Number 3: ")
Number 3: 29
>>> mean = (int(n1) + int(n2) + int(n3)) / 3
>>> print "The avarage is: %s" % mean
The avarage is: 12

So just take this line by line, we assign 3 numbers to variables n1, n2, n3 respectively. We then assign a variable mean, we cast these variables because when you take input its always as a string so we make them integers to do maths on them and then we divide the sum of the three numbers by 3 (to find the mean) and then we print a string "The avarage is: " with the value we've just calculated which happens to be 12 in my case but you can do it for any amount of numbers

Making a python file

Okay when writing the stdin/stdout stuff the last stuff made me realize we're doing enough now that you might want to leave the interpreter and make these files so we have the code in a file and its run behind the scenes and we only ever then will see the output. If you are happy in the interpreter I won't say you have to or even you should do, switch when you're ready but remember this is here for when you do as I won't re-write it later...

So create a file, you can use bash and touch one or open gedit. The file can be anything, but it should end in .py that's the file extension you use for python source files (a source file contains code which is sometimes called source code, hence source). In gedit for example you will find it will highlight things this is called syntax highlighting, you can turn it on in most other editors, google for help.

Once you've got the code in the file save it and go to terminal, like you did in lesson one typing 'python' you now type 'python <file name>' (make sure you're in the directory you saved it in)... so if i had a file called it would be 'python' and it would run the code... note in source files you don't have the >>> that's what's known as the prompt and only happens in the interpreter. You also should note before we did


>>> "Hello"
>>> 7 + 2

And it showed us what that statement or function or whatever it was returned. Now in source files you must print it, if you haven't printed it then you won't see it in the terminal.


1) What do you think will happen if you do this

question1 = "This is question %s" % 1

2) Will this work? if so, what will be the result?

print "%i" % 7.2

3) what will happen when you do this?
print raw_input()
4) you add two numbers and assign them to a variable, how would you display that?
5) How would you ask the user for a number, add 7 to that and display the result?
6) What do you think the result of this will be?


7) Could you ask the user for a number and cast it to be a certain data type and then store it in one line?
PMUsers Website
 Posted: Aug 5 2011, 12:53 PM
Quote Post

Retired SLF Administrator

Group: Admins
Posts: 1276
Member No.: 2
Joined: 8-April 11

Thanks for the next lessons, keep 'm coming

"Sometimes the best helping hand you can give is a good, firm push."
 Posted: Feb 3 2014, 10:49 PM
Quote Post

SLF Junior

Group: Members
Posts: 30
Member No.: 2325
Joined: 1-March 13

print "hello" + str(72)

i get no spaces, why ?
oh you had a space after hello

print "Hello " + str(72)


lame nil and full of idiocy i am..
PMEmail Poster
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

Topic Options Reply to this topicStart new topicStart Poll