View Full Version : Let's learn how to mod in civIV... Today!


Pages : [1] 2 3

Gingerbread Man
Aug 16, 2004, 08:02 PM
Go to my python tutorial website (http://sthurlow.com) for updated versions of all the lessons posted in this thread. The site also contains some other things that may be useful for your Civ Python modding adventures, so feel free to have a look, and ask questions in this thread if they arise.

Lesson Index:
(Opens in a new window. Post number Next to link)
Lesson 1 - What is Python, and how do I install it? (http://forums.civfanatics.com/showpost.php?p=2106016&postcount=25) Post 25
Lesson 2 - One-liners - very simple 'programs' (http://forums.civfanatics.com/showpost.php?p=2123632&postcount=43) Post 43
Lesson 3 - Programs in a file, and variables (http://forums.civfanatics.com/showpost.php?p=2152895&postcount=70) Post 70
Lesson 4 - Loops, Loops, Loops, Loops, Loops, Loops... (http://forums.civfanatics.com/showpost.php?p=2172780&postcount=85) Post 85
Lesson 5 - Oh, how functional! (http://forums.civfanatics.com/showpost.php?p=2209889&postcount=105) Post 105
Lesson 6 - Tuples, Lists, and Dictionaries (http://forums.civfanatics.com/showpost.php?p=2246303&postcount=120) Post 120
Lesson 7 - another loop, and a simple game (http://forums.civfanatics.com/showpost.php?p=2284479&postcount=134) Post 134
Lesson 8 - Let the classes begin! (http://forums.civfanatics.com/showpost.php?p=2381434&postcount=153) Post 153
Lesson 9 - 'Borrowing Other People's Stuff (with Modules) (http://forums.civfanatics.com/showpost.php?p=2495872&postcount=187) Post 187
Lesson 10 - File I/O (http://forums.civfanatics.com/showpost.php?p=2500278&postcount=189) Post 189
Lesson 11 - Exception Handling: dealing with the dumb (http://forums.civfanatics.com/showpost.php?p=2536560&postcount=197) Post 197

Firaxis made a daring and interesting move when they announced that much of the modding in cIV will be in Python and XML. Python is a well established language that is well known among server-side scripting and open-source communities. XML is a relatively new markup language, often mistaken for something like HTML, but actually has an entirely different purpose.

with Firaxis making this move, the civ modding community has an unprecidented opportunity - they can learn the modding language before the game evn comes out!

So, I'm thinking, with at least a year until cIV comes out, we should start learning python an XML now! By learning python, and focusing on the logic aspects of it that will be used in the AI, we may only need a slight learning curve to adapt it to cIV.

Here, I am periodically posting very easy, interactive, tutorials in python. Anybody can join, from a person with no programming experience, to a full-blown professional developer. Python and XML are both free, and easy to obtain.

And remember - This is a living tutorial, not some lifeless, static text book. Ask questions, share thoughts, grow your knowledge!

ybbor
Aug 16, 2004, 08:08 PM
uhh, well i guess, i don't know, i;ll try, but i'll probably give uo, i know a bit of HTML abd that's it

Mr. Will
Aug 16, 2004, 08:08 PM
Mr. Will - Dab of HTML, Dab of BASIC :lol: , Attempted Visual Basic

Gingerbread Man
Aug 16, 2004, 08:30 PM
Wow, excellent response!

ybbor - that's fine, just give it a go, just do as much as you can.
Mr. Will - great to have you on board.

Gogf
Aug 16, 2004, 08:41 PM
I'll join. I know some HTML.

Gingerbread Man
Aug 16, 2004, 08:43 PM
I welcome Gogf to the team!

warpstorm
Aug 16, 2004, 09:09 PM
Extensive professional Python programming as well as use of XML for data storage. I don't know how much I'll be able to participate though...

To get started on this go to www.python.org for details on Python. If you know nothing about Python start here http://www.python.org/topics/learn/ This has links to excellent tutorials for all levels of programmers (including those who have never programmed before).

Go to http://www.python.org/2.3.4/ to get the latest version of Python. You may also want to get the win32all package for it. This is a Windows specific IDE that is very good.

Gingerbread Man
Aug 16, 2004, 09:25 PM
Alrighty!
Thanks warpstorm for the links. I found that site, though didn't know if it was good or not.

As for your participation, do as much as is convenient for you. I was hoping for somebody with professional skills, to help us along when we get stumped. Just your prescence should make it easier.

Jon Shafer
Aug 16, 2004, 09:57 PM
Extensive professional Python programming as well as use of XML for data storage. I don't know how much I'll be able to participate though...
Be able to or want to? ;) :)

I suppose I'll join up. I know VB, C++, some C, some XML and some Python (I don't count HTML as a real language ;)).

Gingerbread Man
Aug 16, 2004, 10:08 PM
Welcome aboard, Trip! It's great to have people with previous knowledge help.

When this starts, should we move it to the Computer Talk forum, or leave it here? I figure seeing it will be civ-focused, it should stay, but that will be a decision for the mods.

Jon Shafer
Aug 16, 2004, 10:15 PM
Oh, I know Java also. Almost forgot about that. That and I know HTML and BASIC quite well, if you want a complete list of my knowledge.

Jon Shafer
Aug 16, 2004, 10:25 PM
By the way, I think this is a really good idea. Having a communal learning effort is a really good idea, it'll help me as I continue to learn Python and how it is similar and differs from the other languages I know. ;)

Gingerbread Man
Aug 16, 2004, 10:32 PM
Yeah, this will also be really good for my software classes that I am starting in school next year. They dont actually teach you a language - you have to pick one, learn it, and apply the theory you learn in class to a program you make. I figured I'd learn python with you guys who will probably be interested in learning it for cIV, and kill two birds with one stone :D

Jon Shafer
Aug 16, 2004, 10:33 PM
Clever, I like the way you think. ;)

Coorae
Aug 16, 2004, 11:47 PM
I want to join
I have 3 years expreience in C++ and VB and Blitz. I know some java and html.
I dont know what xml or python is though.

Gingerbread Man
Aug 17, 2004, 12:26 AM
Welcome aboard Coorae!

Never heard of Blitz. What is it?

Python is described at www.python.org
Dont know where XML is decribed, though.

Jon Shafer
Aug 17, 2004, 12:45 AM
There's a FAQ here, but it mostly describes XML's application in an internet-based environment.

http://www.ucc.ie/xml/

For CIV it will be used to store variables of various sorts that modders can change in order to create mods/scenarios.

MMAfan
Aug 17, 2004, 02:35 AM
JAVA, education.
Pascal, education (yak! :thumbdown )
C, I used to program my college student exercises.
C++, well know the syntax.
Perl, programmed some part for a system that track positions with GPS.
XML, used it in above system.
HTML, I know how to echo it from a php file. :blush:
JAVASCRIPT, JSCRIPT ASP.
PHP, using it right now.

Oh and I love to discuss AI architecture and design :)

Havent got much time to teach.. I am a bad teacher anyway ;)

Now where is the thread where we start designing the AI?? :goodjob:

Gingerbread Man
Aug 17, 2004, 05:46 AM
Welcome MMAfan!

I'll be starting the thread where we learn Python in about 24hrs - we need to give other people the opportunity to join.

We'll start programming AIs as soon as we are fluent enough in Python. I think we might make a very simple game (no more complex than pong) and make an AI for that as a start. Once we get that, we'll move up to another level. But that will be a while - some of us haven't learnt python at all yet.

Chieftess
Aug 17, 2004, 07:53 AM
I'll join up. Make a nice tutorial thread, and I'll sticky it.

croxis
Aug 17, 2004, 11:36 AM
I'll join. Maybe Friaxis could provide some details of the API as well (I think its called API... I'm just a computer nerd wannabe)

Experience: Some HTML, C++, Java. I'm not very fluent in any of them however

bob rulz
Aug 17, 2004, 03:09 PM
Let's see, I'll join up...I have no experience whatsoever.

Coorae
Aug 17, 2004, 11:14 PM
yay, I am on the team, I have cable so I can participate every day ;)

Blitz is a programming language meant for making games. It is one of the best languages if you only want to make games (meaning dont ever want to get a job in programming, or code an operating system)
www.blitzbasic.com

Gingerbread Man
Aug 18, 2004, 01:43 AM
Welcome CT, croxis, and bob rulz!

I'll post the first lesson in a few hours. And that doesn't mean that people can stop joining.

Also, I'll be tracking people's progress. At the start of each new lesson, I will post a list showing each person's progress in the lesson. That way, we'll stop some people getting left behind. You can choose to take the lesson, skip it, or do it later. I will adjust the list accordingly. Notify me if you are stuck at a certain point, too busy, or unable to complete the lesson. As a general rule, we'll wait for the people who are stuck at some point, and continue when they have somewhat grasped the idea (again, a general rule. NOT STRICTLY HELD BY!) I will then post it as:

Name Progress
Person A WAITING
Person B IN PROGRESS
Person C SKIPPING
Person D COMPLETING LATER
Person E STUCK
Person F COMPLETED

Links to all lessons will be at the top.

Wait a few hours, and we're ready to go!

Gingerbread Man
Aug 18, 2004, 02:40 AM
LESSON 1:
What is python, and how to install it.

What is Python?
If you don't understand this, don't worry. Just skip it and move on.
Python is an interpreted programming language.
For those who don't know, a programming language is what you write down to tell a computer what to do.
However, the computer doesn't read the language directly - there are hundreds of programming languages, and it couldn't understand them all. So, when someone writes a program, they will write it in their language of choice, and then compile it - that is, turn it in to lots of 0s and 1s, that the computer can easily and quickly understand. A windows program that you buy is already compiled for windows - if you opened the program file up, you'd just get a mass of weird characters and rectangles. Give it a go - find a small windows program, and open it up in notepad or wordpad. See what garbled mess you get.

But that windows program is compiled for windows - no other machine can run that program, unless it has windows. What Python is, is a language which is never actually compiled in full - instead, an interpreter turns each line of code into 0s and 1s that your computer can understand this. And it is done on the fly - it compiles the bits of the program you are using as you are using them. If you were to quit the program and come back another day, it would compile the bits you are using, as you are using them, again. Seems a waste of time? Maybe, but the fact is that when you come back another day, you might be using a Windows instead of a Mac. You might send the program to a friend, who uses another type of computer. Or you might post your program on the internet, where everyone using all different types of systems might download it. That is the wonder of an interpreted programming language - it is like a language that EVERYONE can understand.

So why will cIV use Python?
Remember that garbled mess that you got when opening a program in notepad? Not much use to anyone, apart from the computer. And there is no reliable (or legal) way of turning that program back in to a programming language that you or I could understand.
The same is with Civ3 AI - it is compiled into a garbled mess. Nobody can understand it, and most of all, nobody can change it. Only Firaxis can change the AI, and they cant share the logic behind it with anyone.
With cIV, they decided to change that - they would leave the AI uncompiled in the language of Python, and have it compiled on-the-fly by an interpreter. This is so that Joe modder can look at the AI and change it, yet when it is neede to be used, the python interpreter turns it into 0s and 1s for your computer to understand. And it isn't permanently compiled into a garbled mess - you are still left with python code, that you can read, understand, and MODIFY!!!!!

How do you install Python?
First download Python-2.3.4.exe (http://www.python.org/ftp/python/2.3.4/Python-2.3.4.exe) by following this link.
DAILUP USER'S WARNING - THIS FILE IS 9.4MB!
If you aren't using windows, tell me and I'll post instructions for Linux, or I'll google for Mac information.

Run the file you just downloaded, and follow the prompts.
(TODO - Details on the prompts)

OK! Hopefully now everything is good!

Now, to test if that just worked, type this in your DOS window:
python -V
Remember to use a CAPITAL V. If everything is good, you should see:
Python 2.3.4
If you forgot a CAPITAL V, you will accidently load python in verbose mode. Give it a go, see what happens. Just press CTRL-D to quit, or type 'quit' for quit instructions.

Good work! Lesson 1 over! Next lesson, we learn our way around Python Interactive Mode, and write simple one-line pieces of code. I'll also have a lesson plan drawn up by then, so you can see where you are going. If any of our more experienced members have suggestions for the lesson plan, tell me!

Thanks to all, Gingerbread Man.

Harald
Aug 18, 2004, 04:56 AM
Interesting, sign me up. I'm not sure how much I can participate though.
I use c/c++ on a regular basis and I have som knowledge in assambler as well.

And I belive I have completed the first lesson :) (unless I missed something :blush: ).

Gingerbread Man
Aug 18, 2004, 05:32 AM
Welcome aboard Harald!

I'll credit you as completed lesson 1 right away.

I'll remain as in progress until everyone is happy with how they've done in the lesson.

MMAfan
Aug 18, 2004, 08:02 AM
Downloaded it, not yet installed. Am constantly coding php/sql with some short breaks here on this forum to keep my head from exploding. :crazyeye: Dont even have the nights off... :(

I will probably install it after a coming backup (yes i am paranoid!)

I have 1 suggestion... Not with the python tutorial but another tutorial..
We should also gather information (and a tutorial if possible) of the abstract aspects of AI design. Not thing like A* pathfinding, since this stuff will be either hardcoded or predelevered by firaxis so anyone can use it without trouble. No, we have to get familiar with the higher level stuff of AI of strategy games.

It is a pity that there are no examples. to my knowledge no one, ever bothered to make a good AI. So:...

1. we cant copy anything
2. most stuff is theoretical
3. we will have to figure things out ourselves

back to work... :coffee:

Jon Shafer
Aug 18, 2004, 11:31 AM
Completed this one a while ago. :) ;)

Coorae
Aug 18, 2004, 12:00 PM
I dont know what any other "dos window" is besides command prompt.
I had to open command prompt
type "cd\"
type "cd python23"
type "python -V"
Then I did it.

croxis
Aug 18, 2004, 12:32 PM
done (well downloading, but checking for version shouldn't be too hard )

Coorae: Command Prompt is XPs version of a dos prompt. Also to get it to work at any directory you are going to have to set the system variable, but I am not sure how to do this for python.

Slax
Aug 18, 2004, 02:48 PM
Welcome MMAfan!
I think we might make a very simple game (no more complex than pong) and make an AI for that as a start.

To correlate to CIV, maybe a good example problem would be AI for something like RISK on a basic grid map.

Milan's Warrior
Aug 18, 2004, 08:06 PM
I answered to the first post and it turned up to be off topic with the rest of thred so I am editing my post away.

Thanks for "Lesson 1", I have learnt something. I am a programmer in an interpreter language (Stata) and I did not know what an interpreter language was.

I won't join the course, but I still think it is a great idea :)

Gingerbread Man
Aug 18, 2004, 09:33 PM
I have 1 suggestion... Not with the python tutorial but another tutorial..
We should also gather information (and a tutorial if possible) of the abstract aspects of AI design. Not thing like A* pathfinding, since this stuff will be either hardcoded or predelevered by firaxis so anyone can use it without trouble. No, we have to get familiar with the higher level stuff of AI of strategy games.

It is a pity that there are no examples. to my knowledge no one, ever bothered to make a good AI. So:...

1. we cant copy anything
2. most stuff is theoretical
3. we will have to figure things out ourselves

back to work... :coffee:
We will be designing some AI in this tutorial, and that includes for existing games. even if it is way later on.
Oh, and search SourceForge (hyyp://www.sourceforge.net/) for open source games made in python. There are bound to be tonnes of them, even if they are mostly in linux (Which is easily portable, dont you worry...)

See, the open source community is good for everything!

Gogf
Aug 19, 2004, 12:05 PM
Okay, I just skipped all of the thread after I joined, what's going on now, what are we learning, how do we do it, and what's with the status in the main post? Sorry, I don't have any time to read the thread now, about to rush out. Thank you.

Mr. Will
Aug 19, 2004, 08:42 PM
I'll start the lesson tomorrow. Sorry for being late...

Gingerbread Man
Aug 20, 2004, 01:30 AM
Gogf: read Post 24 (http://forums.civfanatics.com/showpost.php?p=2105962&postcount=24) to have the status thing at the top explained.

I will hopefully have the next lesson written in 24hrs, have it posted in 30hrs, but I'll still help those who are stuck on lesson 1. It takes < 10 minutes, it's not much to catch up on.

Mr. Will
Aug 20, 2004, 02:59 PM
Finished Lesson 1!

Blackbird_SR-71
Aug 21, 2004, 01:04 PM
Hi I would like to join and I have no experience what so ever. I completed the first lesson.

Gingerbread Man
Aug 21, 2004, 07:28 PM
Welcome aboard Blackbird!

Sorry guys, couldn't write the next lesson when I said I would. But it is in progress now.

Blackbird_SR-71
Aug 23, 2004, 01:40 PM
Gingerbread Man,
not to put pressure on you but when will the next lesson begin? Again I'm not pressuring you to hurry up your doing a great job to teach us but I'm just wondering?

Thanks for answering my question if you can.

Gingerbread Man
Aug 24, 2004, 01:15 AM
The lesson is about 1/2 complete.

I was going to have a driving lesson, but things went awry, so the being written.

EDIT: It's now 3/4 written, I just have to play in a band for a few hours. Not long, my fellows!

Gingerbread Man
Aug 24, 2004, 05:50 AM
LESSON 2:
One-liners - very simple 'programs'

OK! We have python installed, now what? Well, we program!

And it is that simple (at least for now). Python makes it easy to run single lines of code - one-liner programs. Lets give it a go.

Go to the start menu, find Python, and run the program labelled 'IDLE' (Stands for Integrated Development Environment, it isn't literally idle... think that's dumb? it took me a day to figure that out ;) ) If that doesn't work, go to the command line and type:
python
That starts the IDLE in a command line. You in now? Good.

Now you are in the IDLE environment. Type the following and press enter: (don't type >>> as it should already be there)
>>> print "Hello, World!"
What happened? You just created a program, that prints the words 'Hello, World'. The IDLE environment that you are in immediately compiles whatever you have typed in. This is useful for testing things, e.g. define a few variables, then test an equation. That will come in a later lesson, though.

Now try typing the stuff in bold. You should get the output shown in blue. I've given explainations in brackets.

>>> 1 + 1
2
>>> 20+80
100
>>> 18294+449566
467860
(These are additions)
>>> 6-5
1
(Subtraction)
>>> 2*5
10
(Multiply, rabbits!)
>>> 5**2
25
(Exponentials e.g. this one is 5 squared)
>>> print "1 + 2 is an addition"
1 + 2 is an addition
(the print statement, which writes something onscreen)
>>> print "one kilobyte is 2^10 bytes, or", 2**10, "bytes"
one kilobyte is 2^10 bytes, or 1024 bytes
(you can print sums and variables in a sentence. The commas seperating each section stop a few problems from occuring, which will be discussed later)
>>> 21/3
7
>>> 23/3
7
>>> 23.0/3.0
7.6666...
(division, 2nd ignoring remainder/decimals, 3rd including decimals)
>>> 23%3
2
>>> 49%10
9
(the remainder from a division)

As you see, there is the code, then the result of that code. I then explain them in brackets. These are the basic commands of python, and what they do. Here is a table (because tables look cool, and make you feel smarter ;) )

Command Name Example Output
+ Addition 4+5 9
- Subtraction 8-5 3
* Multiplication 4*5 20
/ Division 8/2 4
% Remainder 15/4 3
** Exponential 2**3 8


Remember that thing called order of operation that they taught in maths? Well, it applies in python, too. Here it is, if you need reminding:
1) parentheses ()
2) exponents **
3) multiplication *, division \, and remainder %
4) addition + and subtraction -

