User Input in Python
In a Python command line application you can display information to the user using the print() function:
name = "Roger"
print(name)
We can also accept input from the user, using input():
print('What is your age?')
age = input()
print('Your age is ' + age)
This approach gets input at runtime, meaning the program will stop execution and will wait until the user types something and presses the enter key.
You can also do more complex input processing and accept input at program invocation time, and we'll see how to do that later on.
This works for command line applications. Other kinds of applications will need a different way of accepting input.
Control Statements in Python
When you're dealing with booleans, and expressions that return a boolean in particular, we can make decisions and take different roads depending on their True or False values.
In Python we do so using the if statement:
condition = True
if condition == True:
# do something
When the condition test resolves to True, like in the above case, its block gets executed.
What is a block? A block is that part that is indented one level (4 spaces usually) on the right:
condition = True
if condition == True:
print("The condition")
print("was true")
The block can be formed by a single line, or multiple lines as well, and it ends when you move back to the previous indentation level:
condition = True
if condition == True:
print("The condition")
print("was true")
print("Outside of the if")
In combination with if you can have an else block that's executed if the condition test of if results to False:
condition = True
if condition == True:
print("The condition")
print("was True")
else:
print("The condition")
print("was False")
And you can have different linked if checks with elif that's executed if the previous check was False:
condition = True
name = "Roger"
if condition == True:
print("The condition")
print("was True")
elif name == "Roger":
print("Hello Roger")
else:
print("The condition")
print("was False")
The second block in this case is executed if condition is False, and the name variable value is "Roger".
In a if statement you can have just one if and else check, but multiple series of elif checks:
condition = True
name = "Roger"
if condition == True:
print("The condition")
print("was True")
elif name == "Roger":
print("Hello Roger")
elif name == "Syd":
print("Hello Syd")
elif name == "Flavio":
print("Hello Flavio")
else:
print("The condition")
print("was False")
if and else can also be used in an inline format, which lets us return one value or another based on a condition.
Example:
a = 2
result = 2 if a == 0 else 3
print(result) # 3
Lists in Python
Lists are an essential Python data structure.
The allow you to group together multiple values and reference them all with a common name.
For example:
dogs = ["Roger", "Syd"]
A list can hold values of different types:
items = ["Roger", 1, "Syd", True]
You can check if an item is contained in a list with the in operator:
print("Roger" in items) # True
A list can also be defined as empty:
items = []
You can reference the items in a list by their index, starting from zero:
items[0] # "Roger"
items[1] # 1
items[3] # True
Using the same notation you can change the value stored at a specific index:
items[0] = "Roger"
You can also use the index() method:
items.index(0) # "Roger"
items.index(1) # 1
As with strings, using a negative index will start searching from the end:
items[-1] # True
You can also extract a part of a list, using slices:
items[0:2] # ["Roger", 1]
items[2:] # ["Syd", True]
Get the number of items contained in a list using the len() global function, the same we used to get the length of a string:
len(items) #4
You can add items to the list by using a list append() method:
items.append("Test")
or the extend() method:
items.extend(["Test"])
You can also use the += operator:
items += ["Test"]
# items is ['Roger', 1, 'Syd', True, 'Test']
Tip: with extend() or += don't forget the square brackets. Don't do items += "Test" or items.extend("Test") or Python will add 4 individual characters to the list, resulting in ['Roger', 1, 'Syd', True, 'T', 'e', 's', 't']
Remove an item using the remove() method:
items.remove("Test")
You can add multiple elements using
items += ["Test1", "Test2"]
#or
items.extend(["Test1", "Test2"])
These append the item to the end of the list.
To add an item in the middle of a list, at a specific index, use the insert() method:
items.insert("Test", 1) # add "Test" at index 1
To add multiple items at a specific index, you need to use slices:
items[1:1] = ["Test1", "Test2"]
Sort a list using the sort() method:
items.sort()
Tip: sort() will only work if the list holds values that can be compared. Strings and integers for example can't be compared, and you'll get an error like TypeError: '<' not supported between instances of 'int' and 'str' if you try.
The sort() methods orders uppercase letters first, then lowercase letters. To fix this, use:
items.sort(key=str.lower)
instead.
Sorting modifies the original list content. To avoid that, you can copy the list content using
itemscopy = items[:]
or use the sorted() global function:
print(sorted(items, key=str.lower))
that will return a new list, sorted, instead of modifying the original list.
领英推荐
Tuples in Python
Tuples are another fundamental Python data structure.
They allow you to create immutable groups of objects. This means that once a tuple is created, it can't be modified. You can't add or remove items.
They are created in a way similar to lists, but using parentheses instead of square brackets:
names = ("Roger", "Syd")
A tuple is ordered, like a list, so you can get its values by referencing an index value:
names[0] # "Roger"
names[1] # "Syd"
You can also use the index() method:
names.index('Roger') # 0
names.index('Syd') # 1
As with strings and lists, using a negative index will start searching from the end:
names[-1] # True
You can count the items in a tuple with the len() function:
len(names) # 2
You can check if an item is contained in a tuple with the in operator:
print("Roger" in names) # True
You can also extract a part of a tuple, using slices:
names[0:2] # ('Roger', 'Syd')
names[1:] # ('Syd',)
Get the number of items in a tuple using the len() global function, the same we used to get the length of a string:
len(names) #2
You can create a sorted version of a tuple using the sorted() global function:
sorted(names)
You can create a new tuple from existing tuples using the + operator:
newTuple = names + ("Vanille", "Tina")
Dictionaries in Python
Dictionaries are a very important Python data structure.
While lists allow you to create collections of values, dictionaries allow you to create collections of key / value pairs.
Here is a dictionary example with one key/value pair:
dog = { 'name': 'Roger' }
The key can be any immutable value like a string, a number or a tuple. The value can be anything you want.
A dictionary can contain multiple key/value pairs:
dog = { 'name': 'Roger', 'age': 8 }
You can access individual key values using this notation:
dog['name'] # 'Roger'
dog['age'] # 8
Using the same notation you can change the value stored at a specific index:
dog['name'] = 'Syd'
And another way is using the get() method, which has an option to add a default value:
dog.get('name') # 'Roger'
dog.get('test', 'default') # 'default'
The pop() method retrieves the value of a key, and subsequently deletes the item from the dictionary:
dog.pop('name') # 'Roger'
The popitem() method retrieves and removes the last key/value pair inserted into the dictionary:
dog.popitem()
You can check if a key is contained into a dictionary with the in operator:
'name' in dog # True
Get a list with the keys in a dictionary using the keys() method, passing its result to the list() constructor:
list(dog.keys()) # ['name', 'age']
Get the values using the values() method, and the key/value pairs tuples using the items() method:
print(list(dog.values()))
# ['Roger', 8]
print(list(dog.items()))
# [('name', 'Roger'), ('age', 8)]
Get a dictionary length using the len() global function, the same we used to get the length of a string or the items in a list:
len(dog) #2
You can add a new key/value pair to the dictionary in this way:
dog['favorite food'] = 'Meat'
You can remove a key/value pair from a dictionary using the del statement:
del dog['favorite food']
To copy a dictionary, use the copy() method:
dogCopy = dog.copy()
Sets in Python
Sets are another important Python data structure.
We can say they work like tuples, but they are not ordered, and they are mutable.
Or we can say they work like dictionaries, but they don't have keys.
They also have an immutable version, called frozenset.
You can create a set using this syntax:
names = {"Roger", "Syd"}
Sets work well when you think about them as mathematical sets.
You can intersect two sets:
set1 = {"Roger", "Syd"}
set2 = {"Roger"}
intersect = set1 & set2 #{'Roger'}
You can create a union of two sets:
set1 = {"Roger", "Syd"}
set2 = {"Luna"}
union = set1 | set2
#{'Syd', 'Luna', 'Roger'}
You can get the difference between two sets:
set1 = {"Roger", "Syd"}
set2 = {"Roger"}
difference = set1 - set2 #{'Syd'}
You can check if a set is a superset of another (and of course if a set is a subset of another):
set1 = {"Roger", "Syd"}
set2 = {"Roger"}
isSuperset = set1 > set2 # True
You can count the items in a set with the len() global function:
names = {"Roger", "Syd"}
len(names) # 2
You can get a list from the items in a set by passing the set to the list() constructor:
names = {"Roger", "Syd"}
list(names) #['Syd', 'Roger']
You can check if an item is contained in a set with the in operator:
print("Roger" in names) # True