OpenRPG Plugin HQ

Contact me: aim | icq | yahoo im | e-mail (remove SPAMISBAD)

//pyguide/Variable Types: Ints and Strings

You are viewing Chapter 1.3: Variable Types: Ints and Strings of the Guide to Learning Python for OpenRPG. You can also go to the table of contents to see the full list of available chapters.

Non-programmers: I've alrealy mentioned something of the difference between strings and integers (ints). Strings are a type of variable which contains a word or phrase, essentially a list of characters. Conversely, ints are numbers. If you ever receive a TypeError message, it likely means that you were mixing up two different types of variables. Some things can be done with strings which can't be done with numbers, and vice versa; there are also some things you can do to both. In other programming languages, you may need to declare your variables before you use them - that is, to state what the name of a variable is and what type of variable it is - but in Python no such thing is necessary. It simply figures out what type of variable you're creating when you first assign a value to it.

Like any programming language, Python automatically simplifies any math phrases it finds, and these math phrases can contain ints or strings. Thus, if you were to open up a Python interpreter and type:

>>> (1 + 5 - 6) * (8 / 2)

It would print out the result, in this case, 0. You can also simplify string statements:

>>> "My name is"+"mDuo13."

And it would print out the result of adding the two strings together, sometimes called concatenating them. However, in this case, there is a small mistake - the result is "My name ismDuo13", because there is no space at the end of "My name is" nor is there one at the beginning of "mDuo13". Be careful not to make this mistake when programming, or you might end up with ugly printouts. ;)

It is of note that in Python, a string can be denoted with a double-quote mark, like this: ", or a single quote mark: '. The double quote mark is made by holding down SHIFT and pressing the key to the left of ENTER on a standard US keyboard. The single quote key is made by simply pressing the same key without SHIFT held. If you start a string with a single-quote (also known as an apostrophe), you will be able to use double-quote marks in your string, like so: 'My name is "mDuo13," he said.' The reverse is also true.

Now, a problem arises if you try to include a line break in your string - you can't simply press ENTER and continue on the next line. You must instead use "\n". This is called a newline character, and when printed it appears like an actual linebreak. The backslash \ cannot be used in a string by itself, because it is used to introduce special characters like the newline character. You can also make a tab character, with "\t", or print single or double quotes regardless of which you used to introduce the string, like "I said, \"Okay!\" when you asked the first time." An actual backslash can be printed by typing two of them, like so: "The backslash, or \\ character, is cool!". The process of using a backslash to put something special in a string is called escaping, and the set of characters, such as "\n", used to create the special thing is called an escape sequence.

Now, back to the difference between ints and strings. You cannot mix the two together; if you try to add a string to an int, you'll get an error, like so:

>>> "Five: "+5
TypeError: cannot concatenate 'str' and 'int' objects.

The 'str' type refers to a string, the "Five: " string in particular, and the 'int' refers to the integer 5. The error says that they can't be concatenated - and if you remember from before, concatenating is putting strings together. So, it's saying that we can't add integers and strings together.

We can, however, turn the 5 into a string so that we can add the two together. We do this using the str() function, like so:

>>> "Five: "+str(5)
Five: 5

See? Wasn't that easy? The str(5) is simplified to be "5", and then is added to "Five: ". We can convert the other way, also, though not all things can become ints. For example:

>>> int("512")
>>> int("your mom")
ValueError: invalid literal for int(): your mom

Thus, you should be careful what you int(), because you might come up with some kind of error.

Now, let's get to actually creating some variables. If you're not sure on this, go back and read the For the First-time Programmer section. In Python, you need not declare your variables, but simply assign a value to them - Python will figure out what type of variable you are using when you do so. Python variable names can be any combination of letters, numbers, and underscores _, but may not start with numbers. As far as I've seen, there is no limit to the length of a variable name, but since you generally have to type variable names a lot, it's better to keep them short. Variable names are also case-sensitive, so ThIs_VaR is not the same as tHiS_vAr. The following names are legal variable names in Python:


