Learn Python Quickly Flashcards
learn python 3.8 quickly
exit()
exited with the quit command or depending on the version you are running quit()
help()
all the various commands
> > >
The primary prompt. Python is waiting for a command when you see this.
…
Python is waiting for your input, but this means it’s the second line of input
IDE
Most programming done in the IDE (integrated development environment). They auto complete commands, phrases, and functions, track bugs, highlight syntax errors and overall make programming and seeing the output of your programs easier.
Book recommends which IDEs?
PyCharm, Spyder, PyDev, Idle, and Wing.
writing comments in python
use # at the start of a line or
Triple single quotes at the start and end of your multi-line statement:
‘’’
comment 1
2
3
‘’’
variables: how to assign string variables?
use “
stuff = “cloudy”
Python Operators
- Operators are symbols that perform functions and are used to manipulate data in different ways
Example operators
Operators:
- assignment is the = for assigning variables
- R = 12
- S = 5
- T = S
- ^^ assigning variable to a variable
- Addition: +
- R + S = 17
- Subtraction: -
- R - S = 7
- Multiplication: *
R * S = 60 - Division: /
- R / S = 2.4
- Floor division: //
- This divides and then rounds down to the nearest whole number
- R // S = 2
- Modulus (mod): %
- Modulus operator produces the remainder of the division operation
- R % S = 2
- Exponent: **
- R ** S is R to the S power
- R ** S = 248,832
R = 12
S = 5
- Floor division:
//
- This divides and then rounds down to the nearest whole number
- R // S = 2
R = 12
S = 5
- Modulus (mod):
%
- Modulus operator produces the remainder of the division operation
- R % S = 2
R = 12
S = 5
- Exponent:
**
- R ** S is R to the S power
- R ** S = 248,832
R = 12
S = 5
Can you combine operators?
Yes. Specifically this way:
Short handing R = R * 2
shrinks to R * = 2
Same for the other operators
Variables are stored as what primary Data Types in Python?
Primary Data types:
- integers
- floats
- strings
What are the the different data structures used for the primary data type variables?
- lists
- tuples
- dictionaries
Integers
- same as math class
- whole numbers
- positive or negative
- assigns normally to a variable
floats
- Numbers that contain decimal parts
- positive or negative
- assigns normally to a variable
strings
- text data
- assign them using “ “ or ‘ ‘
- string_1 = “string”
What order should nested quotes be used inside strings?
- Use “ “ first, then ‘ ‘ inside the quoted space
How are numbers treated in a quote do when assigned to a variable?
A = “12”
Python sees them as a string.
String Manipulation
- you can combine them the same way we combine numbers:
str_1 = “Words “
str_2= “and “
str_3= “more words.”
str_4 = str_1 + str_2 + str_3
print(str_4)
Running this =
Words and more words.
changing letter case using built in functions. Explain upper and lower case usage with string variables.
Using the following functions will change the letter case to upper or lower:
my_up_string = “all MY letters”.upper()
my_dn_string2 = “ all MY letters”.lower()
print(my_up_string + my_dn_string2)
running this =
ALL MY LETTERS all my letters
String formatting example using %
Using mod operator % on strings allows you to specify values / variables you would like to insert into a string.
string = “With the mod op, you can add %s, integers like %d, or even floats like %2.1f.”%(“strings”, 25, 12.34)
print (string)
running this =
With the mod op, you can add strings, integers like 25, or even floats like 12.3.
where every % gets its variable / value piped in from the entries at the end of the variable assignment line. special notes here:
- %s is a string
- %d is an integer (digit?)
- %f is a float, but in this instance we used %2.1f
- %2.1f took the 12.34 and read it as needing 2 digits before the decimal place and one digit after the decimal place resulting in 12.3
Automatic formatting example using {}
There’s more on this later in the chapter, but using the format function for strings instead of using the modulus operator.
- Inside the brackets goes:
- data type tag
- position of the value in the collection of values you want in that spot
- it is possible to leave the brackets blank. Python will automatically fill them in from left to right with the values listed left to right.
“The string you want to format {} “.format(values you want to insert)
- curly braces denote the location where you want to insert the value.
- to insert multiple values, you need to create multiple braces then separate the values with commas
string = “with the mod operator, you can add {0:s}, integers like {1:d}, or even floats like {2:2.2f}”
print (string.format(“strings”, 25, 12.34))
will print =
with the mod operator, you can add strings, integers like 25, or even floats like 12.3
Python starts with 0 or 1?
Unlike some other programming languages, python is a zero-based system when it comes to positions. First position is ZERO, second is ONE.
what is Type Casting used for?
Converting data from one type to another type.
e.g. String to Integer
int()
convert to integer
- going FLOAT to INTEGER means it will drop the decimal values and always round down to the whole number value
- strings to integers obviously need to be numbers
float()
convert to float
strings to floats obviously need to be numbers.
str()
convert to string
basically anything can become a string.
Data Structures?
How data is stored.
what are the different data structures in python?
Lists
Tuples
Dictionaries
Lists
Data structure
Collections of data
quick and easy storage and retrieval of items
Functionally this is done by saving the list as a variable that’s declared as a list
List: syntax example of a list
Fruits = [“apple”,”pear”,”coconut”]
List: Can you declare an empty list to append items to later?
yes
Fruits = []
append() to add more later
List: How do you access a specific item in the list?
when the list is:
Fruits = [“apple”,”pear”,”coconut”]
then the first item is:
apple = fruits[0]
List: call something from the end or second to last of the list
Fruits = [“apple”,”pear”,”coconut”]
last = Fruits[-1]
seclast = Fruits[-2]
print(last)
print(seclast)
Using slicing.
a[-1] # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything except the last two items
List: How do you call multiple items from a list?
Using slicing.
where a = a list
a[start:stop:step]
start through not past stop, by step
a[start:stop]
items start through stop-1
a[1:5], will print items 1 through 4
a[start:]
items start through the rest of the array
a[:stop]
items from the beginning through stop-1
a[:]
a copy of the whole array
List: Reversing the order of items in a list
a[::-1] # all items in the array, reversed
a[1::-1] # the first two items, reversed
a[:-3:-1] # the last two items, reversed
a[-3::-1] # everything except the last two items, reversed
List: in what ways are lists modified?
add, remove, and values can be altered
List: How to append lists?
list_to_append.append(value)
where
value = item number (starting at 0)
List: How to remove items from lists?
list_to_append.remove(value)
where
value = item number (starting at 0)
List: How to remove items from lists?
To remove a single entry:
list_to_append.remove(value)
where
value = item number (starting at 0)
to remove multiple entries at once:
del List_Name[2:4]
which will delete everything from the 3rd item through the 4th item
list: how to edit the 2nd through the 4th items in a list
Fruits[1:4] = [“pear1”,”coconut1”,”riot1”]
list: how to insert items into a list
list_name.insert(Where,Inserted_Item)
a.insert(1,”outland”)
Inserts outland string before list item 1, but after list item 0 and pushing everything else after it down the list
Whats the difference between lists and arrays?
Lists are basically the same as other arrays outside of python.
Python do have arrays too, they are more functional than lists if you want to say divide everything in the array by 4. Doing this with lists will result in an error.
Tuples: What are tuples?
Similar to lists, but can’t be modified
Tuples: when would Tuples be beneficial?
Whenever you have an unchanging list of items. Examples include the days of the week, Months, etc.
Tuples: How do you define Tuples in py?
MyTuple = (“Mon”,”Tue”,”Wed”)
Using parenthesis instead of brackets.
Tuples: How are Tuples called / accessed in py?
Same as lists
Dictionaries: what are they?
Dictionaries hold data that can be retrieved with reference items or keys
They contain pairs of keys and values associated with those keys
Dictionaries: Can you have 1 key open multiple box
No that would be problematic. e.g. 2 keys both named cyfer1
Dictionaries: How do you create a key in py?
Use curly braces containing the key on the left side and the value on the right side.
separated by a colon.
dict_example = {“key0”:39, “key1”:50}
or by using the dict() method
dict_example2 = dict(key0 = 39, key1 = 21)
Dictionaries: How do you access the items in one?
dictionary[‘key’]
(Bracket, single quote surrounding key value)
example:
dict_example2 = dict(key0 = 39, key1 = 21)
dict_example2[‘key0’]
would resolve to 39
Dictionaries: Can you define an empty one? If so how?
dict_example2 = {}
To add data to the dictionary, just assign a value:
dict_example2 [“key1”] = 60
Dictionaries: how do you add entries?
To add data to the dictionary, just assign a value to key
dict_example2 [‘key1’] = 60
Dictionaries: how do you remove entries?
del dict_example2[‘key0’]
Would remove the value associated to key0
Inputs: How do you solicit and accept input from the user?
the input() function
similar to read -p command in bash
Inputs: How to store a variable using input()
food = input(“What food do you want?:\n”)
Variables: Best way to print two variables using f-string formatting?
(f-string formatting is available in Python 3.6)
example:
name = “fine”
score = 20
print(f’Grand total for {name} is {score}’)
Print: How can you print out less wide blocks of text without using /n?
example:
use triple single quotes and enter between lines to space it however you wish:
longstring = ‘'’Using triple quotes will allow us to
divid our statements onto multiple lines This makes
it easier to read As you can see this shrinks up the
output…’’’
print(f’{longstring}’)
Print: how to use raw string formatter as an escape on an entire string?
escape character r or R
example:
This applies to the entire string:
print(r”hey hey \t we’re the monkeys.”)
print(R”hey hey \t we’re the monkeys.”)
normal print
print(“hey hey \t we’re the monkeys.”)
Print: how to avoid a long string from running across the screen?
Use triple ‘ to surround the string and apply normal text editing with new lines and tabs.
example:
print(‘’’hey there
How’s it going?
Oh that’s good!‘’’
Delete
Print: how do you print more than one string in a print or input function?
You can using the format function.
Example:
name = “B”
nametwo = “john”
foodtwo = input(“What food does {0} want and what kind does {1} want?:\n”.format(name,nametwo))
Print: how to use an escape character on a specific item WITHOUT using raw string formatter on the entire string?
example:
use \
print(“hey hey \\t we’re the monkeys.”)