Here are some examples that you might want to try, if you're rusty on this:

>>> 1 + 2 * 3
7
>>> (1 + 2) * 3
9

In the first example, the computer calculates 2 * 3 first, then adds 1 to it. This is because multiplication has the higher priority (at 3) and addition is below that (at lowly 4)
In the second example, the computer calculates 1 + 2 first, then multiplies it by 3. This is because parentheses (brackets, like the ones that are surrounding this interluding text ;) ) have the higher priority (at 1) and addition comes in later than that.

Also remember that the math is calculated from left to right, UNLESS you put in brackets. Watch these examples:

>>> 4 - 40 - 3
-39
>>> 4 - (40 - 3)
-33

In the first example, 4 -40 is calculated,then - 3 is done.
In the second example, 40 - 3 is calculated, then it is subtracted from 4.

The final thing you'll need to know to move on to multi-line programs is the comment. Type the following (and yes, the output is shown):

>>> #I am a comment. Fear my wrath!
>>>

A comment is a piece of code that is not run. In python, you make something a comment by putting a hash in front of it. A hash comments everything after it in the line, and nothing before it. So you could type this:

>>> print "food is very nice" #eat me
food is very nice
(a normal output, without the smutty comment, thankyou very much)
>>> print "food is very nice" eat me
(you'll get a fairly harmless error message, which is a computer trying to tell you it doesn't know what 'eat me' means)

