Biteresources.com



Python reference

Reference Page

Contents

Introduction 2

Output to the screen 3

Taking input from the user 5

Variable 7

Data type 10

MC tutorial 20

Introduction

This document is going to cover most of the things you will need to know about Python for the A453 controlled assessment and for your exam. I have broken the information down into sections so that it is easier to search it and it looks more organised (if you disagree, do say).

I am hoping that you will use this as a reference guide when you are trying to do something and you have forgotten the syntax or you are getting some kind of error on the screen and you are not sure why it is doing that. I would like to say that Google is your tool and Stack Overflow is your friend. Use them wisely and you should be able to solve most of your problems.

Remember that programming is about patience and this is coming from someone with Cisco background that hated programming. My passion lies in networking but I am starting to enjoy programming. If you are trying to solve a problem and it isn’t working, give yourself a break and then come back to tackle the problem. You are not going to get it first time round, if you do then well done.

Finally, if you are someone who doesn’t like to read a lot of text, the code for each example is put inside the box so that you can easily identify it.

What is python?

Python is a high level programming language that was developed by Guido van Rossum. It is a language that works in many platforms such as Windows, Linux, Mac etc… A programming language enables us to communicate instructions to a computer. We use a programming language to create programs. The program can be used to control the behaviour of a machine and we do this by creating instructions which are known as algorithm.

If you want to use Python then you will need to install an interpreter. The interpreter will understand our instructions typed using python syntax and it will convert it into a form that the computer can understand.

To install the interpreter, you can go to the link below:



There are different versions of Python. The version we are using at the moment is 3.2.x. You can install any new version and the code should work perfectly fine. When you install Python it will install IDLE which is a GUI based interface. At the moment, at school, we are using PyScripter which is basically an editor. It makes things easier and more manageable when we are coding. You can think of html as a scripting language and Dreamweaver as the editor we use to design and code our website.

How do I code?

To create a program, you will need to use IDLE as this is the development environment. You can then code away and save your project with the following: filename.py. You don’t have to limit yourself to IDLE, you can use other environments but don’t forget you will need to interpreter. This can be downloaded from the link above.

Output to the screen

Note: If you copy the code, do not copy the line number. The line number is there for reference purposes only.

We output to the screen if we want to ask the user a question or if we want to display something. To output, we use a function called print. The print function is responsible for displaying text onto the screen and it takes an argument; what you put inside of the brackets.

An example of the print function:

1. print(“Hi. What is your name?”)

1. The first thing you need to remember is that Python is case sensitive and this means that the word print has to be in lower case otherwise it will not work.

2. It is also important to note that any message you want to display has to be in quotes unless it is a variable otherwise it will be treated as text (string).

3. You can use single quotes or double quotes but you cannot use them together.

4. Finally, when you print, you need to make sure that you have an open bracket (and a close bracket ).

Displaying variable

We can use the print function to also display a variable or perform some calculations. You can perform the calculations inside of the brackets. To perform calculations you must not use quotes. Every time you use quotes the computer thinks that you want to display string (text) so “5 + 5” is not the same as print(5+5). The first one will print 5+5 and the second one will print 10.

Examples:

1. name = “Bob”

2. print(“Hi “ + name)

3. print(10 * 50)

1. Line 1 is showing a variable being assigned a value. In this case the variable is called name and it is assigned the value “Bob”. We will discuss variables later in detail.

2. Line 2 is showing a variable being printed with some text. This process is known as concatenation. It is where we add text and variables together.

3. If line 2 was printed, it would output the following text: Hi Bob.

4. Don’t forget that we are adding two strings together and this will work however if we were adding a string and a number we would need to convert them. I have covered this under the heading: converting variable data type

5. Finally, line 3 will print 500 as the output. This is because it is not inside quotes and it will perform the calculation.

Adding line breaks

1. For each line of text you want to display, you will need to use the print statement.

2. You can add a line break line so

1. print(“This is the first line of text”)

2. print(“This is the second line of text”)

1. print(“This is the first sentence

2. And this is the second”)

3. The second example code will not work. You will need separate print statements lines.

4. If you want the second example to work with line break you can use the following code:

1. print(“This is going to \n print two lines of code”)

5. \n can be used to print a new line.

6. Don’t forget the space after \n will be printed in the new line. If you don’t want this space, then use it like so: \n….

Images for printing to the screen

How the code will look when you run it

Tip: hold ctrl and press F9 and it will run the code i.e. debug it.

The green line of text is displaying what our program will look like when we run it. If you receive any errors you need to make sure that you have used the correct syntax.

Taking input from the user

Taking inputs from the user is an important part of programming because every program takes some sort of input from the user. If we have a program where the user has to log-in to the system, we need a way of storing that information somewhere. This is so we can check whether or not they have the credentials to access the system. This has to be stored somewhere i.e. in a variable.

To take an input, we use the input function.

1. name = input(“What is your name?”)

2. print(“Hi “ + name)

1. In line 1 we are declaring a variable called name. The variable name is going to be assigned to whatever the user inputs.

2. In line 1 we have used the input function and the text inside of the brackets is what the user is going to be displayed with.

3. In line 2 we are printing Hi with whatever the user inputs as their name. If you remember this process is known as concatenation.

4. We can take as many inputs as we want and we can either store them in separate variables or update the existing variable.

1. guess = input(“What is your first guess?”)

2. print(“You first guesses is: “ + guess)

3. guess = input(“What is your second guess?”)

4. print(“You guesses guess is : “ + guess)

5. The example above is showing two inputs taken from the user using one variable.

Images for taking input from the user

[pic]

1. The image above shows how our code will be formatted in PyScripter.

1. This screenshot shows the window that will be displayed asking the user to input

2. This will be different based on the environment you are using.

1. This screenshot is showing the Python interpreter and the output for running our code.

Variable

A variable is a place holder for a value or expression. We declare a variable by giving it a name and also the value that it is going to be assigned, i.e. the value it is going to hold. The value that a variable is assigned can change within our program. A simple way of thinking about a variable is that it is a box where we store things. As our program develops, we will be storing more and more of these boxes.

Why would we store an expression or value in a variable?

Well, if the expression was big and if it involved complicated calculations then we might not want to actually do it again. If we save the value or answer from the expression in a variable it saves us from running the code again. Remember, programmers are lazy and they don’t want to repeat things.

Why do we give values a name?

When we give a value from an expression a name, it makes it easy for others to identify our computation i.e. what we are trying to do in our program and how this value is going to be used later on.

Declaring variables

In this example I am going to show you expressions that are going to be stored in a variable.

1. shirt_price = 50

2. vat_rate = 0.20

3. vat_amount = shirt_price * 0.20

4. total_price = shirt_price + vat_amount

5. print(“The price of the shirt, after vat, is “ + str(total_price))

1. In line 1 and 2 we are assigning the value 50 to shirt_price and 0.20 to vat_rate.

2. When we assign a value to a variable, we do not have to remember what value we have assigned it, we just have to remember the name (identifier) we have given it such as shirt_price or vat_rate.

3. The other good thing about storing this value in a variable is that we can perform calculations on it and if suddenly vat_rate changes to 25%, we just do vat_rate = 0.25 and this will update the value in our algorithm (code).

4. If we didn’t use a variable then we would need to go into our code and manually change 0.20 to 0.25 which can be time consuming if we are doing many calculations.

5. Line 3 is storing an expression that consists of two operands (50) and (0.20) and the operator * (multiply). The value of this, which is 10, will be stored in the variable vat_amount.

6. Line 4 is going to store the calculation for shirt price plus how much the VAT will be to total_price.

7. Line 5 is printing the string with the variable total price which is converted into string otherwise it will give an error because of the + sign.

Images for variable

Code

[pic]

Interpreter window

[pic]

Suggestion:

In our program we have given the variables static values. This means we have assigned a value to them. We could create a program where we are taking inputs from the user and storing those inputs to the variables. This will make our program more dynamic and it

Changing a variable

When we declare a variable and give it a value, we can, anywhere within our program update this value.

1. name = “Bob”

2. name=”John”

3. print(name)

1. Line 1 is declaring a variable called name that will be assigned Bob

2. Line 2 is updating the variable name and it will be assigned john

3. Line 3 is printing the variable name and it will show the updated name (John)

Output

[pic]

Valid variable names

When we declare variable names in Python, we have to make sure that they are valid. A valid variable name will have a combination of letters, numbers and underscore.

Rules:

Allowed:

The name has to start with a letter or an underscore.

Examples:

1. username

2. test_score

3. apple

4. player_score

