Python Essentials: Part 1 - Module 2

¡Supera tus tareas y exámenes ahora con Quizwiz!

"Sep" keyword argument

(like separator) -specifies the value of the separator instead of using the print() functions default- a space. ex. print("My", "name", "is", "Monty", "Python.", sep="-") My-name-is-Monty-Python. - The print() function now uses a dash, instead of a space, to separate the outputted arguments. Note: the sep argument's value may be an empty string, too. -empty (sep="") outputs nothing- no space btwn arg.'s

//

*integer* divisional operator / also called floor division differs from the standard / operator because: - its result lacks the fractional part the point if absent (for division w/ ONLY integers) values right of point are = 0 ".0" (for div. w/ ANY floats) - ...so, the results are always rounded > rounded DOWN - The result of division with negative values results are rounded toward the lesser integer value (still rounded DOWN- keep in mind the lesser integer value appears larger when negative but it is not) - it conforms to the integer vs. float rule

Expression

A combination of values (or variables, operators, calls to functions) which evaluates to a value - formed when data & operators are connected together - simplest one is a literal itself

clarifying examples

ex 1. a = '1' b = "1" print(a + b) OUTPUT : 11 (just puts the variables together next to eachother- doesn't sum them, output "1+1", or actually add them together outputting "2" as tho they're integers ex 2. a = 6 b = 3 a /= 2 * b print(a) OUTPUT : 1.0 a /= 2 * (3) → a /= 6 → a = a/6 → a = (6) / 6 = 1.0 [it solved info after "=" first & then solved w/ shortcut]

What arguments does print() expect?

Any; able to operate with virtually all types of data offered by Python & have them successfully passed into print(), such as: strings, numbers, characters, logical values, objects

How NOT to divide

As you probably know, division by zero doesn't work Do not try to: - perform a division by zero - perform an integer division by zero - find a remainder of a division by zero

how do we code negative numbers in Python?

By adding a minus "-" You can write: -11111111, or -11_111_111 (positive signs "+" can be used too, but not necessary)

How does Python recognize integers?

it's simply a string of digits that make up the number - BUT you must not interject any characters that are not digits inside the number (negative integers exist: "-2") Python doesn't accept things like (prohibited X) : this: 11,111,111, or this: 11.111.111, or this: 11 111 111 - allows the *use of underscores in numeric literals* - so, can write the number either like this: 11111111, or *like that: 11_111_111* *Python 3.6 has introduced underscores in numeric literals, allowing for placing single underscores between digits and after base specifiers for improved readability. This feature is not available in older versions of Python*

Octal Number

literals- - If an integer number is preceded by an 0O or 0o prefix (zero-o), it will be treated as an octal value - the number must contain digits taken from the [0..7] range only ex. 0o123 is an octal number with a (decimal) value equal to 83 https://www.youtube.com/watch?v=FFDMzbrEXaE

Hexadecimal Number

literals- Such numbers should be preceded by the prefix 0x or 0X (zero-x) ex. 0x123 is a hexadecimal number with a (decimal) value equal to 291 https://www.youtube.com/watch?v=pg-HEGBpCQk

What value does the print() function return?

None. Its effect is enough

unary* operator

Operator with only 1 operand (binary has 2) - Minus operator may be used in a different (unary) way ex. print(-4 - 4) vs. print(*-1.1*) - (there is also a unary + operator > ex. print(+2) -> while syntactically correct, doesn't make much sense in use)

Ex. Solving simple math problems

Pythagorean theorem - solve for "c" a = 3.0 --> assign value 3.0 to a b = 4.0 --> assign value 4.0 to b c = (a ** 2 + b ** 2) ** 0.5 --> assign value (a^2+b^2)^(1/2) to c - [the ½ or .5 power represents square root] print("c =", c) --> OUTPUTS : c = 5.0

/

Python operator that performs mathematical operation of division The value in front of the slash is a dividend, the value behind the slash, a divisor = dividend / divisor - The result produced by the division operator is always a float, regardless of whether or not the result seems to be a float at first : 1 / 2, or looks like a pure integer: 2 / 1 - can pose a problem when you need an integer answer

*

Python operator that performs mathematical operation of multiplication

Rules for Use of Variables

Strict rules for giving a variable a name : - A legal identifier name must be a non-empty sequence of characters - name of the variable must be composed of upper-case or lower-case letters, digits, and the character _ (underscore) - the name of the variable must begin with a letter; the underscore character is a letter - upper- and lower-case letters are treated as different (a little differently than in the real world - Alice and ALICE are the same first names, but in Python they are two different variable names, and consequently, two different variables); - the name of the variable must not be any of Python's reserved words (the keywords - we'll explain more about this soon) - no spaces - DOES let you use not only Latin letters, but also characters specific to languages that use other alphabets - allowed to use as many variable declarations (that EXIST/ have been assigned a value) as you need to achieve your goal - preference- names that are too long or too short are not always more convenient - preference- lower case separated w/ underscores - preference- you can use mixed case (e.g., myVariable), but only in contexts where that's already the prevailing style, to retain backwards compatibility with the adopted convention

Replication Operator

The * (asterisk) sign, when applied to a string & number (or a number & string, as it REMAINS commutative in this position) replicating the string the same number of times specified by the number ex1. "James" * 3 OR 3 * "James" --> "JamesJamesJames" ex1. 5 * "2" OR "2" * 5 --> "22222" [ NOT 10 ! ] [a # <or= 0 produces an empty string]

2 types of numbers handled by modern computers?

The *loose* definitions and differentiations are : - *integers*: that is, those which are devoid of the fractional part - *floating-point* numbers (or simply *floats*), that contain (or are able to contain) the fractional part - the distinction is very important, and the boundary btwn. these two types of numbers is very strict - both differ significantly in how they're stored in a computer memory & in the range of acceptable values

-

The subtraction operator is obviously the - (minus) sign, although you should note that this operator also has another meaning - it can change sign of a # (unary)* - In subtracting applications, the minus operator expects two arguments: left (a minuend in arithmetic) & right (a subtrahend) - this operator is considered to be binary, like * + /

Remainder (modulo)

% ---> Try to think of it as of a slash (division operator) accompanied by two funny little circles - The result of the operator is a remainder left after the integer division ex. print(14 % 4) ---> 2 14 // 4 gives 3 → this is the integer quotient; 3 * 4 gives 12 → as a result of the quotient * the divisor 14 - 12 gives 2 → this is the remainder ex. print(2 % -4) --> -2 MY HYPOTHESIS : ( it seems to ME that whenever there is a modulo where the dividend (left) is smaller than the divisor (right).... - whenever BOTH integers are pos. or neg. in this operator (in this case) the one on the left of the % is the output (either - or + , depending) - whenever there's a negative integer (in this case), the two added together in left to right order is the output )

iteration

To repeat a section of code.

Snippet

a small region of re-uterm-51sable source code, machine code, or text - ordinarily, these are formally defined operative units to incorporate into larger programming modules

the None literal

a special literal that is a so-called NoneType object, and it is used to represent the absence of a value

Operator

a symbol of the programming language, which is able to operate on values & perform (mathematical) operations - ex. just as in arithmetic, the + (plus) sign is the operator which is able to add 2 #s, giving the result more ex.'s + , - , * , / , // , % , **

arguments

a value provided to a function when you call it - it is a function component placed inside parentheses; Python functions may accept any number of arguments - as many as necessary to perform their tasks depending on individual needs

** (double asterisk) sign

an exponentiation (power) operator ex. 2**3 = 2^3, 2 is the base, 3 is the exponent -pure text editors don't accept classic mathematical notation like superscripts to represent exponents, so Python uses ** instead - when both ** arguments are integers, the result is an integer, too; - when at least one ** argument is a float, the result is a float, too.

combining text and var's with +

can use the print() function and combine text and variables using the + operator to output strings and variables ex. var = "3.8.5" print("Python version: " + var) --> OUTPUT : Python version: 3.8.5

Literal

data whose values are determined by the literal itself ex. "123" is a literal: one hundred twenty-three; "c" isn't - use literals to encode data and to put them into your code -notations for representing some fixed values in code - two ex. types of literals: string & number (numeric) - Internally, in the computer's memory, these two values are stored in completely different ways: print("2") > the string exists as a series of letters print(2) > the number is converted into machine representation (a set of bits) - The print() function is able to show them both in a readable form (console outputs "2" for both) - If you encode a literal and place it inside Python code, the form of the literal determines the representation (type) Python will use to store it in the memory

keyword

define the language's syntax rules and structure, and they cannot be used as variable names

Binding of the operator

determines the order of computations performed by some operators with equal priority, put side by side in one expression. Most of Python's operators have left-sided binding, which means that the calculation of the expression is conducted from left to right: ex. 9 % 6 % 2 left --to--> right: 9 % 6 gives 3, & then 3 % 2 gives 1; left <--to-- right: right to left: 6 % 2 gives 0, & then 9 % 0 causes a fatal error > so this operator is left-side binding ex. print(2 ** 2 ** 3) The two possible results are: 2 ** 2 → 4; 4 ** 3 → 64 (left-binding) 2 ** 3 → 8; 2 ** 8 → 256 (right-binding) --> OUTPUT - *exponentiation* operator uses *right*-side binding

Assignment Operator

equal sign - can assign a new value to an already created variable: assigns the value of its right argument to the left, while the right argument may be an arbitrarily complex expression involving literals, operators and already defined variables Ex. var = 1 ----> "assign 1 to var" print(var) ----> outputs "1" var = var + 1 ----> assigns the same variable with the new value taken from the variable itself, + 1 print(var) OUTPUT : 1 2 - math would say no value may be equal to itself +1, but Python treats the sign = , not as "equal to", but as "assign a value" - so "var=var+1" would be read as : "take the current value of the variable var, add 1 to it and store the result in the variable var" Another Ex. var = 100 var = 200 + 300 print(var) OUTPUT : 500 -> var is created & assigned value of 100 Then, the same variable is assigned a new value: the result of adding 200 to 300, which is 500

*float() function

takes one argument (e.g., a string: float(string)) and tries to convert it into a float > if it fails, the whole program will fail too (there is a workaround for this situation, but we'll show you this a little later)

*int() function

takes one argument (e.g., a string: int(string)) and tries to convert it into an integer > if it fails, the whole program will fail too (there is a workaround for this situation, but we'll show you this a little later)

Concatenation Operator

the + operator used to "glue" (concatenate) 2 strings into one > string + string - can be used more than once in one expression (has left-side binding) - NOT commutative like in arithmetic : "ab" + "ba" ISN'T the same as "ba" + "ab" *NOTE: if you want the + sign to be a concatenator, not an adder, you must ensure that both its arguments are strings: mustn't MIX types!* (works for variables containing strings)

type

the characteristic of the numeric value which determines its kind, range, and application

Python's order of operations

the hierarchy of priorities - PUEMDASCE > nemonic (note: M and D include the remainder (modulo) and floor division operators at the same level of priority) (take "U" as Unary operators : +, -) (take A and S as the binary operators) (take "C" as Comparison operators : <, <=, >, >=) (take "E" as Equality operators : ==, !=)

binary system

the system computers use for storing numbers; they can perform any operation upon them system of numbers that employs 2 as the base. Therefore, a binary number is made up of 0s and 1s only, e.g., 1010 is 10 in decimal https://towardsdatascience.com/binary-hex-and-octal-in-python-20222488cee1

Ordinary Words vs Function Names

to distinguish ordinary words from function names, place a pair of empty parentheses after their names, even if the corresponding function wants one or more arguments

Coding Floats

used to record numbers that are very small (in the sense of their absolute value, which is close to zero) - Note: the fact that you've chosen one of the possible forms of coding float values doesn't mean that Python will present it the same way Python always chooses the more economical form of the #'s presentation, and you should take this into consideration when creating literals - may output in different notation than yours -literals- ex. INPUT : .0001 OUTPUT : 1.0E-4

Escape Character

- "Escape" means the series of characters in the string escapes for the moment (a very short moment) to introduce a special inclusion - "\" the backslash doesn't mean anything in itself, but is only a kind of announcement, that the *next character* after the backslash has a different meaning too - If you want to put just one backslash inside a string, don't forget its escaping nature - you have to double it ex. NOT ("\") --> THIS ("\\") outputs \ in console

***"End" keyword argument

- Determines the characters the print() function sends to the output once it reaches the end of its positional arguments - the empty (end="") negates pythons default new line based on position, must specify new line : \n - By default python's print() function ends with a newline, so, to print without newline, Python's print() function comes with a parameter called 'end'. Though the default value of this parameter is '\n', i.e. the new line character. You can end a print statement with any character/string using this parameter. -If the end argument has been set to nothing, the print() function outputs nothing too, once its positional arguments have been exhausted (note: no newlines sent to the output, just keeps them on the same line

Ints vs Floats

- The decimal point is essentially important in recognizing floating-point numbers in Python. ex. 4 vs. 4.0 / 4. Python sees them in a completely different way. 4 (integer number) whereas 4.0 (floating-point number) - the point is what makes the float - the letter "e" also makes a float

Keyword Arguments

- another mechanism for the passing of arguments - name stems from the fact that the meaning of these arguments is taken NOT from its location (position) but from the special word (keyword) used to identify them. - consists of 3 elements: - a keyword identifying the argument - an equal sign (=) - a value assigned to that argument - any keyword arguments have to be put after the last positional argument (this is very important) ex. line 1 > print("My name is", "Python.", end=" ") line 2 > print("Monty Python.") - In our ex. , we have made use of the end keyword argument, & set the value to a string containing 1 space - 2 kinds for different purposes : end & sep

input()

- built-in function that gets data from the console (user) and returns the same data to the running program - can manipulate the data, making the code truly interactive - as opposed to print(), it returns a very usable result - (Virtually all programs read and process data. A program which doesn't get a user's input is a deaf program) ex. print("Tell me anything...") anything = input() print("Hmm...", anything, "... Really?") > the input() function is invoked without arguments (this is the simplest way of using the function) *NOTE : you need to assign the result to a variable; this is crucial - missing out this step will cause the entered data to be lost* > the function will switch the console to input mode - then user can type > finishing off by hitting the Enter key; all the inputted data will be sent to your program through the function's result (stored in the assigned variable) > can use print() to output the data we get, with some additional remarks

*str() function

- can convert a number into a string - makes it so you can concatenate a string and a number, after also converting the number to string form

Shortcut operators

- compound assignment operators If op is a two-argument operator (this is a very important condition) and the operator is used in the following context: variable = variable op expression It can be simplified and shown as follows: variable op= expression Operators like x *=y which means x = x * y. ex. You may use an expression like this if you can't fall asleep and you're trying to deal with it using some good, old-fashioned methods: sheep = sheep + 1 --> (in shorthand) --> sheep += 1

Scientific Notation

- for numbers either very large or very small - ex. of letter "e" : speed of light, expressed in m/sec. Written directly: 300000000 / Abbreviated: 3 x 10^8 - scientific notation in Python: 3E8 -literals- "E", or "e", comes from the word exponent) ---> a concise record of the phrase times ten to the power of Exponent MUST be an integer, Base MAY be an integer

Newline Character

- special symbol > " \n " - "n" comes from the word newline - an empty print() function can output a newline - urges the console to start a new output line --> ex. : print("The itsy bitsy spider\nclimbed up the waterspout") The itsy bitsy spider climbed up the waterspout

Where do/could functions come from?

- from Python itself : a function that is an added value received together with Python and its environment (it is built-in); you don't have to do anything special (e.g., ask anyone for anything) if you want to make use of it - from one or more of Python's add-ons, named modules: some of the modules come with Python, others may require separate installation - whatever the case, they all need to be explicitly connected with your code - from writing them yourself > placing as many functions as you want/need inside program to make it simpler, clearer & elegant > function names should be significant

Positional Way

- most common way in Python to pass arguments into the print() function - name comes from the fact that the meaning of the argument is dictated by its position ---> they will be outputted in the order they are inputted

Comments

- remark inserted into a program & omitted at runtime - a piece of text that begins with a # (hash) sign and extends to the end of the line (if you want a comment that spans several lines, you have to put a hash in front of them *all*) - can also insert a comment right after code using a hashtag to distinguish it like this: ex. c = a ** 2 *# We use ** instead of square root* - to quickly comment or uncomment multiple lines of code, select the line(s) you wish to modify & cmd+/ - can also use them to mark a piece of code that currently isn't needed for whatever reason, or isolate the place where errors might be hidden during testing - whenever Python encounters one in your program, it is completely transparent to it - from Python's point of view, this is only one space (regardless of how long the real comment is) - good developers describe each important piece of code, explaining the role of any variables; but the best way of commenting variables is to name them in an unambiguous manner, like naming a square: "square_area" instead of an unrelated name: "aunt_jane" ^ we say that the first name is *self-commenting*, (meaning self-evident / self-explanatory)

Variable

- special "box" (container) whose purpose is to store values like strings & numerical operations in the memory, in order to use them in other operations, and so on; saves the intermediate results to use them again to produce subsequent ones - a "value" is stored in a "variable name" - content can be varied in almost any way - every Python variable has : name ; value (content of the container) - a variable comes into existence as a result of assigning a value to it (it's automatically created then and nothing else needs to be done-) - can put anything inside it & change it at any time name of desired variable = value you want to put into it ex. var = 1 (assigned value 1) --> (now you can output it onto console -> print(var) *= 1*

What is the effect the print() function causes?

- takes its arguments (more or less than one argument) - converts the argument(s) into human-readable form if needed (strings don't require this - already readable) - sends the resulting data to the output device i.e. anything put in the function will appear on the screen (usually the console) - print function separates it's arguments with spaces

Function Name Restrictions (same for Variable Names)

- the name of the variable must be composed of upper-case or lower-case letters, digits, and the character _ (underscore) - the name of the variable must begin with a letter; the underscore character is a letter; - upper- and lower-case letters are treated as different (a little differently than in the real world - Alice and ALICE are the same first names, but in Python they are two different variable names, and consequently, two different variables); - the name of the variable must not be any of Python's reserved words (the keywords - we'll explain more about this soon)

what NOT to do with the input() function

- the result of the input() function is a STRING containing all the characters the user enters from the keyboard. - It is NOT an integer or a float - mustn't use it as an argument of any arithmetic operation, or perform a mathematical operation with it / on it] ex. X-INcorrect-X ---> anything = input("Enter a number: ") something = anything ** 2.0 print(anything, "to the power of 2 is", something) X-INcorrect-X

Python "Instructions"

- there cannot be more than one instruction in a line - a line can be empty - containing no instruction - allows *1* instruction to spread across more than 1 line (helpful when code contains complex constructions) - the instructions in the code are executed in the same order in which they have been placed in the source file; no next instruction is executed until the previous one is completed (there will be exceptions to this in the future) - function begins its output from a new line each time it starts its execution (this can be changed if needed)

Booleans

-literals- from George Boole (1815-1864), the author of The Laws of Thought, which contains the definition of Boolean algebra - a part of algebra which makes use of only 2 distinct values/constant objects: True & False, denoted numerically as *1* & *0*, respectively - Computers know only two kinds of answers: Yes, this is TRUE >>> True & False are Boolean values No, this is FALSE These 2 values have strict denotations; Python is binary *You cannot change anything - you have to take these symbols as they are, including case-sensitivity*

Keywords

...or (more precisely) reserved keywords, listed here : ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] - they are reserved because you mustn't use them as names : neither for your variables, functions, nor any other named entities you want to create - their meaning is already predefined, and mustn't be changed in any way - due to the fact that Python is case-sensitive, you can modify any of these words by changing the case of any letter, thus creating a new word, which is not reserved anymore ex. "import" is reserved/can't be used > but "Import" can

What does Python do when encountering a Function Invocation?

1. checks if function name is *legal* > browses its internal data in order to find an existing function of the name 2. checks if the function's requirements for the # of arguments allows you to invoke the function in this way (i.e. if a specific function demands exactly 2 arguments, any invocation delivering only 1 argument will be considered erroneous >code will be aborted) 3. leaves your code for a moment & jumps into the function you want to invoke, taking your argument(s) and passing it/them to the function as well 4. function executes its code, causes the desired effect (if any), evaluates the desired result(s) (if any) and finishes its task 5. Python returns to your code (to the place just after the invocation) and resumes its execution

int

A Python data type that holds positive and negative whole numbers -literals-

Floats

A Python data type which stores floating-point numbers. Floating-point numbers are stored internally in two parts: a base and an exponent. When printed in the standard format, they look like decimal numbers *loose* definition -literals- designed to represent and to store the numbers that (as a mathematician would say) have a non-empty decimal fraction- they are the numbers that have (or may have) a fractional part after the decimal point ex. 1.5 -2.6 NOTE : 0.4 --> can be written as: *.4* OR *4.* This will change neither its type nor its value

function

A named sequence of statements that performs some useful operation. a separate part of the computer code able to: - cause some effect (e.g., send text to the terminal, create a file, draw an image, play a sound, etc.) - evaluate a value and return it as the function's result (i.e. evaluate the square root of a value or the length of a given text) ex. 'print' is a function name (Python functions may accept any number of arguments - as many as necessary to perform their tasks depending on individual needs/ also need to use parenthesis whether or not there is an argument)

String

A sequence of characters/symbols - String are delimited with *quotes* > used to mark the beginning and end of a string; they basically MAKE them/cut out a part of the code & assign a different meaning to it (there are many ways to specify strings) - (can be delivered to a function as an argument) - can be delimited with single-quotes / apostrophes - look at it like this : "the text between us is not code" - not to be executed, just taken as is/literally as *data* f

print() function with more than 1 argument

ex. 1 print() function invocation with 3 arguments that are all strings - there are no spaces inside the strings INPUT : print("The itsy bitsy spider" , "climbed up" , "the waterspout.") OUTPUT: The itsy bitsy spider climbed up the waterspout. - a print() function invoked with more than one argument outputs them all on one line; - the print() function puts a space btwn. the outputted arguments on its own initiative ^present in ex. - The arguments are separated by commas- (can surround commas w/ spaces like in the ex. to make them more visible, but it's not necessary) - In this case, the commas separating the arguments are a part of Python's syntax; outside of the string - Commas inside the string would be intended to be shown in the console

Ways to prompt the user for Input

ex. print ("Tell me anything..." ) anything = input() > ^ can prompt the user to input something by using print() for a question or statement and then assigning the results of the input to a variable ex. anything = input("Tell me anything...") > this variant input() function can prompt the user without any help from print() - the message will be displayed on the console before the user is given an opportunity to enter anything - and you can immediately assign the results of it to the variable as well - input() function is invoked w/ 1 argument - STRING containing a msg.

how to encode a quote inside a string which is already delimited by quotes?

ex. string: I like "Monty Python" .....there are 2 ways: - using the escape character, the backslash, to momentarily break out of the code and insert a " as a just a quote, and not as a delimiter forming the string - using an apostrophe as the delimiter instead - Either of these characters may delimit strings, BUT you must be consistent (if starting w/ apos., you must end w/ apos.) ex. print('I like "Monty Python"') - need not use \'s

Function Invocation (or Call)

function name + parentheses + arguments forms it ----> function_name(argument) - one of many possible kinds of Python instructions

print()

function that prints the specified message to the screen, or other standard output device.


Conjuntos de estudio relacionados

MDSE 4010 Final Review (All Quizzes + Vocab)

View Set

Case 5: Skin, Vitamin D, Folate, Melanoma

View Set

Context and Connotation - Connotation and Denotation

View Set

Course 2/MOD1 -Explore the CISSP security domains, Part 1

View Set

Biology 196 Ex. 4 My Lab and Mastering

View Set

Ch 8 Adaptive Immunity, Ch 9 Alterations in Immunity and Inflammation, Chapter 10: Infection, Ch 11 Stress and Disease

View Set