CS1301 Chapter 2

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

1| a = 5 2| b = 5 3| c = 3 4| print(a = b) 5| print(a = c) 6| print(b = c)

leads to error because you need a double equal sign == for print

Assignment Statement

assigns a value to a variable

Comments

Notes from the programmer supplied in-line alongside the code itself, designated in a way that prevents the computer from reading or attempting to execute them as code.

Boolean Operators:

Operators like "and" and "or" that act on pairs of boolean (true or false) values, or that act on single boolean values, like "not".

Relational Operators:

Operators that check the relationships between multiple variables, such as checking if they are equal or if one is greater than another. Check if things are true in the world or in our data

Numeric Comparison Operators:

Operators that facilitate numeric comparison between values. Typically, these are 'greater than' (>), 'greater than or equal to' (>=), 'equal to' (==), 'less than' (<), and 'less than or equal to' (<=).

Logical Operators

Operators that perform logical operations, such as comparing relative values, checking equality, checking set membership, or evaluating combinations of other logical operators.

Mathematical Operators:

Operators that perform mathematical functions, like adding numbers together or assigning values to variables.

Conventions for variable names

Variables should be self-documenting and tell you what kind of data they are holding

Implicit Converstion

When using the print function, it prints things as strings so it will automatically run the string conversion in order to print our value

Underscores

just replaces spaces with underscores, usually keeping the variable name in all-lower case, like this: this_is_my_variable_name.

Set Operators:

Check to see if a value is a member of a set of multiple values. Most often this comes up in strings and lists. With strings, we can check to see if a certain smaller string occurs inside a larger string. For example, "cde" is in the string "abcdefg", but "ijk" is not. With lists, we can check to see if a certain item is on our list. For example, if we had a list containing "grapes", "apples", and "oranges", then "apples" would be in that set, but "papaya" would not.

2 kinds of logical operators

relational and Boolean

Mathematical operators

+, -

Modulus

the remainder function

Converting myDate to String

you can do myDate=date.today() myDateAsString=str(myDate) Or you can just do myDateAsString=str(date.today())

Rules for variable names

-can only contain letters, numbers, and underscores CANNOT contain spaces or special characters -Variable names must start with letters -Variable names must not duplicate certain reserved words --ex. you cant use for as a variable name in python

Which of the following segments of code will run error-free? Assume that no code has been run before these lines.

1| print("Number of the day: " + str(5)) 1| intAsString = str(5) 2| print("Number of the day: " + intAsString) 1| print("Number of the day:", 5) 1| print("Number of the day:", str(5))

Method

A function that is part of a class in object-oriented programming (but colloquially, often used interchangeably with function).

Object-Oriented Programming

A programming paradigm where programmers define custom data types that have custom methods embedded within them.

Function

A segment of code that performs a specific task, sometimes taking some input and sometimes returning some output.

Event-Driven Programming

A type of programming where the program generally awaits and reacts to events rather than running code linearly.

date.today()

After importing date from datetime, returns a date object representing the current date.

When we use this comma, on the other hand, the print statement implicitly converts each thing to a string if needed and then puts them together.

By default, it puts each thing together separated by a space.

Variables

Alphanumeric (letters and numbers) identifiers that hold values, like integers, strings of characters, and dates.

Not operator

An operator that acts on one boolean (true or false) value and evaluates to the opposite value (false becomes true, true becomes false).

Or:

An operator that acts on two boolean (true or false) values and evaluates to "true" if and only if at least one is true.

And:

An operator that acts on two boolean (true or false) values and evaluates to "true" if and only if both are true.

If you try to multiply "Hello world" by 5.1 you will get a Type error that will say it cannot multiply a sequence (referring to the string of letters) by a float (a decimal number)

BUT you CAN multiply "Hello World" by an integer like 3 and the result would be Hello World Hello World Hello World

We can take an integer and interpret it as a floating point number or interpret it as a decimal number.

BUT you can't make Python read a float as an integer and do that conversion: The only way to convert 5.1 to an integer would be to lose some information-- to lose that 0.1. And that's not something Python can do automatically. If we wanted to convert it to the integer 5, we would have to first convert it to a float, then round that float down, and then convert it to an integer.

Self-Documenting Code

Code whose variables and functions are named in a way that makes it clear what their underlying content and operations clear to the reader.

Documentation

Collected and set-aside descriptions and instructions for a body of code.

What are all of the reserved words?

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

Here are the reserved words and where they'll be covered in our material:

Importing Libraries. import, from. Not covered explicitly, but you'll see these in a few places throughout our material, especially when we're dealing with dates, turtles, or random numbers. Logical Operators. and, is, not, or, False, True, None. Covered in Chapter 2.3. Control Structures. as, break, continue, if, elif, else, for, in, while, pass, with. Covered throughout Unit 3. if, elif, and else are covered in 3.2; for, while, pass, continue, and break are covered in 3.3. as and with are not covered explicitly. in comes up in Chapters 2.3, 3.2, 3.3, and other places. Functions. def, return. Covered in Chapter 3.4. Object-Oriented Programming Syntax. class. Covered in Chapter 5.1. Error Handling. except, finally, raise, try. Covered in Chapter 3.5. else also comes up here

camelCase vs. using_underscores

