Python Programming Techniques PDF

Summary

This document provides notes on Python programming, specifically focusing on string manipulation techniques. The content covers topics like input/output functions and comments. It's presented as instructional material.

Full Transcript

2.2 Programming Techniques Introduction to Python and string manipulation Start print ("What is your SELECT * FROM name") Objectives You will apply:  The...

2.2 Programming Techniques Introduction to Python and string manipulation Start print ("What is your SELECT * FROM name") Objectives You will apply:  The use of variables, constants, operators, inputs, outputs and assignments  The use of basic string manipulation Contents 1. Introduction to Python 2. Built-in functions, keywords, comments 3. Strings 4. Input and output 5. Working with variables 6. Printing variables and strings 7. Changing the case of strings 8. The find() function 9. Joining strings (Concatenation) 10. Sub-strings / Slicing strings 11. Flowcharts Introduction to Python Information Thonny IDE  IDE stands for Integrated development environment.  It is an environment which used to create programs by writing Python code. Code editor - where you write all the code Shell - shows outputs from the code Information Other important aspects of the environment Tabs - shows all currently open programs. Line numbers Information Running programs There are three ways of running a Python program: 1. Select the "Run" menu and then select "Run current script". 2. Press F5 on the keyboard. 3. Click the Run icon. Information Identifying errors in programs Thonny IDE will highlight some errors which break the rules of Python (i.e. syntax errors) as code is being written, which includes:  Missing speech marks are green: print ("What is your name )  Missing brackets are grey: print ("What is your name" Information Identifying errors in programs If you try to run a program which has syntax errors, it will not run and Thonny will provide error messages and hints to help in the identification of these errors: Assistant - provides helpful hints Error messag es Information Accessing cheat sheets and worksheets This presentation (i.e. notes), worksheets and files can be accessed from the "RMShared Documents" folder. RMShared Documents  ICT  KS4  CS  2. Programming  Python Built-in functions, keywords and comments Information Built-in functions  Python contains a set of built-in functions that are always available to use anywhere in a program.  They do specific tasks.  They are shown in purple. EXAMPLES:  print()  input()  int() Information Keywords  Python contains a set of keywords that are reserved words.  They must be written in lowercase.  Each keyword has a special meaning and a specific operation.  They are shown in orange. EXAMPLES:  import  if  else  break Information Comments  Comments starts with the hash tag symbol #.  Comments are useful to help others understand a program.  Python ignores them and they thus do not affect the way a program runs.  They are shown in red. # Example 1 - what is your name is output to the screen print ("What is your name?") # Example 2 - The user’s input is stored in the variable named firstname firstname = input() # Example 3 - The user’s names output with a message print ("Hello,",firstname) Strings Information Working with strings  One or more alphanumeric characters (which can include numbers).  It is enclosed within either single or double quotation marks.  They are shown in green. # Examples:  'hello'  "hello" Input and output Information Print() function  The print() function outputs to the screen.  It can be used to print a string to the screen. # Examples print ( "Hello World!") print ( "What is your name?") Information Input function()  The input() function allows user input.  It delays execution of a program to allow the user to type input from the keyboard. # Example: The input() function has been combined with a variable to allow the user to enter a value which is stored in the variable firstname. print ("What is your name?") firstname = input() Information Input function() extended  A prompt can also be included with the input() function.  The prompt parameter is optional and can be used to output a string before the input. SYNTAX: input(prompt) # Example 1: Using the prompt parameter firstname = input("What is your name?") #Example 2: Not using the prompt parameter print ("What is your name?") firstname = input() The output and function of both example 1 and 2 are the same. However, example 1 has less lines of code therefore is more efficient. Information New line character  The newline character ("\n") can be used to create a new line.  It consists of a back slash, followed by the letter n in lowercase.  Multiple new line characters can be used together.  It is frequently used with the print() function. Example EXAMPLE 1: print ("\nWelcome")Missed line New Welcome line >>> EXAMPLE 2: print ("Welcome\n") Welcome Missed line >>> EXAMPLE 3: print ("Welcome\nThis is a test") Welcome New This is a test line >>> Welcome EXAMPLE 4: print ("Welcome\n\nThis is a test") Missed New line This is a test line >>> Working with variables Information Variables A variable is a memory location which stores data that can be changed while a program is running. # Example 1: The variable named firstname is given the value Zhang firstname = "Zhang" # Example 2: The variable named age is given the value 24. age = 24 Information Creating a variable A variable can be created and given a value in a number of different ways. METHOD 1: The variable firstame is created and given the firstname = "John" value "John". The variable age is created and given the value 23. For age = 23numbers, the quotation marks do not need to be included. METHOD 2: The variable surname is created and given the value which is inputted by the user. surname = input() Note: Method 1 is used when the value of the variable is known before a program is run. Information Identifiers An identifier is the name given to a variable, sub-program (to be covered later), array (to be covered later), etc. They must be consistently used throughout a program. Rules for choosing identifiers: 1. They must clearly describe the data being stored. 2. They can contain letters, numbers and underscores. 3. They can start with a letter or an underscore but can not start with a number. 4. They cannot include a spaces. 5. They cannot include special symbols (e.g. !, @, #, $, £, etc.). 6. They cannot be the same as keywords. Information Which of these identifiers is the most meaningful? SA Surfacearea The wording makes it clear what is being stored, and Surface_Area the use of capital letters and the underscore makes it easy to read. How choosing sensible identifiers improves a program:  It enables programmers to understand the purpose of each variable.  It makes the code easier to follow.  It provides information for future programmers to help maintain the code. Example Identify the inappropriately named variables. Example 1: Example 2: Example 3: f="Angela" pi="python is w = 150 interesting" h = 70 a=24 p=pi[:6:1] d=9 print("My name is",f) i=pi[7:10:2] print("I am",a,"years old") ii=pi[10:21:3] print(p) print(i) print(ii) Variables must clearly describe the data being stored. Example 4: Example 5: firstname="Angela" message="python is age=24 interesting" print("My name is",Firstname) word1=message[:6:1] print("I am",Age,"years old") word2=message[7:10:2] word3=message[10:21:3] print(Word1) print(ward2) print(word 3) Variable names must be consistently used throughout a Information The assignment operator  Assignment is giving a variable a value.  The = symbol is the assignment operator in Python.  There are a different methods of giving a variable a value, these include: Method Examples Using the input () function. length = input() width = 21 Writing the value. name = "David" wages = hours * 15 Using the arithmetic operators in area = (a + b) /2 combination with other variables sum = 4 + 5 and values. fullname = firstname + surname Printing variables and strings The following printing will be covered:  Printing variables.  Printing the length of strings.  Printing specific characters of strings. Information Printing variables  The print() function outputs to the screen.  It can be used to print the data stored in a variable. EXAMPLE: print ("What is your name?") firstname = input() print (firstname) It can be combined with an appropriate message: print ("Your firstname is",firstname) Example Printing variables - examples  When printing to the screen, strings and variables can be combined.  The strings and variables must be separated by commas. It prints the string "Hello", followed by the EXAMPLE 1: print ("Hello",firstname) value stored in the variable firstname. It prints the string "Hello", EXAMPLE 2: print ("Hello",firstname, surname) followed by the value stored in the variable firstname and then the variable surname. It prints EXAMPLE 3: print ("You are",age, "years old")the string "You are", followed by the value stored in the variable age and then followed by the string "years old". Information Printing the length of strings  The len() function returns the length of a string.  It can be combined with the print() function to output the number of letters in a string. SYNTAX: len(variable_name) len("string") # EXAMPLE 1 print (len("John")) # EXAMPLE 2 name = input() print (len(firstname)) It can be combined with an appropriate message: print ("The number of letter in your firstname is",len(firstname)) Information Indexing stings  Each character in a string has a corresponding index, which indicates its position.  The index starts at 0.  The following table indicates the index for each character in the 0 1 2 3 4 string "Hello": H e l l o  Indexes can be used when:  Accessing specific characters of strings.  Printing specific characters of strings.  Searching a string for a specific character.  Slicing strings (To be looked at later). Information Accessing specific characters in strings When indexing strings, the individual characters in a string can be accessed by writing the name of the variable along with the index, enclosed in square brackets. SYNTAX: variable_name [index] Example Accessing specific characters of strings – example 1 0 1 2 3 4 5 6 7 8 9 fullname = "John Smith" J o h n S m i t h Which letters do the following indexes represent? fullname J fullname n fullname fullname t fullname string index out of range Example Accessing specific characters of strings – example 2 fullname = "Sam Jones" 0 1 2 3 4 5 6 7 8 S a m J o n e s Which letters do the following indexes represent? fullname S fullname m fullname n fullname s Information Printing specific characters of strings By using the index of a string with the print() function, allows individual characters in a string to be printed. SYNTAX: print(variable_name [index]) # EXAMPLE 1 firstname = "John" print(firstname) Outputs the first letter print(firstname) Outputs the fourth letter # EXAMPLE 2 school_name = input() print(school_name) Outputs the second letter print(school_name[-1]) Outputs the last letter Changing the case of strings The following functions allow the case of strings to be modified:  Upper()  Lower()  Title()  Capitalize() Information All characters of a string in uppercase The upper() function makes all characters of a string uppercase. # EXAMPLE 1 print ("What is your postcode?") postcode = input().upper() print ("Your postcode is",postcode) What is your postcode? e4 8es Your postcode is E4 8ES # EXAMPLE 2 print ("hello".upper()) HELLO Information All characters of a string in lowercase The lower() function makes all the characters of a string lowercase. # EXAMPLE 1 print ("Enter a word?") word = input().lower() print ("You entered the word",word) Enter a word? PIZZA You entered the word pizza # EXAMPLE 2 print ("HELLO".lower()) hello Information First character of each word uppercase The title() function makes the first character of each word in a string uppercase. # EXAMPLE 1 print ("What is your full name?") fullname = input().title() print ("Your full name is",fullname) What is your full name? john smith smith Your full name is John Smith # EXAMPLE 2 print ("hello world".title()) Hello World Information First character of a string uppercase The capitalize() function makes the first character of a string uppercase. # EXAMPLE 1 print ("What is your name?") firstname = input().capitalize() print What ("Hello,",firstname) is your name? john Hello, John # EXAMPLE 2 print Hello ("roberto".title()) World NOTE: The word capitalize follows the American spelling of the word so it includes a z and not a s. The find() function Information The find() function  The find() function finds the first occurrence of a specified value and returns its index.  It has three parameters, separated by commas.  It specifies at which index to stop  It specifies the value to the search.  The default is the last character. search for.  It is required.  It is optional. SYNTAX: string.find(value, start, stop)  It specifies the string being  It specifies at which index to start searched. the search.  It is required.  The default is the first character (0).  It is optional. Example Find function() - examples EXAMPLE 1: fullname = "John Smith" Searches the string fullname and returns the print(fullname.find("h")) index of the first occurrence of the letter "h". 2 EXAMPLE 2: fullname = "John Smith" Searches the string fullname from index 5 print(fullname.find("h",5,10)) to 10 and returns the index of the first occurrence of the letter "h". 9 EXAMPLE 3: print("Enter your full name") Searches the variable fullname which is inputted by the user and returns the index fullname = input() of the first occurrence of the letter "a". print(fullname.find("a")) Joining strings (Concatenation) Information Joining strings (Concatenation)  Two or more strings can be joined together to form a larger string.  The + operator can be used to join strings. EXAMPLE: A new variable named fullname has been created which joins the variables firstname and surname. firstname = "John" surname="Smith" fullname = firstname + surname Information Joining string variables with other strings  String variables can also be joined to other strings.  In the following example the string variables firstname and surname have been joined with a space between them (a space is a character and thus a string). EXAMPLE: firstname = "John" Surname = "Smith" fullname = firstname + " " + surname A space between the quotation marks must be included Example Joining string variables with other strings - example A new variable named fullname has been created which joins the string variables title, firstname and surname with spaces between each. firstname = "John" Surname = "Smith" title = "Mr" fullname = title + between A space " " + firstname + " " +marks the quotation surname must be included Example Joining strings with integers  Strings cannot be joined with integers and floats unless they are converted to strings.  This can be achieved using the str() function. EXAMPLE 1: The following code creates a new username variable which joins the variable surname, followed by the first character of the variable firstname, followed by the length of the variable surname. (strin (string) (integer) g) username= surname +firstname +str( len ) (surname) EXAMPLE 2: The following code creates a new username variable (strin (intege which joins the string "John" with the integer 10. g) username= "John" 10 +str(r) ) Sub-strings / Slicing strings Information String slicing  There are times when it is required that a program extracts characters from a string. This is called string slicing.  When a string is sliced, a sub-string or slice is created which returns part of the original string. original_pizza original_pizza The name of the original [0:2] 0 pizza and the slices 0 5 being returned must be specified. 1 4 1 sams_slices = 3 2 original_pizza [0:2] The slices must be given a new name. Information Slicing syntax  When creating a substring or slice, three parameters can be specified (the third parameter will be covered later).  They are separated by colons and enclosed within square brackets.  A start or stop parameter must be included. Start:  It specifies at which index to start the substring.  The default is the first character (0). SYNTAX: original_string [start : stop] Stop:  It specifies at which index to stop the substring.  The default is the last character.  It always stops one before this number. Example Slicing strings – example 1 fullname = "John Smith" The variable fullname has been sliced to create two substrings which are firstname and surname. SUBSTRING 1: FIRSTNAME  Firstname is a substring of the variable fullname, which starts at index 0, stops at index 4 and includes every character.  firstname = fullname [0:4] 0 1 2 3 4 J o h n Start Stop SUBSTRING 2: SURNAME  Surname is a substring of the variable fullname, which starts at index 5, stops at index 10 and includes every character.  surname = fullname [5:10] 5 6 7 8 9 1 0 S m i t h Start Stop Example Slicing strings – example 1 fullname = "John Smith" 0 1 2 3 4 5 6 7 8 9 J o h n S m i t h The variable fullname has been sliced to create two substrings which are firstname and surname. SUBSTRING 1: firstname = fullname [0:4] firstname = fullname [ :4] When the first parameter is omitted, Python assumes the sub-string will start SUBSTRING 2: at the first character of the string. surname = fullname [5:10] surname = fullname [5 : ] When the second parameter is omitted, Python assumes the sub-string will stop at Example Slicing strings – example 2 message= "Hello World!!" 0 1 2 3 4 5 6 7 8 9 1 1 1 0 1 2 H e l l o W o r l d ! ! SUBSTRING 1: Slice the string "Hello". 0 1 2 3 4 5 word1= message[0:5] H e l l o word1= message[:5] Start Stop SUBSTRING 2: Slice the string "World". 6 7 8 9 10 11 12 13 word2= message[6:13] W o r l d ! ! word2= message[6:] Start Stop Example Slicing strings – example 3 message= "Good Morning" 0 1 2 3 4 5 6 7 8 9 1 1 0 1 G o o d M o r n i n g SUBSTRING 1: Slice the string "Good". 0 1 2 3 4 word1= message[0:4] G o o d word1= message[:4] Start Stop SUBSTRING 2: Slice the string "Morning". word2= message[5:12] word2= message[5:] 5 6 7 8 9 10 11 12 M o r n i n g Start Stop Example Slicing strings – example 4 message= "This is a test" 0 1 2 3 4 5 6 7 8 9 1 1 1 1 0 1 2 3 T h i s i s a t e s t SUBSTRING 1: Slice the string "This". 0 1 2 3 4 word1= message[0:4] T h i s word1= message[:4] Start Stop SUBSTRING 2: Slice the string "is". word2= message[5:7] 5 6 7 i s Start Stop Example Slicing strings – example 4 message= "This is a test"0 1 2 3 4 5 6 7 8 9 1 1 1 1 0 1 2 3 T h i s i s a t e s t SUBSTRING 3: Slice the string "a". word3= message[8:9] 8 9 a Start Sto p SUBSTRING 4: Slice the string "test". word4= message[10:14] 1 1 1 1 1 word4= message[10:] 0 1 2 3 4 t e s t Start Stop Information Slicing syntax  The third parameter is step.  It is optional. Stop: Start:  It specifies at which index to stop the  It specifies at which index to substring. start the substring.  The default is the last character.  The default is the first character  It always stops one before this (i.e. 0). number. SYNTAX: original_string [start : stop : step] Step:  It specifies how many characters to move forward after the first character is retrieved.  The default is every character (i.e. 1).  It is optional Example Example 2 revisited message= "Hello World!!" 0 1 2 3 4 5 6 7 8 9 1 1 1 0 1 2 H e l l o W o r l d ! ! SUBSTRING 1: Slice the string "Hello". word1= message[0:5:1] word1= message[:5:1] SUBSTRING 2: Slice the string "World". word2= message[6:13:1] word2= message[6::1] A step of 1 indicates that every character will be included in the substring. In these examples, it is not needed to include the step parameter as the substring includes every character from Example Example 3 revisited message= "Good Morning"0 1 2 3 4 5 6 7 8 9 1 1 0 1 G o o d M o r n i n g SUBSTRING 1: Slice the string "Good". word1= message[0:4:1] word1= message[:4:1] word1= message[:4:1] SUBSTRING 2: Slice the string "Morning". word2= message[5:12:1] word2= message[5::1] word2= message[5:1] A step of 1 indicates that every character will be included in the substring. In these examples, it is not needed to include the step parameter as the substring includes every character from Discussion What is the output 1? message= "Hello World!!" SUBSTRING 1: 0 1 2 3 4 5 word1= message[0:5:1] print(word1) H e l l o Hello Start Stop SUBSTRING 2: 0 1 2 3 4 5 word2= message[0:5:2] print(word2) H e l l o Hlo Start Step StepStop SUBSTRING 3: word3= message[6:13:3] 6 7 8 9 10 11 12 13 print(word3) W o r l d ! ! Wl! Start Step StepStop Discussion What is the output 2? message= "Computer Science" SUBSTRING 1: word= message[9:16:1] 0 1 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 0 1 2 3 4 5 6 C o m p u t e r S c i e n c e Science Start Stop SUBSTRING 2: word= message[9:16:2] 0 1 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 0 1 2 3 4 5 6 C o m p u t e r S c i e n c e Start Step Step Step Sto p Sine Discussion What is the output 2? message= "Computer Science" SUBSTRING 3: word= message[9:16:3] 0 1 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 0 1 2 3 4 5 6 C o m p u t e r S c i e n c e Start Step StepSto See p Flowcharts Information Flowcharts They can be used to represent an algorithm visually. They show:  The data that is input and output.  The processes (actions) that take place.  The decisions (used in selection and iteration) that take place. Some of the flowchart symbols: Symbols are used to represent different functions. Terminal – used to show the start and end of an algorithm. Process – used to show data processing e.g. a calculation. Input/Output – used to show input or output of data. Line – used to show the flow of control. Information Sequence  A flowchart can show the sequence of instructions.  The sequence of instructions is where instructions are processed one after the other from top to bottom. Example Flowcharts with sequence An algorithm asks the user to input their age and name, and then prints them with appropriate messages. Start Input age = input("What is your age?") age Input name = input("What is your name name?") Print age print("Your age is",age) Print name print("Your name is",name) End Example Flowcharts with sequence An algorithm creates a fullname variable which it slices into two sub- strings, firstname and surname. It then prints them with appropriate messages. Start Create fullname fullname = "Aisha Ali" variable Create "fistname" sub- firstname = fullname[0:5] string Create "surname" sub- surname = fullname[6:9] string Print print ("The firstname firsntame is:",firstname) Print surname print ("The surname is:",surname) End

Use Quizgecko on...
Browser
Browser