Want to create interactive content? It’s easy in Genially!
Python Basics
Phil Hoggins
Created on May 14, 2021
Start designing with a free template
Discover more than 1500 professional designs like these:
Transcript
Coding with Python
Mr Hoggins - Computer Science
Coding With Python Index
Welcome to the Python help Guide, the options below will help you to get started on the path to being a code master
- What are variables
- Display text on screen
- Asking for input
- Making decisions
- Loops
- Validation
- Making a program
- Lists
- Useful Functions in Python
- Useful resources
- Famous quotes
What are variables
Variable are like containers, we can put something inside them and go back to it laterIn computing we can put text and number inside variables, there is a list of things we can put inside variablesThere are several different datatypes we can use in python including :
- STRING - data that is normally in quotes, "" words or worlds and numbers mixed etc
- INTEGER - whole numbers, 1,2,3,4,5,6,7,8,9,100, 9999999
- FLOAT - numbers with decimal places eg: 1.67 99.999
- BOOLEAN - True or False
- TUPLE - Tuple items are ordered, unchangeable, and allow duplicate values. Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
- LIST - List items are ordered, changeable, and allow duplicate values. List items are indexed, the first item has index [0], the second item has index [1] etc.
- DICTIONARY - Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable and does not allow duplicates.
Elians
4065
Peter
906
What are variables
Assigning values to variables. Variables contain data that changes . Variables that contain data that does not change throughout the running of a program are called constants: When we assign a value to a variable it assumes the datatype of the value, below are examples :
Here the value 9.99 is placed inside a variable called price. The number assigned is a decimal number so the datatype assumed by the variable is FLOAT.
price = 9.99
Here the value 12 is placed inside a variable called total. The number assigned a whole number, an integer so the datatype assumed by the variable is INTEGER.
total = 12
"You win!" is placed inside the variable msg, this is mixed text so the variable assumes the datatype STRING
msg = "You win!
The brackets used here indicate a datatype of TUPLE.
fruit_list = ("apple", "orange","lemon")
fruit_list = ["apple", "orange","lemon"]
The square brackets used here indicate a datatype of LIST.
Coding With Python Index
- How to display text on the screen
- How to display the contents of variables on the screen
- How to display a mixture of text and variables on the screen
- How to display a mixture of text and numbers on the screen
How to display text on the screen
to print some text or number on the screen using python look at the following commands
print ("Hello World !")
The output of this command will be
Hello World !
How to display variables on the screen
The variable must exist before you try and print the contents of it or you will get an error
user_name = "Fernando Alonso"
print (user_name )
The output of this command will be
Fernando Alonso
How to display a mixture of text and variables on the screen
The variable must exist before you try and print the contents of it or you will get an error
user_name = "Fernando Alonso"
print ("The name is " + user_name )
The output of this command will be
Your name is Fernando Alonso
How to display a mixture of text and numbers on the screen
The variable must exist before you try and print the contents of it or you will get an error
user_name = "Fernando Alonso"
user_age = 27
print ("Your name is " + user_name )+ print ("your age is " + str ( user_age))
The output of this command will be
Your name is Fernando Alonso Your age is 27
How to ask a question and get an answer
Asking a question or getting user input is a common activity, it's the inputting of data We need to use a variable to store the input and combine it with an input command and text we want to display
The text in green is what appears as the question
user_name = input("Please enter your name :") print ( "Your name is " + user_name )
The output of this command will be, this assumes the user typed Fernando Alonso as their name
Your name is Fernando Alonso
How to make decisions
Decisions are something that often follows some sort of data input.The line of code below is a question expecting a yes or a no as an input
option = input("Do you want to play the game again yes / no ? ")
We want the program to do different things depending on the input, if the answer is yes do something or if the answer is no do something different. A programming decision. To handle a programming decision we use the IF statement
option = input("Do you want to play the game again yes / no ? ") if option == "yes": do something elif option == "no": do something different
How to make decisions
Sometimes there are decision processes that have more than two options
option = input("Do you want to play the game again yes / no / maybe ? ")
The will want the program to do different things depending on the input, if the answer is yes do something or if the answer is no do something different, if the answer is maybe then we want to program to do something different again. To handle a programming decision we use the IF statement
option = input("Do you want to play the game again yes / no / maybe? ") if option == "yes": do something elif option == "no":do something differentelif option == "maybe":do something very different
Iteration, repeating things
It is common to want to do things again and again in computing, this is called iteration. There are a number of ways we can perform iteration within Python
- FOR loop
- WHILE loop
FOR Loop
The FOR loop is also known as a pre condition loop we use it to perform a block of program code a predetermined number of times. In the example below a variable called num is used as part of the for loop. Each time the program loops through the code the value on num is incrermented by 1 until limit set in the for statement is met.
for num in range (10): print ( " The number is " + str(num) )
The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 . . The number is 9
The output here shows us that the line of code directly under the for statement has been executed 9 times for each iteration the value of the variable num is incremented until it reaches 10.
WHILE Loop
The WHILE loop is also known as a post condition loop we use it to perform a block of program code until a condition changes. In the example below a variable containing a number is created and set to 1. the variable is called num.
num = 1 While num <= 10: print ( "number = " +num ) num = num + 1
number = 1 number = 2 number = 3 number = 4 numebr = 5 number = 6 number = 7 number = 8 number = 9 number = 10
The output here shows us that the lines of code directly under the while statement has been executed 10 times for each iteration the value of the variable num is incremented until it reaches 10.
Lets make a program
By now you should have gone through the basics, learnt about variables, know how to ask questions and print stuff.....even repeating code blocks. So lets put it all together a create a Python program than asks your name and age and prints the details you enter. Then asks if you want to do it again y/n.
again = True: while again: user_name = input ( "Please enter your name ") user_age = input ( "Please enter your age " ) print ( "Your name is " + user_name + " and you are " + user_ age + " years old" option = input ( "Do you want to enter details again y/n ? " if option = "n":again = False
Validation of data entry
Allowing a user to enter data is something we need to do but if they enter data we are not expecting it can cause a program to crash. We need to protect against our program crashing be validating what the user enters.
first we set a boolean variable to false.
valid = False while not valid: answer = input("Do you want another go y/n ? ") if answer in ("y", "n"): valid = True else: print("Please enter a valid option")
Next we run a loop that continues as long as valid = False
ask the question and put the response into a variable
Test if the answer is either "y" or "n"
If it is we set valid = True and the loop will stop running
If the answer is not "y" or "n" output a msg. valid stays = False
Validation of data entry
The previous page looked at validating text input, a simple yes or no question. Here we look at validating for numerical input, when we only want to accept numbers.
first we set a boolean variable to false.
valid = False while not valid: answer = input("Enter your age") if answer.isdigit(): valid = True else: print("Please enter digits only")
Next we run a loop that continues as long as valid = False
ask the question and put the response into a variable
Test if the answer is a number
If it is we set valid = True and the loop will stop running
If the answer is not "y" or "n" output a msg. valid stays = False
Here we use the isdigit method of the STRING datatype to test if the data input is numeric. There are lots of methods to check input data, take a look here
Navigating lists
Lists are generally used to group similar data items together. Lets create a list of fruits.
fruits = ["apple", "orange", "lemon", "pineapple", "melon"]
now, using a FOR LOOP we will go along the list and print out each item within it.
The code here uses a variable called fruit. Each time the code is looped over the list called fruits, the value of the variable fruit changes to the next item in the list. The loop stops when it reaches the end of the list.
for fruit in fruits:print(fruit)
The above code produces the following output.
apple orange lemon pineapple melon
Navigating lists
We have seen how to loop through a list which is very useful. but what if I just want the contents of the 3rd item in the list ?
fruits = ["apple", "orange", "lemon", "pineapple", "melon"]
Lists start with elements at position 0 and the position increses by 1 as we move along the list
The second element in the list is position 1
The first element in the list is actually position 0
If we want to print only the 3rd element in the list we would need to code it like this:
print (fruits[2] )
The output will be :
lemon
Adding / removing elements
We can add more elements to a list, below is the original fruits list, now we cant to add "banana" to it.
fruits = ["apple", "orange", "lemon", "pineapple", "melon"] fruits.append("banana")
To remove an element from a list
fruits.remove("orange")
There are more methods available for list variable click here
Useful functions
- Random Numbers
- Reverse a string
- Remove duplicate elements from a list
- Convert strings <--> numbers
- Find the lensth of a variable
Random numbers
Quite often we need to generate a random number or make a random selection from a list, here we will look at how. To generate any sort of random choice we need to use a module called random within the program. We need to use the import command to bring the functions into the program.
The import command is usually at the begining of the program, making its fuctions available in any part of our program.
import random random_number = random.randint(1,10 ) fruits = ["apple","orange","lemon"] random_fruit = random.choice(fruits)
The variable random_number is assigned a value between 1 and 10 assigned to it. randint is a function in the module random for generating random integers.
The variable random_fruit is assigned a valuefrom the list fruits. choice is a function in the module random for generating random integers.
There are many more random fuctions, to find out more click here
Reverse a string
Reversing a string, not something we do often but an example of a useful technique within Python
the [::-1] steps backwards through the text and puts it in reverse order in the variable txt
txt = "Hello World" [::-1] print(txt)
The output from this would be:
"dlroW olleH"
Remove duplicates from a list
Reversing a string, not something we do often but an example of a useful technique within Python
mylist = ["a", "b", "a", "c", "c"] mylist = list(dict.fromkeys(mylist)) print(mylist)
This is not a stright forward thing to do. We have to convert the list to a dictionary datatype which is the part in blue.
Next we have to convert the dictionary back to a list
The output from this would b a list with no duplicates in it:
["a", "b", "c"]
Convert a STRING to a NUMBER
Whenever we accept user input using the INPUT command the data typed in is in the format of text, inside quotes. There are many occasions when the input is a number but python
the [::-1] steps backwards through the text and puts it in reverse order in the variable txt
txt = "Hello World" [::-1] print(txt)
The output from this would be:
"dlroW olleH"
Useful Resources
There are many great resources on the internet to help answer your questions, here are a few to get you started. We can't always find the answers in tutorials but what ever your problem, someone has done it before so a good method to finding answers to questions is to type into a browser 'python how do I........' and see what answers you get
- W3schools Python
- Learn Python
- StackOverflow
Great quotes in computing
There are 10 kinds of people in the world, those that understand binary and those that do not!
Object Orientated Programming
Procedutal programming relates to statements and subroutines. Classes take a different route and focus on data structures and methods that operate on the data. Data that belongs together is grouped in a class. Items of data that make up a class are known as attributes. Definition : A class is a group of related attributes. Click the options below to find out more.
1. Classes
2. Objects
3. Methods
4. Inheritance
5. Containment
6. Encapsulation
Object Orientated Programming
Procedutal programming relates to statements and subroutines. Classes take a different route and focus on data structures and the subroutines that operate with that data Data that belongs together is grouped in a class. Items of data that make up a class are known as atributes. Definition : A class is a group of related atributes. Click the options below to find out more.
1. Private Classes
2. Public Classes
Classes - Private
Private classes can only be operated on by by methods defined within the class. They are very robust, meaning they can only be updated my defined methods reducing the risk of accidental changes to data. You are less liklely to introduce bugs into code using private classes.
This is an example of a private class. The class student has been defined. The attributes are all related to a student, the class groups these attributes together. When we populate the class with data we create an object of type student
class student: def __init__ ( self, firstname. lastname , dob )self.__first_name = firstname self.__last_name = lastname self.__date_of_birth = dob self.__form = "" self.__address = "" self.__telephone = ""
Classes - Private
Private classes can only be operated on by by methods defined within the class. They are very robust, meaning they can only be updated my defined methods reducing the risk of accidental changes to data. You are less liklely to introduce bugs into code using private classes.
This is an example of a private class. The class student has been defined. The attributes are all related to a student, the class groups these attributes together. When we populate the class with data we create an object of type student
class student: def __init__ ( self, firstname. lastname , dob )self.__first_name = firstname self.__last_name = lastname self.__date_of_birth = dob self.__form = "" self.__address = "" self.__telephone = ""
Classes - Public
Public classes can be operated on from anywhere within a program. Because of this they are more versitile to us as programmers.
This is an example of a public class. Note the difference in syntax here. The two underscore characters are missing from each attribute in the class. This means the attributes are public and can be updated from any part of the program.
class student: def __init__ ( self, firstname. lastname , dob )self.first_name = firstname self.last_name = lastname self.date_of_birth = dob self.form = "" self.address = "" self.telephone = ""
Objects
Public classes can be operated on from anywhere within a program. Because of this they are more versitile to us as programmers.
This is an example of a public class. Note the difference in syntax here. The two underscore characters are missing from each attribute in the class. This means the attributes are public and can be updated from any part of the program.
class student: def __init__ ( self, firstname. lastname , dob )self.first_name = firstname self.last_name = lastname self.date_of_birth = dob self.form = "" self.address = "" self.telephone = ""
Methods
Methods are associated subroutines that set and get data from a private class.
Here is our defined class, student
class student: def __init__ ( self, firstname. lastname , dob )self.first_name = firstname self.last_name = lastname self.date_of_birth = dob self.form = "" self.address = "" self.telephone = ""
def set_form ( self, form_name):self.__form = form_name def set_telephone ( self, tel )self.__telephone = tel
Here are examples of setters, subroutines which are defined within the class which are called to update specific attributes within the class. Each attribute will have a setter.
Methods
On the previous page we saw setters for a private class. To retrieve data from the class we use getters.
Here is our defined class, student
class student: def __init__ ( self, firstname. lastname , dob )self.first_name = firstname self.last_name = lastname self.date_of_birth = dob self.form = "" self.address = "" self.telephone = ""
Here are examples of getter, subroutines which are defined within the class which are called to return specific attributes within the class. Each attribute will have a getter.
def get_first_name ( self ):return ( self.__first_name ) def get_telephone ( self ):return ( self.__telephone )
so let's put the class student together with its methods
Methods
class student: def __init__ ( self, firstname. lastname , dob )self.first_name = firstname self.last_name = lastname self.date_of_birth = dob self.form = ""self.telephone = ""
The class student with methods for setters and getters. Each attribute has a setter to set or update its value and a getter to retrive the data.
def set_first_name ( self, firstname): self.__first_name = firstname def set_first_name ( self, lastname):self.__last_name = lastnamedef set_date_of_birth ( self, dob):self.__date_of_birth = dobdef set_first_name ( self, formID):self.__form =formIDdef set_telephone ( self, tel):self.__telephone = teldef get_first_name ( self ):return ( self.__first_name )def get_last_name ( self ):return ( self.__last_name )def get_date_of_birth ( self ):return ( self.__date_of_birth )def get_form( self ):return ( self.__form )def get_telephone ( self ): return ( self.__telephone )
Advanced Menu
1. OOP
2. Database access
3. Hash algorithm
4. Binary search
98. Useful resources
99. Quotes
Intermediate Menu
1. Lists
2. Arrays
3. Dictionaries
4. Functions
5. Procedures
6. Try Except
7. File handling
98. Useful resources
99. Quotes