Comments are important for adding necessary information for another programmer to read, but not the computer. For example, an explanation of a section of code, saying what it does, or what is wrong with it. You can also comment bits of code by putting a # in front of it - if you don't want it to compile, but cant delete it because you might need it later.

There you go! Lesson 2 Completed. That was even shorter than lesson 1!
Next lesson, we make programs with many lines of code, and save them, so we can actually send them to people. That's right, you don't have to retype every program you run! What an amazing innovation!

Thanks to all, Gingerbread Man

Blackbird_SR-71
Aug 24, 2004, 08:16 AM
great lesson Gingerbread Man. Thank you for taking time to write the lesson.

I finished the lesson.

Thank you again for the great lesson.

ybbor
Aug 24, 2004, 08:30 AM
please remove me from the program

Neomega
Aug 24, 2004, 01:43 PM
I sure am worried about the graphical aspects of modifying the gamebry engine... allthough the python looks interesting indeed.

Coorae
Aug 24, 2004, 05:16 PM
I am done with lesson 2

Trump
Aug 25, 2004, 01:31 AM
Late joiner here!

Been ghosting this site for the past 6-8 months or so, picking up tips on how to improve my game...Never really felt the need to register. Figured I might as well become a part of this community.

Programming experience = basic Turing (http://www.holtsoft.com/turing/) knowledge...It's the programming language that is taught in grades 9/10 in Ontario...Sort of an intro to programming. Very limitted knowledge of html and perl. And I can count in binary :)

Completed lessons 1 and 2.

Gingerbread Man
Aug 25, 2004, 03:25 AM
well Done Blackbird and Coorae, Welcome aboard, Trump, and sorry to see you leaving, ybbor.
Ybbor - Why the dropping out? If you got stuck somewhere, we're here to help. If you're short on time, well, maybe on day we'll see you catch up again. Good on you for having a go, anyway.

Trump - never mind the late joining, you can join at any time. And welcome to Civfanatics! Hope to see you around, in this forum, and maybe others too!

ybbor
Aug 25, 2004, 06:51 AM
Ybbor - Why the dropping out? If you got stuck somewhere, we're here to help. If you're short on time, well, maybe on day we'll see you catch up again. Good on you for having a go, anyway.

i just don't have the time right now, and i dought i will with school strating in a week :twitch: . i'll try to go through the whole thing over winter break though

croxis
Aug 27, 2004, 01:00 AM
Done, and it says I need 10 chars, so here you are!

Mr. Will
Aug 27, 2004, 03:42 PM
Please PM me when new lessons come out or I'll forget. Hopefully I'll have time to get on later this school year during keyboarding. Working on lesson 2. My my, is it just me or does this look a lot like basic?

Mr. Will
Aug 27, 2004, 03:50 PM
Done, thank you Ginger.

MSTK
Aug 27, 2004, 03:51 PM
I know a lot of HTML, a lot of JavaScript, touches of ASP (JS-based, atleast), and learning PHP.

Gingerbread Man
Aug 27, 2004, 10:56 PM
Welcome MSTK!

I wont maintain the list showing all of our skill levels, until we actually need to use it. We seem to be chugging along fine here.

Hopefully I'll have the next lesson written before long. But I'll definitely wait for the others to catch up.

Taé Shala
Aug 28, 2004, 01:45 PM
I want to subscribe.
I have nearly no programming experience. Tried some things on C64 BASIC 15 years ago.

Edit: when I tried to do "lesson 1" all I got was:

Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name ´python´ is not defined.


:confused: :confused: :confused:

I am running WIN XP Pro.

MSTK
Aug 28, 2004, 05:14 PM
What does it take for me to get to status "Complete"?

Oh, yeah, and I've went over the lessons. They were surprisingly simple. Even on my own I was able to enter and manipulate variables...which you will likely cover in the next lesson, right?
I hope you get to functions (or something like them with a different name) soon. Arrays would be nice.

Blackbird_SR-71
Aug 28, 2004, 06:52 PM
I want to subscribe.
I have nearly no programming experience. Tried some things on C64 BASIC 15 years ago.

Edit: when I tried to do "lesson 1" all I got was:

Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name ´python´ is not defined.


:confused: :confused: :confused:

I am running WIN XP Pro.

I had the same problem but here is how you solve it:

open Command Prompt
type "cd\"
type "cd python23"
type "python -V"

This will work if you installed Python in C:\Python23\ directory.

Hope that helps.......
This instructions are from Coorae so thank him.

Blackbird_SR-71
Aug 28, 2004, 06:53 PM
also just a minor mistake but Gingerbread Man you have me under status for the 2nd lesson as "Waiting". I finished the second lesson. Just want to clear that up.

Taé Shala
Aug 29, 2004, 05:28 AM
I had the same problem but here is how you solve it:

open Command Prompt
type "cd\"
type "cd python23"
type "python -V"

This will work if you installed Python in C:\Python23\ directory.

Hope that helps.......
This instructions are from Coorae so thank him.

Tried this
cd\ ==> creates a new line with ...
cd python23 ==> gives an error:
file "<stdin>", line 2
cd python23
^
SyntaxError: invalid syntax

PS: tried lesson 2 ==> it works!
but 23%3 is 2 not 1 :hmm: :lol:

Blackbird_SR-71
Aug 29, 2004, 10:13 AM
it sounds like your opening Python Command Line which is not what your suppose to use. i guess its alright since you got lesson 2 complete. lesson 1 is just checking if the program is their nothing really big to miss.

Gingerbread Man
Aug 30, 2004, 01:13 AM
Welcome Taé Shala!

I'm addressing all your comments now.

Also, thankyou for pointing out any errors. We cant ignore those!

Gingerbread Man
Aug 30, 2004, 01:21 AM
MSTK - to get to status 'COMPLETED', you need to simply tell me that you have done, or know, the lesson.
Taé Shala - Good to hear that you got lesson 2 done. It just shows how leaning in a group like this can really help.

Gingerbread Man
Sep 02, 2004, 05:03 AM
Sorry for my hopeless commitment here - schoolwork can get a bit heavy at this time of year. Expect the next lesson in 24 hours, and start nagging if it isn't ready in 48hrs. I might have an hour or two to write the next lesson.

In the meantime, How about we discuss the logic of Artificial Intelligence? What makes a computer opponent, what does it need to contribute to a game, and how does it compute what a human does, and react accordingly?

Taé Shala
Sep 02, 2004, 06:35 AM
Let´s take a fight for example. Everyone counts the possibility of winning or loosing a fight by comparing attack vs. defense value. The AI does this too. You compare the terrain and defense status of the defender (fortified, fortress, etc.) and the possibility of surviving for both units. If it is likely that you will win you attack. If it is unlikely you won´t.

Things change when there will be a third unit for support.
If you have artillerie you will weaken up the hp of the defending unit first, trying to get a better possibility of surviving for the attacker. You even attack with both units if there is a chance that the opponent will be destroyed, if it is for any means necessary.

So attacking or not is the choice made using the comparison of possibilities of surviving for both units. If you think you will be lucky enough you attack. If it is unlikely you won´t.
Comparing the possibilities is what the AI does.

Hope you got the point. It is a little bit hard to explain for a non native speaker. :)

CrudeDirk
Sep 02, 2004, 07:48 PM
Hi everyone, I'm gonna have a go at reviving my beer soaked brain & learning this stuff. Learnt some Basic & machine language back in the Z80 processor days, nothing more recent. But what you've covered so far is familiar & I've completed both lessons.

Cheers, Dirk.

Nolan
Sep 02, 2004, 07:54 PM
This looks very interesting.. is there time for me to start too?

MSTK
Sep 02, 2004, 08:04 PM
Yes, there is :D

Gingerbread Man
Sep 03, 2004, 04:40 AM
Welcome aboard CrudeDirk and Nolan! It is never too late to join in, BTW.

I have written the next lesson, just finalising this one now.

Gingerbread Man
Sep 03, 2004, 04:47 AM
LESSON 3:
Programs in a file, and variables.

Well, we can make one-liner programs. So What? You want to send programs to other people, so that they can use them, without knowing how to write them.

Writing programs in python to a file is VERY easy. You just need notepad (or a hotted-up version of it that will automatically colour-code python code it recognises). So, go and open notepad. Type the following:


#A simple program.
print "Mary had a little lamb,"
print "it's fleece was white as snow;"
print "and everywhere that Mary went",
print "her lamb was sure to go."

Keep this exactly the same, down to where the commas are placed. Save the file as 'mary.py' - and make sure notepad doesn't add .txt to the end of the filename. You will have to tell it to save as any file, so it doesn't add that. Turn off 'Hide known file extensions' in windows explorer, if it makes it easier.

Now, open up the Python IDLE program (should be in your start menu). Click 'File > Open' and find mary.py and open it. if you cant find mary.py, set the open dialogue to 'Files of type: All Files (*)'. A new window will open, showing the program you just wrote. To run your program, click 'Run>Run Module' (or just press F5). Your program will now appear in the main Python screen (Titled *Python Shell*) and will look like this:
Mary had a little lamb,
it's fleece was white as snow;
and everywhere that Mary went her lamb was sure to go.
We will be writing all of our programs now in the python IDLE program - the notepad thing is just a demonstration to tell you that a .py file is just a simple text file.

There are a couple of things to notice here. First of all, the comment wasn't shown. That is good, because remember - comments aren't compiled. (try compiling it without the comment - it comes out messy)
The second thing is that the 3rd and 4th line got joined. This is because there is a comma just outside the inverted commas that surround the text. In the 'print' command, this stops the program from starting a new line when writing text.

You can also run the program from your command line program (e.g. MSDOS).
Open the prompt up, type 'cd path\to\your\file'. then type 'python mary.py'. Your program will now execute in the command line.

A more complex program:

Now lets start introducing variables. Open up IDLE, click 'File>New Window' - a new window now appears, and it is easy to type in programs. Type the following (or just copy and paste - just read very carefully, and compare the code to the output that the program will make):

