Python Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

Concept: Strings

What is a String?
Strings were used in "Hello World!" print function examples. Strings are sets of
characters. In Python strings are in double or single quotes like "Hello
World!" or 'after edit, save!'

A String is a common type of data, used in programming, consisting of a sequence


of 1 or more characters.

 A String is a sequence of characters (aka: a string of characters)

 Character examples: A, B, C, a, b, c, 1, 2, 3, !, &

 A String in python is contained in quotes, single(') or double(")

 String examples: "ABC", 'Joana Dias', 'I have 2 pet cats.', "item #3 cost $3.29 USD"

Note: the quotes containing a string must come in matched pairs

 "Hello" or 'Hello' are correctly formatted strings

 "Hello' is incorrectly formatted starting with double " and ending with single '
python needs a matching quote to know where the string ends

Example
# examples of printing strings with single and double quotes

print('strings go in single')

print("or double quotes")

Task 1
print messages with "double quotes" and 'single' quotes
# [ ] enter a string in the print() function using single
quotes

# [ ] enter a string in the print() function using double


quotes
Concept: Integers
Integers are another type

 whole numbers such as -2, -1, 0, 1, 2, 3 are Integers

 Integers are not placed in quotes

A String can contain any character, this includes letters, spaces, punctuation,
number digits and formatting. In a string with digits ("123") the digits are text images
rather than representations of numeric values.

remember a line of python code starting with the pound or hash symbol (#) indicates
a comment

comments are for humans to read and are not run by computers

Example
# printing an Integer with python

print(299)

# printing a string made of Integer (number) characters with


python

print("2017")

Task 2
 print Integers

 print strings made of Integer characters

# [ ] print an Integer

# [ ] print a strings made of Integer characters

Student Tip: look for [ ] , which indicates a task in the notebook needs to be
completed.
Edit and Run to complete the task
Concepts: Variables
Variables & Storing Strings in Variables
Variables are named containers
Computer programs often create storage for things that are used in repeated
processing like item_price, student_name, stock_symbol. In python a variable is a
type of object that can be addressed by name to access the assigned contents.

Name a variable staring with a letter or underscore "_"


There are different styles for creating variables this course uses lowercase
descriptive names connected by underscores:

 item_price

 student_name

 stock_symbol

descriptive names reduce the need for comments in the code and make it easier to
share code or read code written long ago

Variables can hold strings


once a variable is assigned:

current_msg = "I am a string"

a python program can refer to the variable, current_msg, in code


so that current_msg, can be used like the string value ("I am a string")
which it stores

Variable reassignment
We can reassign a variable, changing the contents. current_msg = "new
current message"

Variables can be used in place of literals


If we initialize current_msg = "new current message" then
the literal string "new current message" and the variable current_msg are the
same when used in code

Example
 Initializing variables

 literals & variables in printing

 Variable reassignment

# [ ] Review code and Run

# initialize the variable

current_msg = "I am a string"

# print literal string

print("I am a string")

# print variable string

print(current_msg)

# [ ] Review code and Run

# assign a new string to the current_msg

current_msg = "Run this cell using Ctrl+Enter"

print(current_msg)

Task 3
Program: assigning values to a string

 in the cell below

 print the variable current_msg

 assign a new string to current_msg

 print the variable current_msg again

 run the code cell above and then run the cell below

# { ] run cell above then run this cell after completing the
code as directed

Q?: In the cell above, why did the variable have a value to print before it was
assigned?
Jupyter notebooks run cells individually. Any cell in the notebook can access a
variable assigned from a cell that has been run in the current notebook session.

Concepts: Data Types


Data types in variables
variables can be initialized with different data types. Below we see item_price is
a decimal (aka - float) and student_name is string

item_price = 10.25 #item_price initialized as a numeric value


(no quotes)

student_name ="Dias, Joana" #student_name initialized as a


string

license_plate = "123A" #license_plate initialized as a string

Variables can start initialized as an Integer number data type


x = 22

here the Integer 22 value was assigned to the variable x

The type of data a variable holds can be changed,


Python variables can change the type of data a variable holds
x = 22

x = "I am a string"

x changed type from Integer x = 22 to string x = "I am a string"

Best Practice: Friendly Names

Friendly name examples, (item_price, student_name,license_plate), were used above.

Variables help us to write code that can be used repeatedly


A personalized letter can be sent to every student with individual names by using a
name in a variable. Let's start with printing a name based on string variable.
Create a variable, name, at the top of the next cell. Assign a string value to name.

Remember to use the quotes for string values

Examples
name = "Joana Dias"

print(name)

test_value = 22

print(test_value)

test_value = "Joana"

print(test_value)

Task 4: multi-part
Assign a variable and print the value

 assign a string value to a variable student_name

 print the value of variable student_name

# [ ] assign a string value to a variable student_name

# [ ] print the value of variable student_name

Tasks 4 cont...
modified the value of a variable

 assign the student_name variable a different string value (a different name)

 print the value of variable student_name

 assign and print a 3rd value to student_name

# [ ] assign the student_name variable a different string


value (a different name)

# [ ] print the value of variable student_name


# [ ] assign a 3rd different string value, to the variable
name

# [ ] print the value of variable name

Tasks 4 cont...
change variable type with reassignment

 assigning a value to a variable called bucket

 print the value of bucket

 assign an Integer value (no quotes) to the variable bucket

 print the value of bucket

# [ ] assigning a value to a variable called bucket

# [ ] print the value of bucket

# [ ] assign an Integer value (no quotes) to the variable


bucket

# [ ] print the value of bucket

Q?: What is the difference between 123 and '123'?


A: A String type is not a number, even if it is all numeric digits

 in Python code a number can be assigned to a variable: x = 31

 a string of digits can be assigned to the variable id --> id = "001023" the quotations,
mean the number symbols should be stored in the variable as type string, meaning the
digits "001023" are treated as text

The print() function can print Integer or string values:

print(123) #integer, with numeric value

print("123") #string, represents text characters

Tasks 4 cont...
 run the above code the next cell:
# [ ] print integer 123 number

# [ ] print string "123" number

Concept: Using type


Using the Python type() function
type() returns the data type of Python objects

str, int, float


What does using type() reveal?

 str: when type() returns str that means it has evaluated a string characters (numbers,
letters, punctuation...) in quotes

 int: when type() returns int that means it has evaluated an Integer (+/- whole numbers)

 float: when type() returns float that means it has evaluated decimal numbers (e.g.
3.33, 0.01, 9.9999 and 3.0), ...more later in the course

Example
 Read and run the code for each sample

# [ ] read and run the code

type("Hello World!")

type(501)

type(8.33333)

student_name = "Colette Browning"

type(student_name)

Task 1: multi-part
Using type()

 Complete the "identify data types" tasks by assigning values to the variable bucket and
using type()
# [ ] show the type after assigning bucket = a whole number
value such as 16

# [ ] show the type after assigning bucket = a word in


"double quotes"

# [ ] display the type of 'single quoting' (use single quotes)

# [ ] display the type of "double quoting" (use double quotes)

# [ ] display the type of "12" (use quotes)

# [ ] display the type of 12 (no quotes)

# [ ] display the type of -12 (no quotes)

# [ ] display the type of 12.0 (no quotes)

# [ ] display the type of 1.55

# [ ] find the type of the type(3) statement (no quotes) -


just for fun

Concept: Addition with numbers and


strings
Addition: Numbers and Strings
Numeric addition
Numeric addition Single line math equations, run in a code cell, will output a sum

# adding a pair of single digit Integers

3 + 5

String addition
string addition single line equations, run in a code cell, will output a single
concatenated string

Tip: all strings must be in quotes

# adding a pair of strings


"I wear " + "a hat"

We can also add variables as long as we add strings to strings and numbers to
numbers

Example
String and Number Addition
# [ ] Review and run code for adding a pair of 2 digit
Integers

23 + 18

# [ ] Review and run code for adding 2 strings

"my name is " + "Alyssa"

# [ ] Review and run code for adding a variable string and a


literal string

shoe_color = "brown"

"my shoe color is " + shoe_color

Task 1: multi-part
String and Number Addition
# [ ] add 3 integer numbers

# [ ] add a float number and an integer number

# [ ] Add the string "This notebook belongs to " and a string


with your first name

# [ ] Create variables sm_number and big_number and assign


numbers then add the numbers

# [ ] assign a string value to the variable first_name and add


to the string ", remember to save the notebook frequently"

Concept: Addition in variables


use addition in variable assignments
It is common to store the results of addition in a variable

use addition in print ()


Use print() to show the results of multiple lines of output

Example
addition in variable assignments and in print()

# [ ] review & run code for assigning variables & using


addition

add_two = 34 + 16

first_name = "Alton"

greeting = "Happy Birthday " + first_name

print(add_two)

print(greeting)

# [ ] review & run code for Integer addition in variables and


in a print function

int_sum = 6 + 7

print(int_sum)

print(11 + 15)

print()

# string addition in variables and in print()function

hat_msg = "I do not wear " + "a hat"

print(hat_msg)

print("at " + "dinner")

Task 2: multi-part
create Integer addition and string addition output
# [ ] perform string addition in the variable named new_msg
(add a string to "my favorite food is ")

new_msg = "My favorite food is"

print(new_msg)

# [ ] perform Integer addition in the variable named new_msg


(add 2 or more Integers)

new_sum = 0

print(new_sum)

# [ ] create and print a new string variable, new_msg_2, that


concatenates new_msg + a literal string

Concept: Errors
Errors!
Encountering Errors and troubleshooting errors are fundamental parts of computer
programming

Example
# [ ] review & run code

print("my number is " + "123") #string, represents a text


character

print("my number is " + 123) #number, with numeric value

TypeError
The line print("my number is " + 123) causes the TypeError message to
appear

TypeError: Can't convert 'int' object to str implicitly

When adding to the string "my number is " the compiler is experiencing another
string, but finds a number *123
Python cannot convert the Integer 123 to a string without explicit instruction (in
code)

in other words, python only allows combining like types

 str + str

 int + int

Task 3
Fix TypeError

 Review the code in the cells below and then run the code

 Fix any errors and run until the code no longer shows errors

# [ ] review and run the code - then fix any Errors

total_cost = 3 + "45"

print(total_cost)

# [ ] review and run the code - then fix any Errors

school_num = 123

print("the street number of Central School is " + school_num)

# [ ] Read and run the code - write a hypothesis for what you
observe adding float + int

# [ ] HYPOTHESIS:

print(type(3.3))

print(type(3))

print(3.3 + 3)

Concept: Errors
More Errors!
SyntaxError & NameError

 SyntaxError - breaks code formatting rules of python

 NameError - object is not defined (can't be found)

Python has a specific grammar that it follows that is referred to as syntax.


The print function syntax rules for output of a single string include

 parentheses ( ) containing a string follow print (SyntaxError)

 strings have matching quotation marks (SyntaxError)

 print is lowercase and correctly spelled (NameError)

Failure to follow any of these rules results in a SyntaxError or NameError when


the code is run

Example
SyntaxError

 Improperly formatted string (quotes don't match) that results in a SyntaxError

# [ ] review and run the code for properly and improperly


formatted print statement

print("Hi!")

## improper format - non matching quotes

print('I like the morning")

 Note that the "prin" misspelling below results in a NameError

# [ ] review and run the code

prin('hi')

 EOF = "end of file" found in code below

 Python went to the end of the file looking for, but not finding, a closing parenthesis

# [ ] review and run the code missing the closing parenthesis

print("where are my socks?"


 In code below: a parenthesis inside quotations will be seen a part of a string and not as a
parenthesis

# { ] review and run the code

print("my socks are in the wrong bin)"

Task 4
Fix Errors
Tip: explaining errors to a partner often reveals a solution (works even if explaining
error to a pencil)

# [ ] repair the syntax error

print('my socks do not match")

# [ ] repair the NameError

pront("my socks match now")

# [ ] repair the syntax error

print"Save the notebook frequently")

# [ ] repair the NameError

student_name = "Alton"

print(STUDENT_NAME)

# [ ] repair the TypeError

total = 3

print(total + " students are signed up for tutoring")

A parenthesis inside quotations will be seen a part of a string and not as a


parenthesis

Concept: Character Art


Creating ASCII Character Art
Extra Activity
print() character art
print() output to the console can create character art in the forms of pictures and
stylized text. Below we show how to create a stylized letter "A"

# the letter 'A'

print(" *")

print(" * *")

print(" *****")

print(" * *")

print("* *")

print()

Extra Task
 create the flying bird in character art in the Code cell below

_ _

\ /

\ . . /

# create # [ ] flying bird character art

Extra Task cont...


 create the capital letter "E" in character art in the Code cell below

# [ ] capital letter "E" character art


Concept: user input
input()

get information from users with input()


the input() function prompts the user to supply data returning that data as a string

Example
# review and run code - enter a small integer in the text box

print("enter a small int: ")

small_int = input()

print("small int: ")

print(small_int)

Task 1
storing input in a variable

 [ ] create code to store input in student_name variable


an input box should when run

 [ ] type a name in the input box and press Enter

 [ ] determine the type() of student_name

# [ ] get input for the variable student_name

# [ ] determine the type of student_name

Task 1 continued...
note: input() returns a string (type = str) regardless of entry

 if a string is entered input() returns a string

 if a number is entered input() returns a string


 [ ] determine the type() of input below by entering
 a name

 an integer (whole number no decimal)

 a float a number with a decimal point

# [ ] run cell several times entering a name a int number and


a float number after adding code below

print("enter a name or number")

test_input = input()

# [ ] insert code below to check the type of test_input

Concept: input() prompts


user prompts using input()
the input() function has an optional string argument which displays the string
intended to inform a user what to enter
input() works similar to print() in the way it displays arguments as output

Example
student_name = input("enter the student name: ")

print("Hi " + student_name)

Task 2
prompting the user for input

 [ ] create a variable named city to store input, add a prompt for the name of a city

 [ ] print "the city name is " followed by the value stored in city

# [ ] get user input for a city name in the variable named


city

# [ ] print the city name

Task 2 cont...
multiple prompts for user input
often programs need information on multiple items

 [ ] create variables to store input: name, age, get_mail

 [ ] create prompts for name, age and yes/no to being on an email list

 [ ] print description + input values

example print output:


name = Alton
age = 17
wants email = yes

tip: with multiple input statements, after each prompt, click 'in' the input box to
continue entering input

# [ ]create variables to store input: name, age, get_mail with


prompts

# for name, age and yes/no to being on an email list

# [ ] print a description + variable value for each variable

Comma separated string printing


Concept: print formatting

using comma print formatting with strings


Python provides several methods of formatting strings in the print() function
beyond string addition

The print() function supports using commas to combine strings for output
by comma separating strings print() will output each string separated with a space
by default

comma formatted print()

 [ ] print 3 strings on the same line using commas inside the print() function

Example
# review and run code
name = "Colette"

# string addition

print("Hello " + name + "!")

# comma separation formatting

print("Hello to",name,"who is from the city")

Task 1
print 3 strings on the same line using commas inside the print() function

# [ ] print 3 strings on the same line using commas inside the


print() function

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy