Docsity

String Operations - Computer Science - Lecture Notes, Study notes of Computer Science

Partial preview of the text

Download String Operations - Computer Science - Lecture Notes and more Study notes Computer Science in PDF only on Docsity!

Today ...

  • String operations
  • Input function

Homework

  • HW 3 due
  • HW 4 out

String Operations

Python reuses some math operations for strings

  • Concatenate two strings with +

>>> first = "Hello" >>> second = "World!" >>> first + second ’HelloWorld!’ >>> first + " " + second ’Hello World!’

  • Repeat a string with *

>>> "Ha" * 3 ’HaHaHa’ >>> 3 * "Ha" ’HaHaHa’

  • This doesn’t work:

>>> "Ha" * "Ha" TypeError: can’t multiple sequence by non-int of type ’str’

  • This also doesn’t work:

>>> "Ha" + 3 TypeError: Can’t convert ’int’ object to str implicitly

The input built-in function

The input command can be used to get user input

  • For example >>> ans = input() Hi >>> print(ans) Hi
  • The input function waits for user input (ended by a newline)
  • Then returns the result (the string entered by the user)
  • You can also give an optional prompt >>> name = input("Please enter your name: ") Please enter your name: Shawn >>> print("Your name is:", name) Your name is: Shawn

The input command always returns a string

>>> x = input("Please enter an x value: ") Please enter an x value: 5

>>> y = input("Please enter a y value: ") Please enter a y value: 6

>>> print(x + y) # what happens if >>> x + y 56 # displays ‘56’ (with quotes)

>>> type(x + y)

Q: How can we properly add x and y here?

>>> int(x) + int(y) 11

>>> type(int(x) + int(y))

what about this ...

>>> type(int(x + y))

even though ...

>>> int(x + y) 56

Note that input is only for getting user information

  • Only use when user input is needed

Q: For example ... when is this useful?

def add(): x = input("Enter x: ") y = input("Enter y: ") return int(x) + int(y)

  • Only when we want user interaction ...
    • NOT for defining a general add function!
  • Would be better to get the input, then call an add(x, y) function
  • Relying on user input makes our functions less reusable!