#variables demonstrated
print "This program is a demo of variables"
v = 1
print "The value of v is now", v
v = v + 1
print "v now equals itself plus one, making it worth", v
v = 51
print "v can store any numerical value, to be used in other places later."
print "for example, in a sentence. v is now worth", v, "which is a prime number."
print "v times 5 equals", v*5
print "but v still only remains", v
print "to make v five times bigger, you would have to type v = v * 5"
v = v * 5
print "there you go, now v equals", v, "and not", v / 5

As you can see, variables store values, for use at a later time. You can put in more than numbers, though. Try this program:
#giving variables text, and adding text.
word1 = "Good"
word2 = "Morning"
word3 = "to you too!"
print word1, word2
sentence = word1 + " " + word2 + " " +word3
print sentence
The output will be:

Good Morning
Good Morning to you too!

So yes, variable names can be longer than one letter. They can also hold more than numbers! Here, they hold text.
As you can see, words can be added together to make longer words or sentences. However, it doesn't add spaces in between the words - hence me putting in the " " things (there is one space between those).

Well done! We now understand longer programs, and know the use of variables. Next lesson, we look at functions, what they are, and how to use them.

Thanks to all, Gingerbread Man.

Blackbird_SR-71
Sep 03, 2004, 09:45 AM
great lesson Gingerbread Man,

I completed Lesson 3.

Trump
Sep 03, 2004, 12:25 PM
Finished as well.

Harald
Sep 04, 2004, 01:11 AM
Finished to.
Also the link from the main message to lesson 2 seems to point to the wrong post.
Edit: It should be post 43.

Coorae
Sep 04, 2004, 01:47 AM
I am done.

Taé Shala
Sep 04, 2004, 02:49 AM
Finished. :D

Btw: We should change feedback to PM if nothing special happened. :hmm: Right?

Trump
Sep 04, 2004, 11:56 AM
I don't think so.

While I may be new to this board, post farming is still a perfected art form on other boards :lol:

Jon Shafer
Sep 05, 2004, 04:01 PM
Sorry, finished lessons 2 and 3.

Gingerbread Man
Sep 06, 2004, 12:33 AM
Wow, good work guys!

I wont be able to update anything tonight, but a new lesson will be out in 30-48hrs. I've got some assignments that I should have started a week ago.

Nolan
Sep 06, 2004, 03:04 PM
I finished lesson 3.
Thanks GBM

Nols

CanuckSoldier
Sep 06, 2004, 10:51 PM
Ok, I'm jumping on the band wagon. I've also completed lessons one and two, and working on 3. Thanks for your efforts GBM.

CS

MMAfan
Sep 07, 2004, 05:44 AM
:(

I have to apologize for not attending classes...

I am currently finishing my project for my study and just dont have any time until late oktobre.

On 8 oktobre my 'essay' has to be done. :crazyeye: :rolleyes: :eek: :mad: :sad: :confused: :cool:

Gingerbread Man
Sep 08, 2004, 01:05 AM
Welcome to CanuckSoldier (and any others I have forgotten to say hi to)!

I'm writing the new lesson now, though I dont know when it will be out.

EDIT - MMAfan - Dont worry, just post here when you have caught up. I understand your problem, I'm in the middle of quite a few assesments.

Gingerbread Man
Sep 10, 2004, 07:55 AM
Ok, the new lesson has been written. I'll have to post it tomorrow, there's too much organisation to set the next lesson up tonight.

Until then, remember to post your progress in the lesson! There are many people who haven't yet.

croxis
Sep 10, 2004, 11:24 PM
done with 3

Gingerbread Man
Sep 11, 2004, 12:36 AM
LESSON 4:
Loops, Loops, Loops, Loops, Loops, Loops, Loops...

Ahh, our final lesson before we get into interacting with human input. Can't wait, can you?

Just imagine you needed a program to do something 20 times. What would you do? You could copy and paste the code 20 times, and have a virtually unreadable program, not to mention slow and pointless.

Or, you could tell the computer to repeat a bit of code between point A and point B, until the time comes that you need it to stop. The folling are examples of loops in Python:

a = 0
while a < 10:
a = a + 1
print a

How does this program work? Lets go through it in English:

'a' now equals 0
As long as 'a' is less than 10, do the following:
Make 'a' one larger than what it already is.
print on-screen what 'a' is now worth.

What does this do? Lets go through what the computer would be 'thinking':
a = 0

#JUST GLANCE OVER THIS QUICKLY
#(It looks fancy, but is really simple)
Is 'a' less than 10? YES (its 0)
Make 'a' one larger (now 1)
print on-screen what 'a' is (1)

Is 'a' less than 10? YES (its 1)
Make 'a' one larger (now 2)
print on-screen what 'a' is (2)

Is 'a' less than 10? YES (its 2)
Make 'a' one larger (now 3)
print on-screen what 'a' is (3)

Is 'a' less than 10? YES (its 3)
Make 'a' one larger (now 4)
print on-screen what 'a' is (4)

Is 'a' less than 10? YES (its 4)
Make 'a' one larger (now 5)
print on-screen what 'a' is (5)

Is 'a' less than 10? YES (its 5)
Make 'a' one larger (now 6)
print on-screen what 'a' is (6)

Is 'a' less than 10? YES (its 6)
Make 'a' one larger (now 7)
print on-screen what 'a' is (7)

Is 'a' less than 10? YES (its the meaning of life)
Make 'a' one larger (now 8)
print on-screen what 'a' is (8)

Is 'a' less than 10? YES (its 8)
Make 'a' one larger (now 9)
print on-screen what 'a' is (9)

Is 'a' less than 10? YES (its 9)
Make 'a' one larger (now 10)
print on-screen what 'a' is (10)

Is 'a' less than 10? NO (its 10, therefore isn't less than 10)
Don-t do the loop
There's no code left to do, so the program ends
So in short, try to think of it that way when you write 'while' loops. This is how you write them, by the way (and a couple of examples:

while {condition that the loop continues}:
{what to do in the loop}
{have it indented, maybe four spaces}
{code that is not looped}
{don't indent this stuff}

#EXAMPLE
#Type this in, see what it does
x = 10
while x != 0:
print x
x = x - 1
print "wow, we've counted x down, and now it equals", x

Remember, to make a program, you open IDLE, click File > New Window, type your program in the new window, then press F5 to run.

What do you type in the area marked {conditions that the loop continues}? The answer is a boolean expression.

WHOA! Big word for the non-math people here. Never mind, boolean expression just means a question that can be answered with a yes or no response. For example, if you wanted to say your age is the same as the person next to you, you would type:

My age == the age of the person next to me

And the statement would be TRUE.
If you were younger than the person opposite, you'd say:

My age < the age of the person opposite me

And the statement would be TRUE.
However, if you were to say the following:

My age > the age of the person opposite me

The statement would be FALSE - the person is actually younger than you.
Here are all of the boolean signs (or operators):

Expression Function
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
!= Not equal to
<> Another way of saying not equal to

Dont get '=' and '==' mixed up - the '=' operator makes what is on the left equal to what is on the right. the '==' operator says whether the thing on the left is the same as what is on the right.

If the result of the boolean question is true, the loop is run.

OK! We've (hopefully) covered 'while' loops. Now let's look at something a little different - conditionals.

Conditionals are where a section of code is only run if certain conditions are met. This is similar to the 'while' loop you just wrote, which only runs when x doesn't equal 0. However, Conditionals are only run once.

The most common conditional in any program language, is the 'if' statement. Here is how it works:

if {conditions to be met}:
{do this}
{and this}
{and this}
{but not this, because it isn't indented}

#EXAMPLE 1
y = 1
if y == 1:
print "y still equals 1, I was just checking"

#EXAMPLE 2
print "We will show the odd numbers up to 20"
n = 1
while n <= 20:
if n % 2 == 0:
print n
n = n + 1
print "there, done."

Example 2 there looks tricky. But all we have done is run an 'if' statement every time the 'while' loop runs. Remember that the % just means the remainder from a division - just checking that there is nothing left over if the number is divided by two - showing it is even. If it is even, it prints what 'n' is.

Finally, there are more ways of doing the 'if' statement. They are 'else' and 'elif'.

'else' simply tells the computer what to do if the conditions of 'if' arent met. For example, the following:

a = 1
if a > 5:
print "That's weird"
else:
print "That's normal"

'a' is not greater than five, therefore what is under 'else' is done.

'elif' is just a shortened way of saying 'else if'. When the 'if' statement fails to be true, 'elif' will do what is under it IF the conditions are met. For example:

z = 4
if z > 70:
print "Something is very wrong"
elif z < 7:
print "This is normal"

The 'if' statement, along with 'else' and 'elif' follow this form:

if {conditions}:
{run this code}
elif {conditions}:
{run this code}
elif {conditions}:
{run this code}
else:
{run this code}

#You can have as many or as little elif statements as you need
#anywhere from zero to the sky.
#You can have at most one else statement
#and only after all other ifs and elifs.

One of the most important points to remember is that you MUST have a colon : at the end of every line with an 'if', 'elif', 'else' or 'while' in it. I forgot that, and as a result a stack of people got stumped at this lesson (sorry ;) ).

One other point is that the code to be executed if the conditions are met, MUST BE INDENTED. That means that if you want to loop the next five lines with a 'while' loop, you must put a set number of spaces at the beginning of each of the next five lines. Here is an example of both of the above points:

a = 10

while a > 0:
print a
if a > 5:
print "Big number!"
elif a % 2 != 0:
print "This is an odd number"
print "It isn't greater than five, either"
else:
print "this number isn't greater than 5"
print "nor is it odd"
print "feeling special?"
a = a - 1
print "we just made 'a' one less than what it was!"
print "and unless a is not greater than 0, we'll do the loop again."
print "well, it seems as if 'a' is now no bigger than 0!"
print "the loop is now over, and without furthur adue, so is this program!"

Notice the three levels of indents there:

1) Each line in the first level starts with no spaces. It is the main program, and will always execute.

2) Each line in the second level starts with four spaces. When there is an 'if' or loop on the first level, everything on the second level after that will be looped/'ifed', until a new line starts back on the first level again.

3) Each line in the third level starts with eight spaces. When there is an 'if' or loop on the second level, everything on the third level after that will be looped/'ifed', until a new line starts back on the second level again.

4) This goes on infinitely, until the person writing the program has an internal brain explosion, and cannot understand anything he/she has written.

There is another loop, called the 'for' loop, but we will cover that in a later lesson.

You'll probably have to ask a lot of questions about this lesson - I don't know how clearly I have written it. Please, if something is unclear, tell me.

And that is lesson 4! In lesson 5, we get into user interaction, and writing programs that actually serve a purpose. Can't wait!

