Module 2/Week 2

Ace your homework & exams now with Quizwiz!

String type

A value in the print statement, noted as print("pi = 3.14").

Floating-point number type

A value in the print statement, noted as print(3.14).

Variable

A variable is a name that refers to a particular value. It is called a variable because that value it refers to can change. Variable names should be descriptive of their purpose to enhance the readability of your code. They must start with a letter or an underscore and subsequent characters can be numbers, letters, or underscores. Variables are case sensitive, i.e., radius, Radius, raDius, would be interpreted as different variables. Variables cannot be any of the Python 3 keywords. In python you can change what type of value a variable refers. For example, you can assign an integer to a variable (myValue = 999) and then later assign a string to that same variable. You can use the type function (type(myValue)) to see what type of value a variable currently refers to, print("The type of myValue is", type(myValue)) -> The type of myValue is <class 'int'>.

Arithmetic

Addition +, subtraction -, multiplication *, and division /

Floating-point numbers

Are numeric values that contain a decimal point. In mathematics, these are real numbers. Floats can also be written using scientific notation, using either e/E followed by a positive integer (the exponent), ex: print(1.2e7) or print(-3.27E12). The maximum value for a float is 1.7976931348623157e+308. Floats are stored as binary fractions. However, most fractional values cannot be represented exactly as binary. Just as 1/3 cannot be represented exactly in decimal notation with a finite number of digits ((0.333333333333333...). Due to this, floats are approximate values, but the approximation is accurate to several decimal places.

Integers

Are numeric values that don't contain a decimal point, In python 3, integers can be as long as you want (within the limits of your computers memory). Integers are a sub-set of the real numbers (in math).

Strings

Are zero or more characters between a pair of quotation marks (print("Hello World") or print('Hello world')). You can use either single quotes or double quotes. The length of the string is only limited by your computers memory. If you want quotation marks to be a part of a string, there are two options: 1. If the string contains a double quotation mark, you can use single quotation marks to mark the end of the string, ex: print('She explained, "Mae fy hofrenfad yn llawn llyswennod."'). 2. Another way is to put a blacks-lash in front of the quotation marks that are a part of the string, ex: print("She explained, \"Mae fy hofrenfad yn llawn llyswennod.\""). Normal strings cannot be split across multiple lines.

Assignment statement

Assigns a value to a variable, ex: radius = 19.2, first_name = "Jane", is_even = True, num1 = 12. Each of these statements causes the variable on the left side to refer to the value on the right side. It is also possible to have a variable on the right side of an assignment statement, in which case the variable on the left side will now refer to the variable on the right side. Ex: num1 = 12 num2 = num1 >num2 12

Comments

Comments are notes for those reading code. A comment begins with #. It can be on its own line or on the same line as other code. Either way, the complier will ignore everything between the # and the end of the line. Comments should be used to explain non-obvious aspects of code such as purpose of a section, the units for the value of some variable, the reason for a certain design choice, etc. Ex: # this is a comment height = 1.8 # this is also a comment

Exponents

Done with * * symbol. Ex: > power_1 = 3 ** 4 # 81 > power_2 = 2 ** -3 # 0.125

Mod operation

Done with the % symbol and gives you the remainder of division. Ex: > remainder_1 = 14 % 3 # 2 > remainder_2 = 3 % 5 # 3

Floor division operation

Done with the symbol // and gives you the rounded down results of division. If you need an integer remainder, use floor division. Ex: > floor_1 = 7 // 2 # 3 > floor_2 = -7 // 2 # -4

Python 3 keywords

False, class, finally, is, return, True, continue, for, lambda, try, None, def, from, nonlocal, while, and, del, global, not, with, as, elif, if, or, yield, assert, else, import, pass, break, except, in, raise

Write a statement that prints out the string value "He replied, "Never mind", and shut the door."

Input: - print('He replied, "Never mind", and shut the door.') - print("He replied, \"Never mind\", and shut the door.") Output: "He replied, "Never mind", and shut the door."

Write code that assigns "Doctor" to a variable named title, assigns "Pierce" to a variable called last_name, and then uses string concatenation to print out "Doctor Pierce".

Input: title = "Doctor" last_name = "Pierce" full_name = title + " " + last_name print(full_name) Output: "Doctor Pierce"

Write a statement that finds the result of 9 divided by 5 and assigns it to a variable named conversion_ratio.

Input: conversion_ratio = 9 / 5 Output: >conversion_ratio 1.8

Input( ) function #2

Input: name = input("Please enter your name: ") print("Hi", name) Output: Please enter your name: -> Alex Hi Alex

Write code that first assigns 9 to a variable called num_planets, then subtracts 1 from it, so that num_planets will now equal 8.

Input: num_planets = 9 num_planets -=1 Output: >num_planets 8

Write a statement that prints out 2 to the 4th power.

Input: power_1 = 2 ** 4 print(power_1) Output: 16

Write code that asks the user for two numbers and then prints out "The result is" followed by the result of multiplying those numbers.

Input: print("Give me two numbers and I'll multiply them") num_1 = int(input( )) num_2 = int(input( )) print("The result is", num_1 * num_2) Output: Give me two numbers and I'll multiply them -> 3 -> 20 The result is 60

Same as #2, but first store the result of multiplication in a variable and then use that variable when printing out the result.

Input: print("Give me two numbers and I'll multiply them") num_1 = int(input( )) num_2 = int(input( )) result_1 = num_1 * num_2 print("The result is", result_1) Output: Give me two numbers and I'll multiply them -> 3 -> 20 The result is 60

Input ( ) + cast example

Input: print("Please enter two numbers.") num_1 = float(input()) num_2 = float(input()) print("The sum is", num_1 + num_2) Output: Please enter two number. -> 2 -> 6 The sum is 8.0

Input( ) function #1

Input: print("Please enter your name.") name = input( ) print("Hi", name) Output: Please enter your name. -> Alex Hi Alex.

Write code that asks the user for their name and then prints out "Hello" followed by their name.

Input: print("What is your name?") name = input ( ) print("Hello", name) OR name = input("What is your name?") print("Hello", name) Output: What is your name? -> Taylor Swift Hello Taylor Swift

Write a statement that prints out the remainder of 19 divided by 6.

Input: remainder_1 = 19 % 6 print(remainder_1) Output: 1

Assign the value "Smith" to a variable named last_name, and then print out the value of that variable.

Input: last_name = "Smith" > print(last_name = "Smith") Output: "Smith"

Assign the value 19.3 to a variable named length_in_inches, and then print out the type of the value that variable refers to.

Input: length_in_inches = 19.3 > type(length_in_inches) Output: <class 'float'>

Assign the value "haberdashery" to a variable named occupation, and the print out the type of the value that variable refers to.

Input: occupation = "haberdashery" >type(occupation) Output: <class 'str'>

Assign the value 3.14159 to a variable named pi, and then print out the value of that variable.

Input: pi = 3.14 Output: 3.14

Write a statement that prints out the float value 290.73

Input: print(290.73) Output: 290.73

Write a statement that prints out the bool value True (not the string value "True")

Input: print(True) Output: True

Write a statement that print out the type of value "What is your quest?"

Input: type("What is your quest?") Output: <class 'str'>

Write a statement that prints out the results of using the type command value 99

Input: type(99) Output: <class 'int'>

Black slash (\)

Is an escape character, because it escapes the normal significance of the following character. Because of that, if you want to have a back lash be part of the string, you need to put two (\\) of them in a row as the first one escapes the normal significance of the second one.

(symbols -,+,*,/,//,%,**)=

Is used to express that you want to add something to an existing value. Ex: my_sum = my_sum + 8 is the same as my_sum += 8 Ex: num = 1 num += 3 > num 4 Ex: num = 1 num -= 3 >num -2

Literals

Literal values like 212, -17.8, "Dallas," or true, are often referred to as "literals."

Name Error

NameError: name 'phrase' is not defined because we did not assign a value to phrase before trying to print it.

print ( )

Print functions can be used to print out values, You put the value you want to print inside ( ). A print statement can print more than one value, they need to be separated by commas (i.e., print(6, 7)).

Four basic python value types

Python distinguishes between 4 different types of values: integers, floating-point numbers, strings, and Booleans

Determining value types, type ( )

String: <class 'str'> Floating-point number: <class 'float'> Integer: <class 'int'> Boolean: <type 'bool'>

EOL

SyntaxError: EOL while scanning string literal. End Of Line, the interpreter got to the end of the line without finding the missing quotation mark. Because strings cannot be split across lines, the interpreter does not need to look all the way to the end of the line, i.e., @ interpreter, print("hello)

SyntaxError

SyntaxError: cannot assign to literal. We have to have a variable on the left side of an assignment statement, not a literal value. Ex: > 32 = age, cannot work.

EOF error message

SyntaxError: unexpected EOF while parsing. End Of File, meaning the interpreter got to the end of the file and never found the missing parenthesis, i.e., print("hello)

Concentration

The + operator can also be used with strings to concatenate them together. Ex: first_name = Carol last_name = Danvers full_name = first_name + " " + last_name print(full_name) >full_name Carol Danvers

Order of operations and considerations

The order of operations is parentheses*, exponentiation, multiplication, division, floor, mod, addition, and subtraction. *Parentheses can be used to give order to whatever order is needed. Ex: > result_1 = 3 * 5 + 1 # 16, multiplication happens first > result_2 = 3 * (5 + 1) # 18, addition happens first

TypeError

TypeError: unsupported operand type(s)...[incorrect ops] When an operation or function is applied to an object of an inappropriate type.

User inputs

User input is always a string. If you want a numeric value from user input, then you need to cast the string to an int or a float to combine functions. Ex: > age = int(input("Please enter your age: ")) > height_in_meters = float(input("Please enter your height in meters: ")) First the input function gets a string from the user. Next the int( ) or float ( ) function casts that string to a numeric value. That value is assigned to the variable. Ex: > str_age = input("Please enter your age: ") # str_age will refer to a string value > int_age = int(str_age) # int_age will refer to an int value You can cast an int to a float, or a float to an int (which truncates everything after the decimal point), and you can also cast values to strings with str( ).

Booleans

Values: True or False.

Determining types of values

We can use type( ) function to tell us what the type of a particular value is.

Normal division operation

Will result in a float value, even if the result is an integer.

Absolute value

answer = abs(x), the variable 'answer' is assigned to x. Ex: answer = abs(12), the variable 'answer' is assigned to 12.

print ( ) assignment statement variables

radius = 19.2 > print(radius) 19.2


Related study sets

Attention-Deficit/Hyperactivity Disorder (ADHD)

View Set

NIHD Week 4: Motor Systems & Movement Control: (Frank), Upper vs. Lower Motor Neurons; Localization of Weakness & Sensory Syndromes (First Aid 469, 470, 495)

View Set

Unit 1 & 2 Exam Study Guide AP Psychology

View Set

Decision trees and crazy random forests

View Set