In almost all programming languages, variables (as well as functions, methods, classes, and other stuff we'll learn about later) cannot have spaces in them. We can't declare a variable called a number. What do we do, then, when we want to create a variable whose name really should be more than one word? There are two common conventions: camel case and underscores.

More Rules

Set variable equal to values not the other way around May not use variables before they have been assigned a value

Operators

Specific, simple functions that act on primitive data types, like integers and strings.

bool(variable):

Takes as input some variable (usually a string) and attempts to convert it to a boolean, returning the boolean value if successful or raising a ValueError if unsuccessful. Generally, this function returns False if variable is 0 or an empty string, True if variable is anything else.

float(variable):

Takes as input some variable (usually a string) and attempts to convert it to a float, returning the float if successful or raising a ValueError if unsuccessful. This function will work if variable is a string made up only of digits and, optionally, a negative sign and a decimal point.

int(variable):

Takes as input some variable (usually a string) and attempts to convert it to an integer, returning the integer if successful or raising a ValueError if unsuccessful. This function will work if variable is a string made up only of digits and, optionally, the negative sign.

str(variable)

Takes as input some variable and returns a string representation of the variable's value. Every data type can be converted to some kind of string.

type(variable)

Takes as input some variable or value directly and returns the type of the variable such as an integer or string of characters.

Why does print("Today's Date:" , date.today()) work though?

That's because when we use this comma instead of this plus sign, it tells the print statement to interpret each individual thing in the parentheses as a separate piece of data

Null

The "value" a variable has when it doesn't actually have a value.

Value

The content of some variable. The variable myAge might hold the value 29. The variable yourName might hold the value "Adelene".

in operator

The in operator checks to see if something is contained within a list of other things.

input function

The input function is a function like all our others, which means it's followed by parentheses. And its parameter is a string. In this case, the string is enter an integer, followed by a colon and a space. When it's run, it prints that text to the user and then lets them enter some input. Python interprets all of them as strings until it's told to do something else. So if you want to multiply this inputted value or add it or something you will need to convert it to an integer using int() function

Data Type

The type of content a variable holds, like an integer or a string of characters.

When we're dealing with strings, like "132" (marked as a string by the quotation marks), we're treating the characters as text. We can print it, reverse it, look up the second character, ask for the number of characters, duplicate it, etc. Anything we could do with the string "abc", we can also do with the string "132".

When we're dealing with integers, like 132, we're treating the text like an integer. We can add it, multiply it, divide it, square it, etc. Those are things we generally can't do with a string like "abc" (or if we do, they take on different meanings). These are operations specific to numbers. So, even though 132 and "132" look similar to us, they differ in how they can be used, and we have to use certain functions for converting between the two.

Will this generate an error? 1| int = "5" 2| otherInt = "7" 3| combinedInt = int + otherInt 4| result = int(combinedInt) 5| print(result)

Yes because since we used int as a keyword, we now can't use the int function later on int is not a reserved word though

Which will work?

a = myInteger * myFloat b = myInteger * myString c = myInteger * myBoolean e = myFloat * myBoolean f = myString * myBoolean

assignment operator

a single = sign. it assigns value on right to variable on left

5 types of mathematical operators

addition, subtraction, multiplication, division, and modulus

Code block comments

are essential in large programs that contain several functions and files with many people working together

Relational Operators

check for the relationships between values includes: ==, >, <, >=, <=

Boolean operators

check the combination of multiple relational operators

floating point number =

decimal number

Non-Numeric Equality Comparisons:

early any kind of data can compare for equality, even if it isn't numeric. We can't ask if an apple is greater than an orange, but we can ask if apples and oranges are 'equal', or the same thing.

Code to check what the reserved words are:

import keyword print (keyword.kwlist)

Camel Case

mushes the words together and capitalizes each word, like this: thisIsMyVariableName

Which of the following lines of code would run successfully (that is, not generate an error)?

myBoolean = bool("Hello!") myBoolean = bool("5.1") myFloat = float("5.1") myBoolean = bool("5") myFloat = float("5") myInteger = int("5")

Boolean operators

operators that themselves only act on true and false values ex. and, or, not

Complete the line below to print the current time with the form hour:minute:second, such as 12:57:15. Don't worry about the leading 0s for single-digit times. If it's 1:05PM and 7 seconds, the correct answer would be: 13:5:7 (13 because Python uses 24-hour timeby default).

print(str(current_time.hour) + ":" + str(current_time.minute) + ":" + str(current_time.second))

Complete the line below to print today's date with the form year/month/date. For example, January 15th, 2017 would be 2016/1/15.

print(str(todays_date.year) + "/" + str(todays_date.month) + "/" + str(todays_date.day))

type function

tells us the type of data we have for a variable is followed by a set of parentheses ex. print ( type (myNumber)) and this would output int

concatenate

to put together

variable is always on the left of the equals sign

value will be on the right of the equals sign


Ensembles d'études connexes

Foundations of Nursing - Chapter 10 Test

View Set

Psychology of Emotion | Midterm 2

View Set

Chapter 16: Drug Therapy to Decrease Pain, Fever, and Inflammation PrepU

View Set

Chapter 4: Final Exam Review Questions

View Set

Arabic: Rosetta Stone Vocabulary Unit 1

View Set

Bio Section 3-1. What is Ecology

View Set

Ch 08: Security Strategies and Documentation

View Set