Author Topic: SotK's Python Tutorials - Part 2: Variables, Data Types, Conditional Statements  (Read 8102 times)

Son of the King

  • Megas Domestikos
    Voting Member
  • Posts: 3368
  • Karma: 29
  • Awards Awarded for outstanding services to Exilian!
    • View Profile
    • SotK
    • Awards
SotK's Python Tutorials
Part 2: Variables, Data Types and Conditional Statements



More On Variables and Data Types:
 
In the last section, we learnt about how you can use variables to represent whole numbers, fractional numbers and True/False values. There are many other data types and structures that can be stored as variables. In Python, these include the following:

  • Integers
  • Floating Point Numbers (Floats)
  • Booleans
  • Strings
  • Lists
  • Tuples
  • Dictionaries

Lists, Tuples and Dictionaries will be covered later, so for now lets talk about the basics of strings.

Note: Variable names can be anything, except keywords such as True, False or If. In Python, function and variable names are not protected, so be careful you don't accidentally name a variable the same as a function.
 


Strings:
 
Strings are simply sequences of characters. In many programming languages, a character is a separate data type and a string is effectively an array/list of these. In Python, a character is simply stored as a string of length 1. To set a variable to be a string, use the same syntax as when assigning numerical values etc. to variables. The string itself must be enclosed in quotation marks ( ' or " ).

Code: (Strings) [Select]
>>> myString = 'Hello World'
>>> myString
'Hello World'

If the quotes aren't included then an exception/error will be raised. In Python, either single quotes or double quotes can be used to enclose strings. However, if there is a quotation mark of the same type as you chose to enclose the string then the string will be seen to finish where the second quotation mark is, rather than the actual end. This will cause errors.

Code: (Quotation Mark Examples) [Select]
>>> a = 'It's a beautiful day.'
SyntaxError: invalid syntax
>>> a = "It's a beautiful day."

The first attempt at making the string fails because the computer only sees 'It' as the string, and does not know how to deal with the rest of it. The second attempt works because the single quote/apostrophe doesn't close the double quotes that enclose the string.

Pressing return midway through a standard string will also cause an error, because the computer will think that it has reached the end of a line of code and won't find the closing quote of the string, causing a exception. This can be avoided by either using the newline character \n or using triple quotes to enclose the string:

Code: (Newline in Python Strings) [Select]
>>> a = 'test\ntest'
>>> print(a)
test
test
>>> b = """test
test"""
>>> print(b)
test
test

The second method (triple quotes) also allows you to use the same type of quotation mark in the string as is used to enclose it, and so is useful if you need a string with both types of quotation marks in.

Note the lines print(a) and print(b) in the previous example. These are examples of the function print being called, with a and b the parameters used. The print simply displays whatever parameters you pass to it on the console, so print(a) told the computer to display 'test\ntest.
 


Writing a Program:
 
You have probably realised by now that Python doesn't work just using the Python Shell/Interpreter to enter lines of code each time you want to run them. This would be tedious for even tiny programs, and for anything else its practically impossible, not to mention a waste of time. Its time to write your first Python program.

Assuming you are running IDLE, click File-->New Window. Otherwise open up a text editor. Once the new window appears, you can begin writing your program. To start with, we will write one of the most basic programs you can write in Python. Type the following and hit save (if using a text editor, then save it with the extension .py).

Code: (Hello World) [Select]
print('Hello World')
Once you have saved the code, try running it. To do this in IDLE, click Run-->Run Module or just hit F5. If you aren't using IDLE, then use the command prompt/terminal/whatever to navigate to the location of your program and run it using Python (probably something like python <program name> assuming your environment variables are set up correctly). In IDLE, the Python Shell window will refresh itself, then Hello World should be displayed.

Congratulations, you have just written your first program!
 


Conditional Statements:
 
Now its time to flesh your program out a little. We are going to use a conditional (IF) statement to let your program make a choice.

Code: (Conditional Hello World!) [Select]
name = input('Enter your name: ')
if name == 'SotK':
    print('Hello World!')
else:
    print('Hello ', name)

There is a lot of new stuff in here, so I'll start from the top. The first line simply assigns the result of the function input() (more on this in the next section) to a variable called name. The next line then checks if the variable name is the same as 'SotK' ( = is an assignment operator, whereas == is for checking for equality between two things). The condition name == 'SotK' will evaluate to either True or False. If it is True, then the code immediately below the if <condition>: line is executed. If the condition evaluates to False, then the program skips forward to the next part of the conditional statement. In this case, that is the else: line, however you can have as many different conditions in the same if statement using elif <condition>: between the if and the else. The else: line tells the program that it has run out of conditions to check against, and so it should just do what is on the next lines.

Notice that the code underneath the if and else lines is indented. This is of vital importance in Python, since indentation is used to work out when to run code. In general:

Code: (Conditional Statement) [Select]
if <condition>:
    ...
    ...
elif <condition>:
    ...
    ...
else:
    ...
    ...
...
...



And that is the basics of strings and conditional statements. The next section will introduce you to loops, and also talk about a few basic functions included in Python's standard library (like print() and input()). Iterable data structures such as lists and tuples will also be explained, as well as more detail on strings in Python.

<-- Part 1: Introduction, Basic Maths and Variables
--> Part 3: Strings and Loops
« Last Edit: June 28, 2011, 11:21:25 PM by Son of the King »

debux

  • RTW Modders and Tutorialists
    Voting Member
  • Posts: 2521
  • Karma: 11
    • View Profile
    • Awards
I wish I could understand, but you've just gotten 20 points closer to your Triumph! :D
(\__/)
(='.'=) This is Bunny. Copy and paste bunny into your
(")_(") signature to help him gain world domination


START ANSWERING PHOENIXGUARD! POST AS MUCH AS YE DID IN YE OLD DAYS :D

Son of the King

  • Megas Domestikos
    Voting Member
  • Posts: 3368
  • Karma: 29
  • Awards Awarded for outstanding services to Exilian!
    • View Profile
    • SotK
    • Awards
Lol which bit is hard to understand?

Marcus

  • Devourer of Souls
  • Megas Domestikos
    Voting Member
  • Posts: 1667
  • Karma: 10
  • I think, therefore I am.
    • View Profile
    • http://exilian.co.uk/
    • Awards
Good work SotK, it really is quite easy to understand. ;)
"So if you meet me, have some courtesy, have some sympathy, and some taste. Use all your well learned politesse, or I'll lay your soul to waste."

debux

  • RTW Modders and Tutorialists
    Voting Member
  • Posts: 2521
  • Karma: 11
    • View Profile
    • Awards
Lol which bit is hard to understand?

I don't code, that's what :D
(\__/)
(='.'=) This is Bunny. Copy and paste bunny into your
(")_(") signature to help him gain world domination


START ANSWERING PHOENIXGUARD! POST AS MUCH AS YE DID IN YE OLD DAYS :D