Python Handout Comments Variables and String
Python Handout Comments Variables and String
01. Variables
Comments
● # single line comment
● “”” ‘’’ multiline comment
● Why do we add comments to the program
○ Make the code more readable and easy to understand.
Variables
● What is a variable
○ A memory location used to store a value, and the stored value can be changed
during the execution of the program.
● Naming conventions
○ Case sensitive
○ Cant start with a number
○ Don’t use keywords such as if else while
● Assign values
○ a = 1
○ y = 2.5
○ name = ‘John’
○ ‘’ and “” are the same for strings
○ is_cool = True
● Multiple assignments
○ x, y, name, is_cool = (1, 2.5, ‘John’, true)
● Basic Math
○ a=x+y
● Casting
○ x = str(x)
○ y = int(y)
○ z = float(y)
● print(type(z), z) how to check the data type
02. Strings
What are Strings?
Strings in python are surrounded by either single or double quotation marks. Let's look at string
formatting and some string methods.
name = ‘John’
age = 20
Concatenate
● print(‘hello, my name is ‘ + name)
● print(‘hello, my name is ‘ + name + ‘ and I am ‘ + age) ERROR only string can be
concatenated, age is int
● print(‘hello, my name is ‘ + name + ‘ and I am ‘ + str(age)) #casting to str
Positional Arguments
● print(‘my name is {name} and I am {age}’.format(name=name,age=age))
● {name} and {age} are place holders
String Methods
s = ‘hello world’
● Capitalize String
○ print(s.capitalize()) # Hello world
● Make all Uppercase
○ print(s.upper()) # HELLO WORLD
● Make all lower
○ print(s.lower()) # hello world
● Swap Case
○ print(s.swapcase()) # HELLO WORLD
● Get length
○ Can be used on strings, list, and any other types and will get the length or
amount of characters in this case
○ print(len(s)) # 11
● Replace
○ print(s.replace(‘world’,’everyone’) #hello everyone
● Count
○ sub = ‘h’
○ print(s.count(sub)) # 1 this is case sensitive
● Starts with
○ print(s.startswith(‘hello’)) # True this is case sensitive
● Ends with
○ print(s.endswith(‘d’)) # True case sensitive
● Split
○ Take the string and turns it into a String, basically it’s an array, and it will have all
the words in the list
○ word_list = s.split()
○ print(str(word_list)) # ['hello', 'world']
● Find
○ Find function will find the position of a character(s)
○ print(s.find(‘e’)) # 1
● Is All alphanumeric
○ print(s.isalnum()) # False
● Is all alphabetic
○ print(s.isaslpha()) # False because of the space
● Is all numeric
○ print(s.isnumeric()) # False