Python, Day 2
IWKS 2300
Fall 2019
John K. Bennett
2
Naming Variables (Review …)Which of the following are valid variable names?
1. MarvelMovies2. Avengers_Infinity_War3. 2019_Endgame4. Black Panther 5. _3_Iron_Man6. thor
3
Naming Variables (Review …)Which of the following are valid variable names?
1. MarvelMovies2. Avengers_Infinity_War3. 2019_Endgame4. Black Panther 5. _3_Iron_Man6. thor
Answer: 1, 2, 5, and 6 are valid. 3 is not valid (starts with a digit), 4 is not
valid (it contains a space).
Operators (Review …)>>> (4 + 3) * 6
>>> 4**3
>>> 33 / 2
>>> 33 // 2
>>> 74 % 8
Note: The >>> symbol is used to indicate lines typed at IDLE. You do not need to type >>> yourself
Operators (Review …)>>> (4 + 3) * 642>>> 4**3
>>> 33 / 2
>>> 33 // 2
>>> 74 % 8
Note: The >>> symbol is used to indicate lines typed at IDLE. No need to type >>> yourself
Operators (Review …)>>> (4 + 3) * 642>>> 4**364>>> 33 / 2
>>> 33 // 2
>>> 74 % 8
Note: The >>> symbol is used to indicate lines typed at IDLE. No need to type >>> yourself
Operators (Review …)>>> (4 + 3) * 642>>> 4**364>>> 33 / 216.5>>> 33 // 2
>>> 74 % 8
Note: The >>> symbol is used to indicate lines typed at IDLE. No need to type >>> yourself
Operators (Review …)>>> (4 + 3) * 642>>> 4**364>>> 33 / 216.5>>> 33 // 216>>> 74 % 8
Note: The >>> symbol is used to indicate lines typed at IDLE. No need to type >>> yourself
Operators (Review …)>>> (4 + 3) * 642>>> 4**364>>> 33 / 216.5>>> 33 // 216>>> 74 % 82
Note: The >>> symbol is used to indicate lines typed at IDLE. No need to type >>> yourself
User Input
The input function:
takes a prompt string
returns the string the user types.
name = input("What is your name?")
print("Nice to meet you", name)
Console Input / Output
You already know about print()
How can we provide input to a program? Use input ()
a = input ("Enter a number: ")
print (a)
Note: a is entered as a string. If we wanted it to be an
integer, we can perform a "cast," as follows:
a = input ("Enter a number: ")
print ("a has the string value: " + a)
b = int (a)
Print ("b has the integer value: " + str (b))
print ("a is a " + str (type (a)))
print ("b is a " + str (type (b)))
CommentsComments are a way for programmers to leave notes for others (or for yourself!) in their code.
In Python, you can write comments using the # symbol. Anything from # to the end of the line will be ignored in Python.
# This defines number of cats and sets the value to 10num_cats = 10
num_cats = num_cats +1 # add one to num_cats
Many/Most Python programmers start comments with ##
CommentsComments are a way of telling others (and yourself) what is
going on in your program. Example:
"""
This program demonstrates input().
John K. Bennett
August 22, 2019
"""
## Enter the first number
a = input ("Enter a number: ")
print ("a has the string value: " + a)
b = int (a) ## input a second line
print ("b has the integer value: " + str (b))
print ("a is a " + str (type (a)))
print ("b is a " + str (type (b)))
Data TypesWe've been using two data types: integers and strings. Python provides a way to change between these two types:
Call int on a string to convert to an integer
an_integer = int("42")
Call str on an integer to convert to a string
a_string = str(42)
Data Types (Continued …)
Can you add an integer to a string?
Try in Python IDLE and see what happens.
For example:
"26" + 26
More on Data TypesFloats are another data type we will need. You can switch between float, int and strings
Call float on a string to convert to a float
a_float = float("42")
Call str on a float to convert to a string
float_to_string = str(4.2)
More on Data Types (Continued …)What happens when we try the following?
Call float on a string such as:
try_float = float("forty-two")
Answer: This will cause an error."forty-two", is not a number!
More on Data Types (Continued …)What happens when we try the following?
Call float on a string such as:
try_float = float("forty-two")
Boolean data
A boolean is a type of data that can be one of two values:True or False
my_bool = True
print(my_bool)
True
The len FunctionThe len function takes a sequence (such as a string) and
returns its length. For example:
>>> len("Bob")
3
>>> len("Hello World!")
12
Note: The empty space within " " counts towards the length!
String Formatting
String formatting expressions can be used to print variables
in a more readable way.
Placeholders define the type of value that will be printed.
Object/variable is converted into the type printed (if needed).
%d%f
Substitute an integerSubstitute a floating point decimal
%s Substitute a string
String Formatting (Continued …)
What is the output of this code?
name = "Bob"
age = 22
bmi = 24.6 # Body Mass Index
print("%s is %d years old with a BMI of %f" %(name, age, bmi))
OutputBob is 22 years old with a BMI of 24.600000
Note: Using "%.2f" will result in only two decimal points.
F-strings (introduced in Python 3.6)
What is the output of this code?
name = "Bob"
age = 22
bmi = 24.6 # Body Mass Index
print(f"{name} is {age} years old with a BMI of {bmi}")
OutputBob is 22 years old with a BMI of 24.6
Note: more readable less prone to error!
Python SubstringsWhat does this code do?a = 'flimsy'b = 'miserable'c = b[0:1] + a[2:]print (c)
Python SubstringsWhat does this code do:a = 'flimsy'b = 'miserable'c = b[0:1] + a[2:]print (c)
It will output the string formed by the first character of miserable and the last four characters of flimsy:mimsy
Why does this code output "mimsy"?a = 'flimsy'b = 'miserable'c = b[0:1] + a[2:] print (c)
Because substring notation in Python starts with the character at the first index, and goes up to, but not including, the second index. If there is no second index, it goes to the end. If there is no first index, it starts from the beginning.What if we wanted to make the range inclusive?
Adding Strings in Python
a = 'see'b = 'you'c = 'later'
outstr = a + ' ' + b + ' ' cprint (outstr)
What happens?
Python Village ini3## Problem## Given: A string s of length at most 200 letters and four integers a, b, c and d## Return: The slice of this string from indices a through b and c through d (with
space in between), inclusively.## In other words, we should include elements s[b] and s[d] in our slice."""Sample DatasetHumptyDumptysatonawallHumptyDumptyhadagreatfallAlltheKingshorsesandalltheK
ingsmenCouldntputHumptyDumptyinhisplaceagain.22 27 97 102Sample OutputHumpty Dumpty"""
Looping Over a String in Python
s = 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTC'for ch in s:
print (ch)
What happens?
Python if Statement
s = 'AGCTTTTCATTCTGACTGCAACGGGCAATATGT'Acnt = 0for ch in s:
if ch == 'A':Acnt = Acnt + 1
print (Acnt)
What happens?
What If We Wanted to Test Two Things?
s = 'AGCTTTTCATTCTGACTGCAACGGGCAATATGT'Acnt = 0Ccnt = 0for ch in s:
if ch == 'A':Acnt =Acnt + 1
else:Ccnt += 1 ## this is the same as 'Ccnt = Ccnt + 1'
print (Acnt, Ccnt)
More Than Two?
if one:## do this if one is true
elif two:## do this if two is true
elif three:## do this if three is true
…else:
## do this one, two, & three are false
Do #2 and #3 over next week
http://lightbot.com/hour-of-code.html
http://lightbot.com/hour-of-code.html