COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
Conditional Expressions Boolean expressions an expression that is either true or false x == y # x is equal to y x != y # x is not equal to y x > y # x is greater than y x < y # x is less than y x >= y # x is greater than or equal to y x <= y # x is less than or equal to y >>> 5 == 5 True >>> 5 == 6 False True and False are special values that are built into Python. !!!Remember that = is an assignment operator and == is a comparison operator
Strings Strings are made up of smaller pieces—characters. The bracket operator selects a single character from a string. >>> fruit = "banana" >>> letter = fruit[1] >>> print letter Output: a The expression in brackets is called an index Index starts at zero
Length The len function returns the number of characters in a string: >>> fruit = "banana" >>> len(fruit) Output: 6 length = len(fruit) last = fruit[length] # ERROR! That won’t work. It causes the runtime error IndexError: string index out of range. The reason is that there is no 6th letter in "banana“ the six letters are numbered 0 to 5 length = len(fruit) last = fruit[length-1]
Exercise As an exercise, write a function that takes a string as an argument and outputs the letters backward, one per line.
String Operations
String Slices A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
String Comparison The comparison operators work on strings. In Python, uppercase letters come before all the lowercase letters. Zebra, comes before banana.
Cannot change Strings! A string cannot be changed in Python! Immutable Create new strings from bits and pieces of old
String Functions ( import string )