Noadswood Science, 2014
To understand what strings are and how decisions are made Thursday, September 17, 2015
Strings Python is excellent for using words and sentences within programs: different strings can be joined together, or individual parts of them can be selected and pulled out… Remember, a string can include letters, numbers, symbols or spaces a = ‘Run! ’ b = ‘Aliens are coming.’
Adding Strings Adding two numbers together creates a new number, and in the same way two strings can be added together (with one simply joining the other) The “+” symbol joins one string to the other a = ‘Run! ’< notice the space here after ! b = ‘Aliens are coming.’ c = a + b print(c)
In Between String New strings can also be added between two strings a = ‘Run! ’ b = ‘Aliens are coming.’ c = b + ‘ Watch out! ‘ + a print(c) Consider where your spaces go!
String Length Python allows you to identify the length of a string using the “len()” function It will count all the characters (including spaces) to give the total number of characters in a string a = ‘Run! ’ b = ‘Aliens are coming.’ print(len(b)) The answer should be 18 (there are 18 characters in string “b”)
String Escape Strings can go in single or double quotes – it is important that strings start and end with the same type of quote Write the following string print(‘It’s a lovely day today.’) This will cause an error – in order to avoid this Python has a function known as escaping – within the string if an apostrophe is needed type “\” before it such as the code below print(‘It\’s a lovely day today.’)
Numbering Characters Each character in a string is allocated a number according to its position – this position number can be used to look at individual letters or symbols, or to pull them out of a string… When counting the positions, Python starts at 0 (the second character is 1, the third is 2 etc…) FLAMINGO
Numbering Characters The position number is known as the “index” and can be used to pull out a particular letter from a string FLAMINGO a = ‘FLAMINGO’ print(a[3])< the character is position 3 from variable “a”
Slicing Two indexes can be used to pull out a part of the string (slice it) – the letter in the last position isn’t included FLAMINGO a = ‘FLAMINGO’ print(a[3:7])< a slice from index 3 to 6 in variable “a”
Start to End If you leave off the start or end index, Python will automatically use the first or last character of the string FLAMINGO a = ‘FLAMINGO’ print(a[:3]) print(a[3:])
Input The “input()” function is used to accept input from the keyboard into a program – it waits until a user finishes typing and presses the return or Enter key name = input (‘Enter your name: ‘) print(‘Hello’, name)
Output The “print()” function is used to display characters in the shell window – it can be used to show a combination of text and variables a = ‘David’ b = ‘is’ c = 31< no quote marks as this is an integer print(a, b, c) print(‘Goodbye’, a)
Separating Strings Strings can be separated in a variety of ways, including using the separator command (“sep”) Strings can be separated using spaces Strings can be separated using hyphens “-” (or other characters such as “+” or “*”) Strings can also be separated by printing on a new line
Separating Strings a = ‘David’ b = ‘is’ c = 31 print(a, b, c)< separates using a space print(a, b, c, sep=‘-’)< separates using a hyphen print(a, b, c, sep=‘\n’)< separates onto a new line
Ending Output There are several ways to signal the end of an output of a “print” function a = ‘Hurray!’ print(a, ‘.’)" print(a, end=‘.’)< “end=‘.’” ensures no space is printed print(end='\n')< new line for n in range(3):< repeat x3 print(a, end=‘ ‘)< output all on one line using a space print(a, end=‘\n\n\n\n’)< “\n” starts a new line print('4 new lines')
Decisions Programs make decisions about what to do by comparing variables, numbers and strings using Boolean expressions (True or False) Logical operators are used to compare variables against numbers, strings or other variables – the result is either True or False ==(equals operator) !=(not equal operator) <(less than operator) >(more than operator) <=(less than or equal to operator) >=(more than or equal to operator) *Remember, Python uses the equals sign (=) to assign a value to a variable
Decisions Write a Python code for a variable (toys) which equals the integer of 10 Print off the results for equal, not equal, less than, more than, less than or equal to and more than or equal to operators toys = 10 print(toys == 1) print(toys != 1) print(toys < 1) print(toys > 1) print(toys <= 1) print(toys >= 1)
Not, Or, And The not logical operator (not) reverses the answer (from True to False and vice versa) The or logical operator (or) checks if the outcome is one or another The and logical operator (and) checks if the outcome is one thing and another toys = 10 print(not toys == 1) print(toys == 1 or toys == 10) print(toys == 1 and toys == 10)
In The in operator (in) can be used to see whether one string is inside another string (e.g. is a letter in a word / is a word in a sentence) print(‘a’ in ‘abc’) print(‘d’ in ‘abc’) print(‘Mr Crowley’ in ‘Computer Science course with Mr Crowley’) print(‘Mr Hewitt’ in ‘Computer Science course with Mr Crowley’)
Compare Strings Two strings can be compared using the equal (==) or not equal (!=) operators Strings have to match exactly to get a True output dog = 'Woof woof' print(dog == 'Woof woof')(True – matches) print(dog == 'woof woof')(False – no capital) print(dog == 'Woof woof ')(False – extra space)
Rachel’s Birthday Today? Rachel’s birthday is the 9 th July – write a program using logical operators to check if it is Rachel’s birthday today… Write a second program to check if it is not Rachel’s birthday today Write a third program to check if it is Rachel’s birthday or New Year or Christmas today import datetime(Python function to find the date) i = datetime.datetime.now()(variable i for time now) %i.day(today’s day) %i.month(today’s month) %s (needed for string formation)
Rachel’s Birthday import datetime i = datetime.datetime.now() day = 9(Rachel’s birthday day) month = 7(Rachel’s birthday month) print((“Rachel’s birthday day is”), day) print((“Rachel’s birthday month is”), month) print(‘Current day is %s’ %i.day) print(‘Current month is %s’ %i.month) print((“Today is Rachel’s birthday:”), day == i.day and month == i.month)
Not Rachel’s Birthday import datetime i = datetime.datetime.now() day = 9 month = 7 print((“Rachel’s birthday day is”), day) print((“Rachel’s birthday month is”), month) print(‘Current day is %s’ %i.day) print(‘Current month is %s’ %i.month) print((“Today is not Rachel’s birthday:”), day != i.day and month != i.month)
Rachel’s Birthday or Xmas or New Year import datetime i = datetime.datetime.now() day = 9 month = 7 Xmas_day = 25 Xmas_month = 12 NY_day = 1 NY_month = 1 print((“Rachel’s birthday day is”), day) print((“Rachel’s birthday month is”), month) print((“Xmas day is”), day) print((“Xmas month is”), month) print((“New Years day is”), day) print((“New Years month is”), month) print(‘Current day is %s’ %i.day) print(‘Current month is %s’ %i.month) print(("Today is either Rachel's birthday, or Xmas or New Year:"), day == i.day and month == i.month \ or Xmas_day == i.day and Xmas_month == i.month or NY_day == i.day and NY_month == i.month) Use this character (\) to code over multiple lines
Rachel’s Birthday or Xmas or New Year