Thanks to all, Gingerbread Man.

Harald
Sep 11, 2004, 02:26 AM
Lesson 4 done.

croxis
Sep 12, 2004, 12:43 AM
I am done too

CivGeneral
Sep 12, 2004, 01:00 AM
Is it to late to join up in this? I have virtualy no knowlage of programing

MSTK
Sep 12, 2004, 01:02 AM
I already knew lesson 3 & 4, and they are self explanitory if you know any programming language at all :(

Oh well. It's still fun :)

CivGeneral
Sep 12, 2004, 01:20 AM
I already knew lesson 3 & 4, and they are self explanitory if you know any programming language at all :(

Oh well. It's still fun :)
I probhibly need help catching up. Place me as still going on Lesson 1 ATM.

CivGeneral
Sep 12, 2004, 01:25 AM
Edit: Apperently I have gotten this thingy to work :wallbash:

I would like to say that I am finished with lessons 1-4. Why am I getting the feeling that this is a review from Algebra class :hmm:

Also, I have been around with basic logics (And, Or, Not, Nor, etc) from electrionics class in High School.

Blackbird_SR-71
Sep 12, 2004, 11:33 AM
okay i had problems with this lesson:

the last two examples i typed them in and pressed F5 and it said there was a synastic (spel?) error. Then i copied both and it gave the same error. can someone help me:confused:. other than that i finished the rest of the lesson.

Trump
Sep 12, 2004, 11:41 AM
I'm getting errors too...

Blackbird - I think that's a syntax error, it's what I'm getting as well.

hurrah for 3 edits. Found what was wrong, you've gotta have a colon after the if condition and the elif/else's.

Blackbird_SR-71
Sep 12, 2004, 02:10 PM
Trump,
yeah its a syntax error. i tried what you said but it still said ivalid syntax. Here is what it typed in:

a = 1
if: a > 5
print "That's weird"
else:
print "That's normal"

EDIT: I found out the problem. I put the colons in the wrong places. This is what I should have typed in:

a = 1
if a > 5:
print "That's weird"
else:
print "That's normal"

Thanks Trump for helping me. :D

Blackbird_SR-71
Sep 12, 2004, 02:14 PM
Now I completed Lesson 4 completely.

Dease
Sep 12, 2004, 02:47 PM
Sign me up :D
I've completed all lessons although I'm a bit fuzzy on "elif" ;)

I have a question though, why wont this work?
z = 4*20
if z-11 > 70:
print "Something is very wrong"
elif z-11 < 7:
print "This is normal"

Harald
Sep 12, 2004, 04:57 PM
z = 4*20
if z-11 > 70:
print "Something is very wrong"
elif z-11 < 7:
print "This is normal"
The above code works as it is writen. Since "z - 11"( z = 4*20 = 80, 80 - 11 = 69) isn't above 70 nor below 7 the program will not print anything.
Though I guess that the "7" in the elif-function is a typo and is supposed to be "70". If corrected, the program works.

Coorae
Sep 12, 2004, 07:34 PM
I am done.

Gingerbread Man
Sep 13, 2004, 01:23 AM
I knew this would be a toughie!

Welcome aboard CivGeneral and Dease! Everybody is welcome to join.

Great to see you guys discussing the lesson - you even figured out the answer to your own question. Yes, you do have to remember those colons at the end of the 'if's.

And thankyou! You just pointed out a stack of typos!

Taé Shala
Sep 14, 2004, 06:49 AM
LESSON 4:
Loops, Loops, Loops, Loops, Loops, Loops, Loops...



Expression Function
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
!= Not equal to
<> Another way of saying not equal to


#EXAMPLE 1
y = 1
if y = 1:
print "y still equals 1, I was just checking"





Seems like you have a typo in the #EXAMPLE 1

I think it must be:

#EXAMPLE 1
y = 1
if y == 1:
print "y still equals 1, I was just checking"



I finished lesson 4. :banana:

Gingerbread Man
Sep 14, 2004, 11:37 PM
Thanks Taé. Will fix.

As of 5 minutes from now, the top thread will be updated.

Blackbird_SR-71
Sep 19, 2004, 09:20 AM
when will the next lesson be just wondering?

Gingerbread Man
Sep 20, 2004, 12:22 AM
when will the next lesson be just wondering?

When I get my yearly exams out of the way. Hopefully I'll have a spare moment between them in the next couple of days.

Gingerbread Man
Sep 22, 2004, 04:39 AM
A new lesson will be up in 30hrs. Finish off this lesson, if you haven't already!

Gingerbread Man
Sep 25, 2004, 05:18 AM
LESSON 5:
Oh, so functional!

Last lesson I said that we would delve into purposefull programming. That involves user input, and user input requires a thing called functions.

What are functions? Well, in effect, functions are little self-contained programs that perform a specific task, which you can incorporate into your own, larger programs. This saves you the time and effort of having to retell the computer what to do every time it does a common task, for example getting the user to type something in.

A function is very simple. You give it some input, and it will become a value, as an output. Don't understand? Here is the general form that a function takes:


function_name(parameters)


See? Easy.
Function_name identifies which function it is you want to use. For example, the function raw_input, which will be the first function that we will use.
Parameters tells the function what to do. for example, if a function multiplied any given number by five, the stuff in parameters tells the function which number it should multiply by five. Put the number 70 into parameters, and the function will do 70 x 5.

Well, that's all well and good that the program can multiply a number by five, but what does it have to show for it? A warm fuzzy feeling? Your program needs to see the results of what happened, to see what 70 x 5 is, or to see if there is a problem somewhere (like you gave it a letter instead of a number). So how does a function show what is does?

Well, in effect, when a computer runs a function, it doesn't actually see the function name, but the result of what the function did. Lets call this program that multiplied any number by five, multiply(). You put the number you want multiplied in the brackets. So if you typed this:

a = multiply(70)

The computer would actually see this:

a = 350

(P.S. don't bother typing in this code).
The function pretty much turned itself into a number, based on what parameters it was given.

Now let's try this with a real function, and see what it does. The function is called raw_input, and asks the user to type in something. It then turns it into a string of text. Try the code below:

# this line makes 'a' equal whatever you type in
a = raw_input("Type in something, and it will be repeated on screen:")

# this line prints what 'a' is now worth
print a


Say in the above program, you typed in 'hello' when it asked you to type something in. To the computer, this program would look like this:

a = "hello"
print "hello"

Remember, a variable is just a stored value. To the computer, the variable 'a' doesn't look like 'a' - it looks like the value that is stored inside it. Functions are similar - to the computer, they look like the value of what they give in return of running.

Lets write another program, that will act as a calculator. This time it will do something more adventerous than what we have done before. There will be a menu, that will ask you whether you want to multiply two numbers together, add two numbers together, divide one number by another, or subtract one number from another. Only problem - the raw_input function only turns what you type in into text - we want the number 1, not the letter 1 (and yes, in python, there is a difference.).

Luckily, somebody wrote the function input, which gives what you typed in, to the program - but this time, it puts it in as a number. If you type an integer, what comes out of input is an integer. And if you put that integer into a variable, the variable will be an integer - type variable, which means you can add and subtract, etc.

Now, lets design this calculator properly. We want a menu that is returned to every time you finish adding, subtracting, etc. In other words, to loop (HINT!!!) while (BIG HINT!!!) you tell it the program should still run.

We want it to do an option in the menu if you type in that number. That involves you typing in a number (a.k.a input) and an if loop.

Lets write it out in understandable English first:

START PROGRAM
print opening message

while we let the program run, do this:
#Print what options you have
print Option 1 - add
print Option 2 - subtract
print Option 3 - multiply
print Option 4 - divide
print Option 5 - quit program

ask for which option is is you want
if it is option 1:
ask for first number
ask for second number
add them together
print the result onscreen
if it is option 2:
ask for first number
ask for second number
subtract one from the other
print the result onscreen
if it is option 3:
ask for first number
ask for second number
multiply!
print the result onscreen
if it is option 4:
ask for first number
ask for second number
divide one by the other
print the result onscreen
if it is option 5:
tell the loop to stop looping

Print onscreen a goodbye message
END PROGRAM


Lets put this in something that python can understand:

#calculator program

#this variable tells the loop whether it should loop or not.
# 1 means loop. anything else means don't loop.

loop = 1

#this variable holds the user's choice in the menu:

choice = 0

while loop == 1:
#print what options you have
print "Welcome to calculator.py"
print "your options are:"
print " "
print "1) Addition"
print "2) Subtraction"
print "3) Multiplication"
print "4) Division"
print "5) Quit calculator.py"
print " "
choice = input("Choose your option: ")
if choice == 1:
add1 = input("Add this: ")
add2 = input("to this: ")
print add1, "+", add2, "=", add1 + add2
elif choice == 2:
sub2 = input("Subtract this: ")
sub1 = input("from this: ")
print sub1, "-", sub2, "=", sub1 - sub2
elif choice == 3:
mul1 = input("Multiply this: ")
mul2 = input("with this: ")
print mul1, "*", mul2, "=", mul1 * mul2
elif choice == 4:
div1 = input("Divide this: ")
div2 = input("by this: ")
print div1, "/", div2, "=", div1 / div2
elif choice == 5:
loop = 0

print "Thankyou for using calculator.py!"

Wow! That is an impressive program! Paste it into python IDLE, save it as 'calculator,py' and run it. Play around with it - try all options, entering in integers (numbers without decimal points), and numbers with stuff after the decimal point (known in programming as a floating point). Try typing in text, and see how the program chucks a minor fit, and stops running. I'll explain that later, if you ask me to.

Well, it is all well and good that you can use other people's functions, but what if you want to write your own functions, to save time, and maybe use them in other programs? This is where the def operator comes in. (An operator is just something that tells python what to do, e.g. the '+' operator tells python to add things, the 'if' operator tells python to do something if conditions are met.)

This is how the 'def' operator works:

def function_name(parameter_1_variable,parameter_2_var iable):
{this is the code in the function}
{more code}
{more code}
return {text, or number to return to the main program}

{this code isn't in the function}
{because it isn't indented}
#remember to put a colon ":" at the end of the line that starts with 'def'

Functions run completely independent of the main program. Remember when I said that when the computer comes to a function, it doesn't see the function, but a value, that the function returns? Here's the quote:
a variable is just a stored value. To the computer, the variable 'a' doesn't look like 'a' - it looks like the value that is stored inside it. Functions are similar - to the computer, they look like the value of what they give in return of running.
So in this sense, functions aren't really cutting and pasting code in a convenient way. It is more like a miniture program that some parameters are given to - it then runs itself, and then returns a value. Your main program sees only the returned value. If that function flew to the moon and back, and then at the end had

return 1

then all your program would see is the number '1', where the name of the function was. It would have no idea what else the program did.

Because it is a seperate program, a function doesn't see any of the variables that are in your main program, and your main program doesn't see any of the variables that are in a function.


For example, here is a function that prints the words "hello" onscreen, and then returns the number '1234' to the main program:

#Below is the function
def hello():
print hello
return 1234

#And here is the function being used
print hello()


Think about the last line of code above. What did it do? Type in the program (you can skip the comments), and see what it does. The output looks like this:

hello
1234
So what happened?
1) When the line 'print hello' was run, the function 'hello' was executed.
2) The function 'hello' printed "hello" onscreen, then returned the number '1234' back to the main program
3) The main program now sees the line as 'print 1234' and as a result, printed '1234'

That accounts for everything that happened. remember, that the main program had NO IDEA that the words "hello" were printed onscreen. All it saw was '1234', and printed that onscreen.

There is one more thing we will cover in this (monsterly huge) lesson - passing parameters to a function. Remember that calculator program. Did it look a bit messy to you? I think it did, so lets re-write it, with functions.

To design - First we will define all the functions we are going to use with the 'def' operator (still remember what an operator is ;) ).
Then we will then have the main program, with all that messy code replaced with nice functions. This will make it so much easier to look at again in the future.


