>> letter = fruit[1] >>> print letter Output: a The expression in brackets is called an index Index starts at zero"> >> letter = fruit[1] >>> print letter Output: a The expression in brackets is called an index Index starts at zero">
Download presentation
Presentation is loading. Please wait.
Published byRoxanne O’Neal’ Modified over 9 years ago
1
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University 2010-2011
2
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
3
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
4
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]
5
Exercise As an exercise, write a function that takes a string as an argument and outputs the letters backward, one per line.
6
String Operations
7
String Slices A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
8
String Comparison The comparison operators work on strings. In Python, uppercase letters come before all the lowercase letters. Zebra, comes before banana.
9
Cannot change Strings! A string cannot be changed in Python! Immutable Create new strings from bits and pieces of old
10
String Functions ( import string )
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.