python basics (slides)

CSc 110 Python Basics

Announcements

Did you set up your workspace?

  • Did you download Python 3?
  • Did you download VS Code (or PyCharm, or Mu)?
  • If not, that’s fine, you can use vscode.dev

What is a program?

The print function

  • What does the print function do?

The print function

  • print() sends characters (strings) to the standard output
  • By default, the standard output of a python program goes to the console.
print("some characters")
some characters


print('some characters')
some characters

String operations

String concatenation:

  • What will the standard output display when the code below is run?
print("hello" + "world")

String operations

In your groups, try the following operations:

  • String repetition: "abc" * 4
  • String concatenation with + and ,. What is the difference?
  • Combine both repetition and concatenation to print the following:
They sang AaAaAaAaAaAaAaAaAaAa

String operations

solution 1:

print("They sang", "Aa" * 10)
They sang AaAaAaAaAaAaAaAaAaAa

solution 2:

print("They", "sang", "Aa" * 10)
They sang AaAaAaAaAaAaAaAaAaAa

solution 3:

print("They" + " "  + "sang" + " " + "Aa" * 10)
They sang AaAaAaAaAaAaAaAaAaAa

Multiple print statements

  • What will the standard output display when the code below is run?
print('Are')
print('You')
print('In')
print('College?')

Multiple print statements

  • By default, the print function moves the cursor to the next line after printing, unless you specify otherwise.
print('Are', end = ' ')
print('You', end = ' ')
print('In', end = ' ')
print('College?', end = ' ')
Are You In College? 

What other characters can you use for values for the end parameter?

Dealing with special characters

Write a simple program that prints the following output to the python console:


   He said, "What's up?" 
   Joe's friend didn't reply.

Dealing with special characters

double quotes:

print("He said, \"What's up?\"")
print("Joe's friend didn't reply.")
He said, "What's up?"
Joe's friend didn't reply.

single quotes:

print('He said, "What\'s up?"')
print('Joe\'s friend didn\'t reply.')
He said, "What's up?"
Joe's friend didn't reply.

Variables

Variables and assignment

  • Variables are names in a program that represent a stored value
  • We can assign names to particular values in our program
  • When we give a value a name, or update the value stored in a variable, this is called assigning a variable

Demonstration of variable assignment

Variable assignment does not produce any output to the console. Run the following code:

first_name = "Mary"
family_name = "Silva"

How would we print these variables?

Variables improve readability

Without variables:

print("The total price is", 100 * 1.08)
The total price is 108.0

With variables:

base_price = 100
tax_rate = 1.08
total_price = base_price * tax_rate
print("The total price is", total_price)
The total price is 108.0