#calculator program

#NO CODE IS REALLY RUN HERE, IT IS ONLY TELLING US WHAT WE WILL DO LATER
#Here we will define our functions
#this prints the main menu, and prompts for a choice
def menu():
#print what options you have
print "Welcome to calculator.py"
print "your options are:"
print " "
print "1) Addition"
print "2) Subtraction"
print "3) Multiplication"
print "4) Division"
print "5) Quit calculator.py"
print " "
return input ("Choose your option: ")

#this adds two numbers given
def add(a,b):
print a, "+", b, "=", a + b

#this subtracts two numbers given
def sub(a,b):
print b, "-", a, "=", b - a

#this multiplies two numbers given
def mul(a,b):
print a, "*", b, "=", a * b

#this divides two numbers given
def div(a,b):
print a, "/", b, "=", a / b

#NOW THE PROGRAM REALLY STARTS, AS CODE IS RUN
loop = 1
choice = 0
while loop == 1:
choice = menu()
if choice == 1:
add(input("Add this: "),input("to this: "))
elif choice == 2:
sub(input("Subtract this: "),input("from this: "))
elif choice == 3:
mul(input("Multiply this: "),input("by this: "))
elif choice == 4:
div(input("Divide this: "),input("by this: "))
elif choice == 5:
loop = 0

print "Thankyou for using calculator.py!"
#NOW THE PROGRAM REALLY FINISHES

The initial program had 34 lines of code. The new one actually had 35 lines of code! It is a little longer, but if you look at it the right way, it is actually simpler.

You defined all your functions at the top. This really isn't part of your main program - they are just lots of little programs, that you will call upon later. You could even re-use these in another program if you needed them, and didn't want to tell the computer how to add and subtract again.

If you look at the main part of the program (between the line 'loop = 1' and 'print "Thankyou for..."'), it is only 15 lines of code. That means that if you wanted to write this program differently, you would only have to write 15 or so lines, as opposed to the 34 lines you would normally have to without functions.

Finally, as a bit of an interlude, I will explain what the line 'add(input("Add this: "),input("to this: "))' means.
I wanted to fit everything onto one line, with as few variables as possible. Remember what functions look like to the main program? Whatever value they return. If the numbers you gave were 2 and 30, the main program would see this:

add(2,30)


The add program would then run. The add program has no 'return' operator - it doesn't return anything to the main program. It simply multiplies two numbers and prints them onscreen, and the main program doesn't see anything of it.

Instead of '(input("Add this: "),input("to this: "))' as the parameters for the add program you could have variables. E.g.

num1 = 45
num2 = 7
add(num1,num2)

You could even put the numbers straight into the function:

add(45,7)

This is because the only thing the function sees are the values that are passed on as parameters. Those values are put into the variables that are mentioned when 'add' is defined (the line 'def add(a,b)' ). The function then uses those parameters to do it's job.

In short:
*) the only thing functions see of the main program is the parameters.
*) the only thing the main program seens of functions is the returned values.

WHOA!!!! WHAT A KILLER LESSON!!! But we got through it, and I made minimal typos. Great!

I haven't decided what will happen in lesson 6. All I can say is I am having a BIG breather, because this lesson took me many hours to write.

Thanks to all,
Gingerbread Man.

Trump
Sep 25, 2004, 08:58 AM
*Hands Gingerbread_Man a box of cookies and an oxygen tank*

Done.

Harald
Sep 27, 2004, 01:54 PM
Done and done.

Really great job Gingerbread Man.

Blackbird_SR-71
Sep 28, 2004, 01:58 PM
Gingerbread Man,

finished

Demetriost
Sep 28, 2004, 02:11 PM
I know , C++, C, some java ,SQL ,a lot of XML and Python basics.
Can i join you?

croxis
Sep 29, 2004, 11:51 AM
done. gbm have you thought of just taking what is used in th epython documentation and just doing minor edits ot make it understabable?

Gingerbread Man
Sep 30, 2004, 05:43 AM
done. gbm have you thought of just taking what is used in th epython documentation and just doing minor edits ot make it understabable?
I'm already doing something along those lines. I've been drawing information from a beginner's guide to python, and re-organising the sections in more complete lessons.

If anybody has any pointers to anything that could do with improvement in the lessons, tell me. That can be anything from a confusing sentence in one of the lessons, to the general structure of my writing - remember, you're getting out what you put in.

I've just gone through a major system re-install (note - installing Fedora three times in two days is a nuisance, to say the least), but hopefully I should find some material for next lesson - hopefully, do lists and arrays, and then move on to some interesting stuff. I'll check out what else we have to learn before straying into graphical stuff, and AI programming. At the moment I'm working on a lesson plan to get us there. Hang tight, and it will turn up 'soon'.

MSTK
Sep 30, 2004, 10:01 PM
forgot all about this topic :lol:

Done.

Coorae
Oct 01, 2004, 11:59 PM
I forgot also...
I am done with lesson 5
thanks

Gingerbread Man
Oct 06, 2004, 07:57 AM
Wow, this place is quiet!

I am in the process of writing the next lesson. Hang tight!

Jon Shafer
Oct 06, 2004, 11:06 PM
I'm up to date.

Thanks for your efforts, GBM, it helps out quite a few people who certainly appreciate your work (even if you're also benefitting from it ;)).

Gingerbread Man
Oct 07, 2004, 01:08 AM
Thanks, Trip. Hopefully it will become a useful tutorial when civIV comes out. I'll probably rewrite the tutorial when it does come out, and host it on my website.

BTW, what would you recommend for the next couple of lessons? At the moment I'm doing tuples, lists and dictionaries. I'll cover the for loop briefly after that, then what? I'm open to any suggestions.

EDIT: Hopefully the next lesson will be up in 24hrs. I think I've finally found a way to present it clearly.

Jon Shafer
Oct 07, 2004, 09:21 AM
I would recommend doing stuff with classes and linking together different files. Then maybe some input stuff (after all, if CIV is going to use Python and XML, there has to be a way for the Python code to read what is stored in the XML).

croxis
Oct 07, 2004, 09:16 PM
well, I wanty to write a python plugin for x-chat which looks at a directory full of different text files, then when someoen types in the name of one of those texts files it will respond with a random quote from that text file. While this has nothing to do with civ it sure would be nice to have ;)

Blackbird_SR-71
Oct 09, 2004, 09:33 AM
I agree with Trip. We should learn how to access files.

Gingerbread Man
Oct 09, 2004, 10:00 PM
LESSON 6:
Tuples, Lists, and Dictionaries

Your brain still hurting from the last lesson? Never worry, this one will require a little less thought. We're going back to something simple - variables - but a little more in depth.

Think about it - variables store one bit of information. They may regurgitate (just not on the carpet...) that information at any point, and their bit of information can be changed at any time Variables are great at what they do - storing a piece of information that may change over time.

But what if you need to store a long list of information, which doesn't change over time? Say, for example, the names of the months of the year.

Or maybe a long list of information, that does change over time? Say, for example, the names of all your cats. You might get new cats, some may die, some may become your dinner (we should trade recipies!).

What about a phone book? For that you need to do a bit of referencing - you would have a list of names, and attached to each of those names, a phone number. How would you do that?

For these three problems, Python uses three different solutions - Tuples, lists, and dictionaries.

Lists are what they seem - a list of values. Each one of them is numbered, starting from zero - the first one is numbered zero, the second 1, the third 2, etc. You can remove values from the list, and add new values to the end. E.g. Your many cats' names.

Tuples are just like lists, but you can't change their values. The values that you give it first up, are the values that you are stuck with for the rest of the program. Again, each value is numbered starting from zero, for easy reference. E.g. the names of the months of the year.

Dictionaries are similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't numbered - they aren't in any specific order, either - the key does the same thing. You can add, remove, and modify the values in dictionaries. E.g. A telephone book.

Well, now we know what they do, lets see how to use them.

TUPLES

Tuples are pretty easy to make. You give your tuple a name, then after that the list of values it will carry. For example, the months of the year:

months = ('January','February','March','April','May','June' ,\
'July','August','September','October','November',' December')

Note that the '\' thingy at the end of the first line carries over that line of code to the next line. It is usefull way of making big lines more readable.

Technically you don't have to put those parentheses there (the '(' and ')' thingies) but it stops python from getting things confused.

You may have spaces after the commas if you feel it necessary - it doesn't really matter.

Python then organises those values in a handy, numbered index - starting from zero, in the order that you entered them in. It would be organised like this:

Index Value
0 January
1 February
2 March
3 April
4 May
5 June
6 July
7 August
8 September
9 October
10 November
11 December

Knowing that, it should be pretty easy to recall values from the tuple. They are just like numbered variables. Here is an example:


#Telling the computer the names of the months:
months = ('January','February','March','April','May','June' ,\
'July','August','September','October','November',' December')

#printing January onscreen:
print months[0]

#printing October:
print months[9]

#create a variable, and put 'August' in it
x = months[7]
print x