Yes, even the triple-underscore variable works, believe it or not. However, it's important to note that starting a variable name with two underscores has a special meaning. You probably won't encounter it for a while, but you're better off getting into the habit of not doing so. Anyway, the following variable names are not legal in Python:

johns variable

You can input variables via two methods - input() and raw_input(). The input() statement takes the inputs as an int, and raw_input() takes the input as a string. Both of them have an optional argument (which goes into the parentheses, non-programmers) which is the prompt displayed next to the input. Open up your preferred text editor, or a new program edit window in IDLE, and put in the following program, which calculates ability bonuses for the d20 system. The red sections are comments. Comments in Python are set off with the character #; and continue until the end of the line.

Non-Programmers: Comments are a special tool for programmers. Simply put, anything that is in a commentted-out section of code is ignored by the computer. That means that comments can be pretty much anything. Common uses for comments include putting in text that describes how a particular line or section works, setting different sections of code apart from each other, setting certain lines to temporarily not work for testing purposes, and turning off certain sections of code while leaving them actually THERE for posterity/security/curiousity/whatever. You do not need to type them into the program, but you can if you want. Note how each new comment line needs a new # symbol to comment it out.

name = raw_input("What is your name? ")#the raw_input() command asks the user for input,
                                       #returns their name as a string,
                                       #then stores it to the variable "name"

strength = input("What is your strength? ")#the input() command takes user input and returns it
                                           #as an int. One thing to beware of with input() is
                                           #that if the user types in something that is not a
                                           #valid int, it will cause an error. I will teach you
                                           #how to avoid this problem later.
strengthmod = ( strength - 10 ) / 2#this performs some simple math - it takes the strength,
                                   #subtracts ten, then divides by two. The parentheses are
                                   #there to make sure that nothing goes wrong, such as dividing
                                   #10 by two and then subtracting that (5) from the strength.
dexterity = input("What is your dexterity? ")#this does the same as above, for dex
dexteritymod = ( dexterity - 10 ) / 2#and again, same as above
constitution = input("What is your constitution? ")
constitutionmod = ( constitution - 10 ) / 2
intelligence = input("What is your intelligence? ")
intelligencemod = ( intelligence - 10 ) / 2
wisdom = input("What is your wisdom? ")
wisdommod = ( wisdom - 10 ) / 2
charisma = input("What is your charisma? ")
charismamod = ( charisma - 10 ) / 2
print "----------"#this is here so that it will separate the input prompts from the output here
print name+"'s stats:"#this displays the name and "'s stats". Because the two strings are added,
                      #they are concatenated and no space appears between them as it would if
                      #you had typed name, "'s stats"
print "Strength:", strength, "\t Bonus:", strengthmod#this is self-explanatory except for the
                                                     #\t, which is a special combination that
                                                     #displays a TAB character.
print "Dexterity:", dexterity, "\t Bonus:", dexteritymod
print "Constitution:", constitution, "\t Bonus:", constitutionmod
print "Intelligence:", intelligence, "\t Bonus:", intelligencemod
print "Wisdom:", wisdom, "\t Bonus:", wisdommod
print "Charisma:", charisma, "\t Bonus:", charismamod
raw_input()#this is a special trick of mine - it's not really smart, but it works. See, normally
           #the program would exit immediatelly, but this stops and has it wait for user input.
           #If the user just presses enter, there will be an error saying that there was no
           #input, but that's no big deal, because the program is done anyway. It's sloppy
           #programming, but it's easier than finding or writing some kind of pause command.

As you may have figured out, the program figures out your stat bonuses for the d20 system and displays them. It's not really necessary, nor is it complicated, but it's an RPG-based example so I figured you guys could relate to it. I think the comments above should really explain it well enough that I don't really have to go over it again here. If you do have any questions or comments, don't refrain from using the Python Guide Forum.

The OpenRPG Plugin HQ by mDuo13
OpenRPG Webring Image [ Prev | Skip Prev | Prev 5 | List | Stats
Join | Rand | Next 5 | Skip Next | Next ]