Not allowed:

1. A variable that starts with a number.

2. Spaces in your variables.

3. A variables that starts with a special character.

4. Certain special characters in your variable such as @.

Examples:

1. 13378

2. 1337_score

3. test score

4. @52

Tips

1. Variable names are case sensitive so the best advice is to use lowercase for your variables.

2. Use an underscore for multiple words.

3. Make sure that variables are memorable and they are related to the data it is going to store or expressions. For example if you were going to store your name then you would use my_name.

Assignment

You assign a variable to a value by using the equal sign. To test equality we would use == as this is to check if something is equal to a value.

Data type

To understand data types you need to understand that a variable is a location in memory to store values or expressions. The memory we are referring to here is your RAM (main memory). A memory that will lose data when there is no power going to it. Every time we declare a variable, what we are doing is reserving some space in memory.

Each variable will have a data type, when we declare the data type, the computer will reserve the appropriate storage space for that data type and it will dictate what can be stored in there. For example, if we declare a data type of integer, which is whole numbers, the computer will provide the space in memory for this and only integer (whole numbers: 10, 20 …) data type is allowed.

Python data type

The reason why Python is an easy language to learn is that we do not have to declare the data type for the variables as they are automatically assigned. When we assign a value to a variable, the data type will be automatically assigned. The data type is identified based on the assignment of data to the variable, the equal sign (=), if you have forgotten. The item to the left of the equal sign is the variable name and the item to the right of the equal sign is the value.

Integer

Integers are whole numbers. They are numbers without fractional parts. These are numbers like: 10, 50, 1,000, 100,000, -100,000 etc…

As you can imagine the computer will use less memory to store integers compared to numbers that will have fractional parts.

1. cost = 10

2. age = 15

3. cars = 10

1. The examples above shows variables being declared and assigned to different values

2. If you can recall, we mentioned that a variable that will store a number cannot have quotes. Quotes are only used for string data type.

Uses

I would integers for whole numbers. This could be for example the age of a person in years, the numbers of cars they have purchased, the numbers houses they own, the numbers kids they have etc..

String

In Python string is identified by the use of quotes. The quotes can have characters, letters, numbers etc… You can store string in single quotes or double but you cannot use both in one. For example:

1. name = “John”

2. name = “John’

1. Line 1 will work perfectly fine however line 2 will not as it is mixing double quotes and single quote

String manipulation

When we store string in a variable we can then then call that variable or we can manipulate the string and do lots of different things with it.

Accessing string

1. word = “Hello”

2. letter = word[0]

3. print(word)

Output

[pic]

1. The example above is going to store “Hello” in the variable word.

2. In line 2 the variable letter is going to store the variable word, 0 index. This is basically the first letter of the word.

3. Line 3 is going to print this off

Tip:

1. Use [] to access characters in string.

Length

We can also find out the length of the word by using a function called length.

1. name = “Hello”

2. print(len(name))

The output will be 5.

Finding words or letters

We can use the find function to find a word within our string variable or a letter.

Index

1. name = “Hello World”

2. find_letter = name.find(“H”)

3. print(find_letter)

1. When you print the example above it will output 0. The 0 is the index number and computers count from 0.

2. If you think about it, 0 is H, 1 is e, 2 is l, 3 is l and is l and so on…

3. If you look for a letter that doesn’t exist then it will print -1

Counting letters

1. name = “Hello World”

2. counting_letter = name.count(“H”)

3. print(counting_letter)

1. This will look at the string that is stored in the variable. It will then try to count the number of letter it has based on what you have asked it to find.

2. In the example above, we are trying to find the letter H.

3. We can improve this example by using the .lower() function to make all the text lower and using the And operator to find two or three letters that occur.

Example:

1. name = “Hello World”

2. name = name.lower()

3. counting_letter = name.count(“h” and “o”)

4. print(counting_letter)

1. The example above is going to make the text stored in the variable to lowercase.

2. It will then count the number of times the letter h and o occur in our example.

3. We have used an AND statement so h AND o has to be there.

Count the number of spaces

This could be used to force the user to only use a certain number of spaces.

1. test = “This is going to have too many spaces .”