#put the months of (southern hemisphere) winter in another variable:
winter = months[5:8]
print winter

And that is tuples! Really easy...

LISTS

Lists are extremely similar to tuples. Lists are modifiable (or 'mutable', as a programmer may say), so their values can be changed. Most of the time we use lists, not tuples.

Lists are defined very similarly to tuples. Say you have FIVE cats, called Tom, Snappy, Kitty, Jessie and Chester. To put them in a list, you would do this:

cats = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester']

As you see, the code is exactly the same as a tuple, EXCEPT that all the values are put between square brackets, not parentheses. Again, you don't have to have spaces after the comma.

You recall values from lists exactly the same as you do with tuples. For example, to print the name of your 3rd cat you would do this:

print cats[2]

You can also recall a range of examples, like above, for example - cats[0:2] would recall your 1st and 2nd cats.

Where lists come into their own is how they can be modified. To add a value to a list, you use the 'append()' function. Let's say you got a new cat called Catherine. To add her to the list you'd do this:

cats.append('Catherine')

That's a little weird, isn't it? I'll explain. That function is in a funny spot - after a period (the '.' kind of period, not otherwise), after the list name. You'll get to see those things more in a later lesson. For the meanwhile, this is the form of the function that adds a new value to a list:

#add a new value to the end of a list:
list_name.append(value-to-add)

#e.g. to add the number 5038 to the list 'numbers':
numbers.append(5038)

Clears things up? Good!

Now to a sad situation - Snappy was shot by a neighbour, and eaten for their dinner (good on 'em!). You need to remove him (or her) from the list. Removing that sorry cat is an easy task, thankfully, so you have to wallow in sadness for as short a time as possible:

#Remove your 2nd cat, Snappy. Woe is you.
del cats[1]

You've just removed the 2nd cat in your list - poor old Snappy.

And with that morbid message, lets move on to...

DICTIONARIES

Ok, so there is more to life than the names of your cats. You need to call your sister, mother, son, the fruit man, and anyone else who needs to know that their favourite cat is dead. For that you need a telephone book.

Now, the lists we've used above aren't really suitable for a telephone book. You need to know a number based on someone's name - not the other way around. In the examples of months and cats, we gave the computer a number, and it gave us a name. This time we want to give the computer a name, and it give us a number. For this we need Dictionaries.

So how do we make a dictionary? Put away your binding equipment, it isn't that advanced.

Remember, dictionaries have keys, and values. In a phone book, you have people's names, then their numbers. See a similarity?

When you initially create a dictionary, it is very much like making a tuple or list. Tuples have ( and ) things, lists have [ and ] things. Guess what! dictionaries have { and } things - curly braces. Here is an example below, showing a dictionary with four phone numbers in it:

#Make the phone book:
phonebook = {'Andrew Parson':8806336, 'Emily Everett':6784346, 'Peter Power':7658344, 'Lewis Lame':1122345}

#Print out Lewis Lame's number:
print phonebook['Lewis Lame']

the program would then print Lewis Lame's number onscreen. Notice how instead of identifying the value by a number, like in the cats and months examples, we identify the value, using another value - in this case the person's name.

Ok, you've created a new phone book. Now you want to add new numbers to the book. What do you do? A very simple line of code:

#Add the person 'Gingerbread Man' to the phonebook:
phonebook['Gingerbread Man'] = 1234567
#(Didn't think I would give you my real number now, would I?)

All that line is saying is that there is a person called Gingerbread Man in the phone book, and his number is 1234567. In other words - the key is 'Gingerbread Man', and the value is 1234567.

You delete entries in a dictionary just like in a list. Let's say Andrew Parson is your neighbour, and shot your cat. You never want to talk to him again, and therefore don't need his number. Just like in any other list, you'd do this:

del phonebook['Andrew Parson']

Again, very easy.

remember that append function that we used with the list? Well, there are quite a few of those that can be used with dictionaries. Below, I will write you a program, and it will incorporate some of those functions in. It will have comments along the way explaining what it does.

Type this program into Python IDLE (you can skip the comments). Experiment as much as you like with it. Type it where you see the lines beginning with >>>

#A few examples of a dictionary

#First we define the dictionary
#it will have nothing in it this time
ages = {}

#Add a couple of names to the dictionary
ages['Sue'] = 23
ages['Peter'] = 19
ages['Andrew'] = 78
ages['Karren'] = 45

#Use the function has_key() -
#This function takes this form:
#function_name.has_key(key-name)
#It returns TRUE if the dictionary has key-name in it
#but returns FALSE if it doesn't
#remember - this is how 'if' statements work - they run if something is true
#and they don't when something is false.
if ages.has_key('Sue'):
print "Sue is in the dictionary. She is", ages['Sue'], "years old"
else:
print "Sue is not in the dictionary"

#Use the function keys() -
#This function returns a list of all the names of the keys.
#E.g.
print "The following people are in the dictionary:"
print ages.keys()

#You could use this function to put all the key names in a list:
keys = ages.keys()

#You can also get a list of all the values in a dictionary.
#You use the values() function:
print "People are aged the following:", ages.values()

#Put it in a list:
values = ages.values()

#You can sort lists, with the sort() function
#It will sort all values in a list alphabetically, numerically, etc...
#You can't sort dictionaries - they are in no particular order
print keys
keys.sort()
print keys

print values
values.sort()
print values

#You can find the number of entries with the len() function:
print "The dictionary has", len(ages), "entries in it"

There are many other functions you can use to work with lists and dictionaries - too many to go through right now. We'll leave the lesson at this point - you have learnt enough for one lesson.

I'll post a lesson plan briefly. Please comment on it when it appears.
Thanks to all,
Gingerbread Man.

Jon Shafer
Oct 09, 2004, 10:07 PM
Done, thanks again for your work GBM. :)

When you delete an element from a list or a dictionary, it bumps all the elements which follow it back one, right? I forget. :)

Gingerbread Man
Oct 09, 2004, 10:08 PM
LESSON PLAN:
Next lesson we will learn a few extra things about lists, the 'for' loop, and then make some programs based on everything we've learnt so far.

After that, we learn classes. That lesson will take a while to write - classes are a difficult learning curve.

Then - file I/O. This is a very useful topic to learn.

A good way to learn how to make a computer respond to input, is to write scripts for chat programs. In the lesson/s following file I/O, we will learn how to make IRC scripts that will respond to what chatters say - auto-banning scripts, random quotes ;), possibly auto-reply scripts and whatever else you can think about.

Then, maybe for some interest, we will make some text adventure games ("You are on the porch of a large mansion. You can hear cars behind you. The door is of solid Mahoghany, with a brass knob. Grass is growing in between cracks in the porch." ;) )

I don't know if it would be possible to incorporate AI into a text adventure game, but we may as well try in the lessons following that. And by this point, you will be writing the programs on your own - I won't be giving them to you.

Hopefully by this time there will be a bit more info on civIV. We should do some more targeted learning at that time.

Jon Shafer
Oct 09, 2004, 10:11 PM
I definitely think that classes and constructors are two very important concepts to cover, probably the most important for large projects (which CIV's scripting will no doubt be). Mastering those is vital to understanding and changing already existing code.

Gingerbread Man
Oct 09, 2004, 10:19 PM
When you delete an element from a list or a dictionary, it bumps all the elements which follow it back one, right? I forget. :)
For lists - yes

For dictionaries - since the elements aren't numbered, they don't really move anywhere. When you use the .values() and .keys() functions, I have a feeling that they give out the elements in the order that they were entered in.

Jon Shafer
Oct 09, 2004, 11:50 PM
Err, right, yeah, I meant lists, not dictionaries... :crazyeye:

croxis
Oct 11, 2004, 04:46 PM
Finished! Yay is me and stuff

Harald
Oct 13, 2004, 03:45 AM
Finished with lesson 06.

Jon Shafer
Oct 13, 2004, 09:14 AM
Guess I should mention I've done it to. :D

Blackbird_SR-71
Oct 13, 2004, 07:01 PM
done too. good lesson like always GBM.

Blackbird_SR-71
Oct 17, 2004, 09:14 AM
this place is so quiet................ to quiet...............

Gingerbread Man
Oct 18, 2004, 12:15 AM
Never worry, I'm working on the next lesson.

I'm not too worried if this place gets quiet. If you look at the thread details, you'll see that there are quite a few lurkers looking at this thread.

Plus, when I'm closer to finishing it, it may get stickied :D

croxis
Oct 20, 2004, 06:41 PM
actually I think you should make a pdf document out of it. You are writing a great python tutorial and I think the beginning coding community as a whole could benifit from it

Gingerbread Man
Oct 21, 2004, 06:43 AM
Guess what! another excuse for not posting another lesson! My monitor has gone haywire, and is now a clunky migrane machine!

It'll be a couple of days before I'm up (and recovered) again...

Gingerbread Man
Oct 25, 2004, 05:28 AM
LESSON 7
The 'for' loop, and some programs of your own

Well, in the first lesson about loops, I said I would put off teaching you the 'for' loop, until we had reached lists. Now, I could have taught you lists before I taught you loops, but I guess that is something for the 2nd revision ;).

Basically, the 'for' loop does something for every value in a list. The way it is set out is a little confusing, but otherwise is very basic. Here is an example of it in code:

#A 'for' loop:
list = [45, 'eat me', 90210, 'The day has come, the walrus said, \
to speak of many things', -67]

#create a loop:
#Goes through list, and seqentially puts each bit of information
#into the variable value, and runs the loop
for value in list:
print value


As you see, when the loop executes, it runs through all of the values in the list after 'in'. It then puts them into value, and executes through the loop, each time with value being worth something different. Let's see it a again, in a classic cheerleading call that we all know:

#cheerleading program
word = raw_input("Who do you go for? ")

for letter in word:
call = "Gimme a " + letter + "!"
print call
print letter + "!"

print "What does that spell?"
print word + "!"

As you see, strings (remember - strings are lines of text) are just lists with lots of characters.
The program went through each of the letters (or values) in word, and it printed them onscreen. And that is the 'for' loop.

Now to the business end of the lesson. Lets start writing programs. So far we have learnt variables, lists, loops, and functions. That is pretty much all we need for quite a bit of programming. So let's set ourselves a task.

