print("Hello World!")
print("The Sky is blue.")
user_input = input("Enter something here: ")
print("You entered:", user_input)
Booleans are used in computer logic. It is a type that is evaluated as either True
or False
. The keywords and
, or
, not
are used to evalaute logical expressions, similar to those you'll find in a discrete math class.
True
True and False
False or True
(not False and not True) or (False or True)
Same thing can be used with 0's and 1's where 0 is False and 1 is True.
0 and 1
The function type()
will evaluate the parameter and determine the type of the input. We discussed types last week; some the more common ones are strings (str
), integers (int
), and floats (float
).
Make sure what is going in the code below:
a = "Hello World!"
b = 24892
c = 234.83
d = "24"+str(3)
e = 24 + 1.4
#################
guess_a = input("What type is a? ")
if guess_a == 'str' or guess_a == 'string' or guess_a == 'String':
print("You are right!\n")
else:
print("You are wrong. The type of a is",type(a).__name__,"\n")
guess_b = input("What type is b? ")
if guess_b == 'int' or guess_b == 'integer' or guess_b == 'Integer':
print("You are right!\n")
else:
print("You are wrong. The type of b is",type(b).__name__,"\n")
guess_c = input("What type is c? ")
if guess_c == 'float' or guess_c == 'Float':
print("You are right!\n")
else:
print("You are wrong. The type of c is",type(c).__name__,"\n")
guess_d = input("What type is d? ")
if guess_d == 'str' or guess_d == 'string' or guess_d == 'String':
print("You are right!\n")
else:
print("You are wrong. The type of d is",type(d).__name__,"\n")
guess_e = input("What type is e? ")
if guess_e == 'float' or guess_e == 'Float':
print("You are right!\n")
else:
print("You are wrong. The type of e is",type(e).__name__,"\n")
(again, adapted from Tanya Amert's slides)
A list
is a collection of objects. These can by anything including other list
s's (called nested). You can store a list
in a variable.
myList = ["apple", 42, 3.14]
myList
yourList = [7, 'a', myList]
yourList
To access or modify an elemt of a list, use []
. The first element's index is 0 and increments from there.
# What do you think this will return?
myList[0]
To modify the list, we can store a value in the list:
myList[0] = "banana"
myList
myList[-1]
myList[-1] = 'what'
myList
To access a range of elements, use a colon. If you include numbers, those are the start (inclusive) and end (exclusive).
myList[:1]
myList[1:]
anotherList = [0,1,2,3,4,5,6,7,8,9]
# What will show here?
anotherList[3:8]
You can add two lists by using the +
sign.
list1 = ['a','b','c','d','e']
list2 = ['t','u','v','w','x','y','z']
list3 = list1 + list2
list3
To add a single element at the end, use the list method append()
.
print(list1)
list1.append('f')
print(list1)
user_word = input("Enter a word: ")
print(user_word[0])
print(user_word[1])
print(user_word[2])
print(user_word[3])
To accomplish this task, we can find the length of the word using the len
function.
user_word = input("Enter a word: ")
if len(user_word) == 1:
print(user_word[0])
elif len(user_word) == 2:
print(user_word[0])
print(user_word[1])
elif len(user_word) == 3:
print(user_word[0])
print(user_word[1])
print(user_word[2])
elif len(user_word) == 4:
print(user_word[0])
print(user_word[1])
print(user_word[2])
print(user_word[3])
This is really long, especially if we don't know how long of a word the user will input. This is only one case of many where we want to use loops.
The for
keyword lets us loop over each element in an iterable. The variable between for
and in
is up to you and is assigned to each element (in this case, a letter in the string) one after another. We can loop over variables as well, as long its an iterable in that there is some mechanism so that we can go 'step through' the variable.
# THE FOR LOOP (for-each)
user_word = input("Enter a word: ")
for letter in user_word:
print(letter)
for i in 2:
print(i)
Python also provides the function range
which comes in handy when we want specific numbers.
range(5)
range(2,5)
range(1,10,1)
range(0,10,2)
Putting what we've learned together, we can do something like:
myList = ["apple","banana","orange"]
for item in range(len(myList)):
print("the fruit at index",item,"is",myList[item])
Sometimes you want to repeat something until a certain event. For example, we might want to echo a user until they type a specific word.
# initializing
response = ""
while response != "stop":
response = input("Please enter a word, or 'stop' to quit: ")
print("You said:",response)
# What's going wrong here
num = 1
while num <= 0:
num = num+1
print(num)
If you ever run into an infinite loop (usually you'll be able to detect this if your program is taking a long time to run) then just hit ctrl+C
to cancel whatever that is going on.
# Some more practice
num = 1
while num <= 10:
print(num * num)
num = num + 1 # much better
We've already seen a bunch of built in functions, such as int
, str
, input
, range
, len
, etc. We also know about append
when working with lists.
We can create our own function using the def
keyword.
By convention, function names in Python should start with lowercase letters.
def addFunction(a,b):
print(a+b)
addFunction(8,10)
def sayHello():
print("Hello")
sayHello()
If your function only prints, you can't expect to call it and use it in other expressions.
addFunction(1,2) + addFunction(3,4) # We want to see (1+2) + (3+4)
This is when we use the return
keyword to actually return that value. Note that this won't output anything to the screen, but instead will return that result. Lets rewrite our addFunction
method and see if we can evaluate multiple of them.
def addFunction(a,b):
return a+b
addFunction(1,2) + addFunction(3,4)
Python as a variety of built-in modules, which you can use via the import
keyword.
For example, the math
module allows us to use functions like sqrt
to take the square root of numbers.
To call them, we use modulename.methodname
.
import math
math.sqrt(4)
math.sin(math.pi) # numerical evaluations usually comes with errors; in this case e-16 is about 0
For external packages, you'll have to download them from an outside source. A few useful packages are