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

This is introductory course for computer science. Its about basic concepts involving in computer programming, structure and working. Key points in this lecture handout are: String Operations, Input Function, Python Reuses, Built-In Type Conversion Functions, Float Function, Input Built-In Function

Typology: Study notes

2012/2013

Uploaded on 09/28/2013

noob
noob 🇮🇳

4.4

(25)

105 documents

1 / 6

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Lecture Notes CPSC 121 (Fall 2012)
Today ...
String operations
Input function
Homework
HW 3 due
HW 4 out
S. Bowers 1 of 6
pf3
pf4
pf5

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!