But before that, we need to figure out some pieces of code that we will use a lot. What I'm thinking, is a menu. So, using our knowledge of lists, functions and input, let's write a function that acts as a menu. Here it is, have a GOOD look at it (remember - you don't have to type in the comments - the computer doesn't see them anyway.


#THE MENU FUNCTION
#The program asks for a string with all the menu options in it,
#and a text string asking a question.
#make sure every menu entry is unique.

def menu(list, question):
for entry in list:
print 1 + list.index(entry),
print ") " + entry

return input(question) - 1

#def menu(list, question): is telling the function to
#ask for two bits of information:
#A list of all the menu entries,
#and the question it will ask when all the options have been printed

#for entry in list: is pretty much saying;
#'for every entry in the list, do the following:'

#print list.index(entry) + 1 uses the .index() function to find
#where in the list the entry is in. print function then prints it
#it adds 1 to make the numbers more intelligable.

#print ") " + entry prints a bracket, and then the entry name

#after the for loop is finished, input(question) - 1 asks the question,
#and returns the value to the main program (minus 1, to turn it back to
#the number the computer will understand).


That wasn't very difficult, was it? the actual program only took up five lines - this is the wonder of how much we have learnt so far! All my comments take up sixteen lines - more than three times the program length. Not that daunting after all. We'll see it used in our first example program.

What will our first example program be? How about a (very) simple text adventure game? Sounds like fun! It will only encompass one room of a house, and will be extremely simple. There will be five things, and a door. In one of the five things, is a key to the door. You need to find the key, then open the door. I will give a plain-english version first, then do it in python:


#Plain-english version of our 'game'

Tell the computer about our menu function

Print a welcoming message, showing a description of the room.
We will give the player six things to look at: pot plant, painting,\
vase, lampshade, shoe, and the door

Tell the computer that the door is locked
Tell the computer where the key is

present a menu, telling you what things you can 'operate':
It will give you the six options
It will ask the question "what will you look at?"

if the user wanted to look at:
pot plant:
If the key is here, give the player the key
otherwise, tell them it isn't here
painting:
same as above
<snip>
door:
If the player has the key, let them open the door
Otherwise, tell them to look harder

Give the player a well done message, for completing the game.


From this, we can write a real program. Ready? Here it is (skip typing the comments):

#TEXT ADVENTURE GAME

#the menu function:
def menu(list, question):
for entry in list:
print 1 + list.index(entry),
print ") " + entry

return input(question) - 1

#Give the computer some basic information about the room:
items = ["pot plant","painting","vase","lampshade","shoe","door"]

#The key is in the vase (or entry number 2 in the list above):
keylocation = 2

#You haven't found the key:
keyfound = 0

loop = 1

#Give some introductory text:
print "Last night you went to sleep in the comfort of your own home."
print "Now, you find yourself locked in a room. You don't know how"
print "you got there, or what time it is. In the room you can see"
print len(items), "things:"
for x in items:
print x
print ""
print "The door is locked. Could there be a key somewhere?"
#Get your menu working, and the program running until you find the key:
while loop == 1:
choice = menu(items,"What do you want to inspect? ")
if choice == 0:
if choice == keylocation:
print "You found a small key in the pot plant."
print ""
keyfound = 1
else:
print "You found nothing in the pot plant."
print ""
elif choice == 1:
if choice == keylocation:
print "You found a small key behind the painting."
print ""
keyfound = 1
else:
print "You found nothing behind the painting."
print ""
elif choice == 2:
if choice == keylocation:
print "You found a small key in the vase."
print ""
keyfound = 1
else:
print "You found nothing in the vase."
print ""
elif choice == 3:
if choice == keylocation:
print "You found a small key in the lampshade."
print ""
keyfound = 1
else:
print "You found nothing in the lampshade."
print ""
elif choice == 4:
if choice == keylocation:
print "You found a small key in the shoe."
print ""
keyfound = 1
else:
print "You found nothing in the shoe."
print ""
elif choice == 5:
if keyfound == 1:
loop = 0
print "You put in the key, turn it, and hear a click"
print ""
else:
print "The door is locked, you need to find a key."
print ""

print "Light floods into the room as you open the door to your freedom."


Well, a very simple, but fun, game. Soon you'll make your own, and you can make it as simple (or as complex) as you like. I'll post quite a few, later.

The fist question you should ask is "does this program work?". The answer here is yes. Then you should ask "does this program work well?" - not quite. The menu() function is great - it reduces a lot of typing. The 'while' loop that we have, however, is a little messy - four lines of indents, for a simple program. We can do better!

Now, this will become much MUCH more straightforward when we introduce classes. But that will have to wait. Until then, let's make a function that reduces our mess. It we will pass two things to it - the menu choice we made, and the location of the key. It will return one thing - whether or not the key has been found. Lets see it:

def inspect(choice,location):
if choice == location:
print ""
print "You found a key!"
print ""
return 1
else:
print ""
print "Nothing of interest here."
print ""
return 0


Now the main program can be a little simpler. Let's take it from the while loop, and change things around:


while loop == 1:
keyfound = inspect(menu(items,"What do you want to inspect? "),keylocation)
if keyfound == 1:
print "You put the key in the lock of the door, and turn it. It opens!"
loop = 0

print "Light floods into the room, as you open the door to your freedom."


Now the program becomes massively shorter - from a cumbersome 83 lines, to a very shapely 50 lines! Of course, you lose quite a bit of versatility - all the items in the room do the same thing. You automatically open the door when you find the key. The game becomes a little less interesting. It also becomes a little harder to change.

Now I said you would write some programs now. Here is your chance! Your task, if you chose to accept it, is to post a better text adventure game. When you are finished, post them here (in a .txt file - the forums don't let you post python files). You can use any of the code I have given you here. Remember to check back on previous lessons we have done - they are priceless tools. Do a search for some simple text adventure games - if you find some nice, fun (and clean) text adventure games, post a link here - some of us have never ventured that far back into gaming history, and need education.

You can ask me absolutely any question you like of me - I am willing to help, even if that means looking an answer - or finding someone who knows the answer ;). I'll be writing some very documented text adventure games myself - I'll post them here, and maybe teach you a thing or two.

Thanks to all,
Gingerbread Man.

Gingerbread Man
Oct 26, 2004, 06:49 AM
Painfully quiet...

nonetheless, I am writing my game, it would be a real shame not to see any others trying.

Remember, I'm ready to help!

EDIT - over the next few days, I'll be posting pieces of code to help you along. You can use them as sparsely or as often as you wish.

Jon Shafer
Oct 26, 2004, 09:17 AM
I'm here. :D

Haven't had time to go over it yet, but I will soon enough.

Jon Shafer
Oct 26, 2004, 11:38 PM
Gone over it, another great one GBM, keep up the good work. :)

Not sure I have time to write my own game, but I think I have enough of a grasp of programming that I've done similar things in the past.

Classes are next. :D

Gingerbread Man
Oct 29, 2004, 07:43 AM
This seems to be the lesson with the least response. What goes?

Am I leaving you guys too much do do, and not enough knowledge to do it?
Please, this tutorial will only be good if you put in some feedback. I am completely happy with restructuring entire lessons, if that is what it takes.

Blackbird_SR-71
Oct 29, 2004, 05:10 PM
hello Gingerbread Man,

I finished the lesson and the loops are confusing but i'll try to get it........

as for the game i'll try but until i really understand this don't count on me.....

anyways good lesson

Gingerbread Man
Oct 29, 2004, 09:52 PM
Hmm, well maybe I set something too hard this time.

By all means, give it a go if you can, but I won't be holding anyone to it.

Gingerbread Man
Oct 30, 2004, 05:02 AM
I made a text adventure game! However, I did read ahead a little - I put dictionaries inside dictionaries, which I never said you could do, and I did a bit of error handling. Here is the source code, and attached is the file it is stored in:

#THE BOX
#Python program by Steven Thurlow
#Property of the Civfanatics.com forums

#The menu function
#make sure every menu entry is unique otherwise it
#will show the index of the first entry it appears in
def menu(list, question):
for entry in list:
print list.index(entry) + 1,
print ") " + entry
return input(question) - 1

#The input processing function
def command(input):
output = []
print ""
text = raw_input(input + " ") + " "
space = 0
letter = 0
count = 0
while count < len(text):
if text[count] == " ":
output.append(text[space:count])
space = count + 1
count = count + 1
end = output[0]
del output[0]
output.append(end)
return output

#Define default actions
actions = ['touch','listen','look','smell','taste','use','tak e','goto', 'leave', 'exit']

#Define the objects in the room
objects = {}

#The space's touch
objects['touch'] = \
"In the confined space you find YOURSELF. You feel a cold \n\
metal ROOF, a rickety FLOOR, a FRONT section, a BACK\n\
section, and two SIDES."

#The space's listen
objects['listen'] = \
"You hear a rumble towards the front of your confines, but it sounds\n\
distant, so you cannot learn much from it."

#The space's look
objects['look'] = \
"you can see absolutely nothing - it is pitch black. You need a \n\
source of light"

#The space's smell
objects['smell'] = \
"You can smell nothing but YOURSELF."

#The space's taste
objects['taste'] = \
"A myriad of disgusting flavours are found throughout your confines."

#Quit the game
objects['exit'] = \
"You quit the game while still stuck in the confines you found yourself in."

#yourself
objects['yourself'] = {}
objects['yourself']['touch'] = \
"You are (quite obviously) a man. You are also slightly obese."
objects['yourself']['listen'] = \
"Normal bodily functions are still occuring."
objects['yourself']['look'] = \
"You cannot see yourself."
objects['yourself']['smell'] = \
"You reek of ALCOHOL"
objects['yourself']['taste'] = \
"You taste like ALCOHOL, with a smidge of jam, with a creamy texture.\n\
You want more."

#alcohol
objects['yourself']['alcohol'] = {}
objects['yourself']['alcohol']['touch'] = \
"Your shirt appears to be soaked in the alcohol"
objects['yourself']['alcohol']['listen'] = \
"Sounds like alcohol, as usual"
objects['yourself']['alcohol']['look'] = \
"Remember? You cant see yet!"
objects['yourself']['alcohol']['smell'] = \
"The sweet aromas of a 1997 vintage, dry sparkling wine, probably \n\
grown organically in the Barossa Valley, reminds you of many fine \n\
days ago."
objects['yourself']['alcohol']['taste'] = \
"It wets your dry mouth with the flavours that it's smell suggests."

#roof
objects['roof'] = {}
objects['roof']['touch'] = \
"The roof is of cold metal, with a spot of RUST."
objects['roof']['listen'] = \
"The roof seems to be rattling&qu