2. print(test.count(‘’)

Others you can look through

1. Start with and end with

2. Replace function will replace a word or letter

3. Upper and lower function

4. Concatenation (+)

5. Isalnum() check if it is all numbers

6. Isalpha() checks if all characters in the string are alphabetic

Real

tring summary

Escaping characters

Mention about the type function

Project example

My_name =”F”

Print (my_name)

My_age = 24

Print above

My_age = 24 + 1

better:

my_age = my_age + 1 or my_age += 1

Magic pill

My_age = 24

Magic_pill = 30

Print my_age – magic_pill

Magic_pill cost 300k

Temperature converter

Temp_Fahrenheit = 32

Temp_celcius = 5.0 /9.0 * (temp_Fahrenheit – 32)

Print(temp_celcius)

Know the value before you even run it.

1. What is a function?

Anywhere where you have used a pair of brackets after an instruction in your coding, you have been using a function. The first function we used was print():

print("I'm an argument")

In the above example, we tell Python the name of the function we want to use (print) and then in the brackets we put our argument. An argument is the information Python needs to carry out the function.

When we want to use more than one argument in a function, we separate them with a comma, as in this example:

1. name = "Mr Chapman"

2. print("My name is ", name)

In this example, the string of text is the first argument, and the variable is the second argument.

It is also possible to have a function that takes no arguments. In this instance, you still put the brackets after the function name, but leave them empty.

2. Creating a function

We have already used a number of different functions that are built into Python, and you will no doubt discover many more as you continue your life as a programmer. But there will also be times where you want to create your own function. It is good practice to create a function for any piece of code that you will need to use more than once within your program. This means you don’t have to re-type the whole thing every time you need to use it, instead you just call your function.

To create a function we use the def keyword, as in this example:

1. def count(number):

2. n=1

3. while n >> count(10)

2. 1

3. 2

4. 3

5. 4

6. 5

7. 6

8. 7

9. 8

10. 9

11. 10

Python will then count up to the number we supply in the argument.

Over the next couple of tutorials we’ll be creating the final program to finish off this series, so make sure you check back on Thursday. I’ll be starting a new tutorial series next week – if there’s anything you’d particularly like to see, let me know.



While loop examples

import random

number = random.randint(1,6)

while True:

choice= input("Would you like to stop")

choice = str(choice)

choice = choice.lower()

if choice == 'y' :

break

elif choice == 'n':

print(number)

import random

timeToStop = "N"

sides = int(input("How many sides would you like to have on your die?"))

while timeToStop != "Y":

number = random.randint(1,sides)

print(number)

timeToStop = input("Would you like to stop?")

print("Thank you for playing")

add the input to it.

3. Creating a list

Another thing we can use the random module for is choosing items from a list. To do this, we need to set up a list in Python. Setting up a list is very similar to creating a variable and setting its value. We start out by giving our list a name, followed by an equals sign. If we were setting up a variable, we would now just type in a value for our variable. With a list, we use square brackets:

pencilCase = ["Pen", "Pencil", "Ruler", "Rubber", "Fork", "Post-It Notes", "Coffee Stirrer"]

As you can see, I’ve now listed the contents of my own pencil case. If I want to check what’s in it, I can just type:

print(pencilCase)

And Python tells me:

['Pen', 'Pencil', 'Ruler', 'Rubber', 'Fork', 'Post-It Notes', 'Coffee Stirrer']

If I only want to print a specific item from my list, I put the number the item appears in my list in square brackets as below:

print(pencilCase[2])

And I get:

Ruler

Note: Python starts counting from zero, so when we asked for item number 2, Python displayed the third item on the list, ruler. If we wanted Pen to display, we could print pencilCase[0].

4. Randomly selecting from a list

Now we know how to create and store lists in Python, we can look at how to randomly select items from them.

In the above example, I created a list of items in my pencil case. If I now wanted to randomly pick one, I would type:

1. import random

2.

3. pencilCase = ["Pen", "Pencil", "Ruler", "Rubber", "Fork", "Post-It Notes", "Coffee Stirrer"]

4. print(random.choice(pencilCase))

As with the die example above, we must first import the random module to be able to use functions from it. We then create our list, and to print a random item from it we use another of random’s built in functions, choice. The output from this code is:

Loop:

If statements:







Variables

Concatenation

converting variable data type

MC tutorial



Keywords

Syntax

Variable

Debug

Code



program idea

-----------------------

Argument that we pass to our function. In this case we are trying to display text hence why we are using quotes.

Print function in lowercase.

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download