You are on page 1of 16

Print Function:

● Start with function name, after there is a pair of parentheses: ( ), followed by a parameter inside the parentheses.

With the print functions, we put text we want to print as a parameter.

● Change the print function to use a capital P: Print

Traceback (most recent call last):


File "main.py", line 1, in <module>
Print("Hello World")
NameError: name 'Print' is not defined
● Looks cryptic but we can decode a bit to see that it includes ‘\n’ which means a line break at the end.
● All escape codes in Python start with a backslash: \. (A backslash leans backwards. A forward slash / leans forward.)
● The escape code for a double quote is \":

Then Mr. Aitonean said to them “Put your phone away or I will read your messages out loud to everyone!”

Escape Character Description

\” double quotation mark

\’ single quotation mark

\t tab

\n new line
\\ backslash
2.2 - Variables & Strings
Variables act as "storage locations" for data in a program. Just like math, it is a letter or a word that is used to represent a piece of data.

Operators are symbols used to perform operations or processes. Although the = symbol is what
we use for an equal sign in math class, this symbol is an the assignment operator in Python, not an equality operator (we'll see what the
equality operator is later this unit).

Rules:
● Variable names can only contain letters, number, and underscores
● Variable names cannot start with a number
● No space, use underscores to separate words
● Avoid Python Keyword (we’ll see these later on) and stick to lowercase
● Variable names should be short but descriptive. E.g. name is better than n, student_number is better than s_n.
In python you can redefine a variable and it will only keep track of your most recent variables.

● A string is a series of characters, think of it as “text”


○ Anything that is inside “ ” is considered a string. Can also use ‘ ’
The most elegant way to format string is to use f-strings
● add a f in front of your quotations
● Insert any variable you with braces { } around the variable name

A method is an action that Python can perform on a piece of


data (variable)

● For us, they will be added to the end of a variable name


○ variable_name.method()
The title method will capitalize first letter of a string
● Single-line comments take up only one line of code or one partial line of code. In Python, they start with #. These types of comments
are typically used to provide a brief description of what's going on in a particular line of code.
● Multi-line comments take up multiple lines of code. In Python, they start with ' ' ' or " " " and end the same way.
● To change any lines into comments, we can highlight them and do CRTL + /.

● The main reason to write comments is to explain what your code is supposed to do and how you are making it work.
● If you leave a project and come back after a long time, the comments can be there as a summary to help understand what is going on.
● Do not OVER COMMENT unless it’s a “to-do” list
2.4 - Numbers I
● Strings are sets of characters joined to form words or sentences
● Integers are positive and negative whole numbers
● Floats are decimal numbers
● Booleans are true or false values

Casting is a type conversion that involves using a function to change a


variable's data type.

● In Python, we do this by wrapping the variable in parentheses and placing the name of the new data type in front.
Note that when int() takes a decimal number,
it doesn't round it to the nearest integer –– it cuts off the all decimal digits.

Float Imprecision: Sometimes we get inaccurate answers when we are working with decimal numbers.

● This is due to finite data representation.


● Python doesn't have an infinite amount of storage and sometimes there isn't enough space to perform a calculation accurately when it
involves decimal numbers

round( ): We can use the round( ) function to round numbers to any number of decimal places.

● Operation goes inside the bracket with a comma and the number of decimals you want it rounded too.

Multiple Assignment: You can use one line to assign multiple values
to multiple variables.

2.5 - Math in Python: Increment increases/ decreases: What


if we need to keep track the number of times a certain event happens in our code? For example, let’s say x represents the number of coins a
character in a game has collected.

A faster way to increase a variable by 1 is to use the increment +=


operator

import random: It might be beneficial to you at some point to create a random number (Think dice games or times
when you don’t want to enter test data from the keyboard).

You need to import the random library and then use the some of the different functions inside it.

import math:The math library gives a number of


functions that you would commonly see on a scientific calculator and beyond. For example:

math.sqrt(): In order to perform a square root


in python you must also import the math library and then use its sqrt function:

2.6 - Intro To Lists: What are Lists? A list is a collection of items in a particular
order. You can make a list that includes the letters of the alphabet, the digits from 0–9, or the names of all the people in your family.

● It’s a good idea to make the name of your list plural, such as letters, digits, or names
● In Python, square brackets [ ] indicate a list, and individual elements in the list are separated by commas
Accessing Elements in a List: Item in a list called an element or
a value

Python numbers the positions of elements in a list from left to right. This is referred to as the index

Index Positions start at 0, NOT


1: Python considers the first item in a list to be at position 0, not position 1

● Using this counting system, you can get any element you want from a list by subtracting one from its position in the list.
● You can also get the last element from the list by asking for index -1

Modifying Elements in a List:To


change an element, use the name of the list followed by the index of the element you want to change, and then provide the new value you want
that item to have.

.append() method
➔ This allows you to add an element to the end of your list.
input( ) and .append( ): Try to come up with a way that we can use input ( ) and .append ( ) together to add an item to a list? NO GOOGLE,
just try.

The .pop()method removes the last item in a list,


but it lets you work with that item after removing it. The term pop comes from thinking of a list as a stack of items and popping one item off
the top of the stack. In this analogy, the top of a stack corresponds to the end of a list.
Let's pop the last car from our list
.insert() method
➔ This allows you to open a space and add an element at any position you’d like.
Using our previous example, let's add another car to the middle of our list.
2.7 - Organizing Lists: Strings & Lists: You can consider a string as a list of its individual characters. So each character in the String is
considered as an item of the list.
● The biggest difference between them is that Strings are “immutable”. You can’t modify the letters in the String as easily as you can if
the they were stored as a list.

Splitting Strings: .split() method. The split method will separate the string based on wherever whitespace occurs. It stores that information in a
list.
You could even force it to split a String that is separated by any character, such as a comma. That character is often called a delimiter in
programming.

3.1 - If Statements:

Basic Comparison:
If-elif-else Chain: Sometimes you’ll have to evaluate more than 2 possible situations.
● Python reads these test from top to bottom. As soon as it finds a condition that is True, it will skip the rest of the test.
If-else Statements: So far, If statements are only executed when the first condition is True. What happens when it is False?
We can use an if-else block, which allows you to define an action to take when a conditional test fails. Let's look at the voting example again.

Using And/Or:You can check multiple conditions by chaining together comparisons with and or operators.
● and - only passes if BOTH conditions are True
● or - passes when either condition is True
3.2 - For Loops & Loops in Lists: a loop is used to repeat a block of code until a specified
condition is satisfied.
People will often use the generic term “iterate” when referring to loops; iterate simply means “to repeat”.

User input and for Loops: This next example asks the user how many times to print using the input function we talked about last chapter in the
input function. Go ahead and try the program out.

For Loops in Lists:


Avoiding Indentation Errors: Python uses indentation to
determine how a line, or group of lines, is related to the rest of the program.
● We will work more with indentations later on
Forgetting the Colon:The colon at the end of a for statement tells Python to interpret the next line as the start of a loop.
● These are really tough to find even though it is an easy fix.
3.3 - For loops in Numbered List
range()Function:Python’s range() function makes it easy to generate a series of numbers.
i variable:We often use the variable i as the “counter” to keep track of the number of “loops”
● Both “value” and “i” are acceptable
If you want to make a list of numbers, you can convert the results of range() directly into a list using the list() function. When you wrap list()
around a call to the range() function, the output will be a list of numbers.
A few Python functions are helpful when working with lists of numbers. For example, you can easily find the minimum, maximum, and sum of
a list of numbers.
3.4 - While Loops
while loop: a while loop can be used anywhere a for loop is used because our “condition” can be a count. That is, the while loop can loop until
a variable reaches a certain value. If that’s the case, why have a for loop if a while loop can do everything?
The format of the while loop is very similar to the if statement. If the condition holds true, the code in the loop will repeat.

Previous slide:

Python repeats the loop as long as the condition i < 10 is true. Because 0 is less than 10, Python prints 0 and then adds 1, making the current
number 1. Because 1 is less than 10, Python prints 1 and adds 1 again, making the current number 2, and so on. Once the value of i is no long
less than 10, the loop stops running and the program ends.

Letting the User quit loops:A very common operation is to loop until the user performs a request to quit. Give this code example a try.
3.5 - Random numbers
After this, random numbers can be created with the randrange function. For example, this code creates random numbers from 0 to 49. By
default the lower bound is 0.

3.6 - Advanced Looping


This will be a “challenge lesson”. If you can understand this lesson, you will have a good grasp on loops.

At the very least, make sure you can write out the answers for the first eight problems. That will give you enough knowledge to continue on.

3.7 - Functions
Defining a function doesn’t cause the computer to do anything. It is like giving a recipe to the computer. Give someone a recipe for banana
bread and they know how to make it. They haven’t actually made it yet, they just know how. You have to tell them to make banana bread. That
is, after we define the function we must call the function before the code in it runs

To call a function, type the function name and follow it by parenthesis. Do not use def, that is only used when we define what the function
does, not when we tell the computer to run it.

Parameter vs Arguments: A parameter is used while defining a function.


○ It is a piece of information the functions needs to do its job.
● An argument is used when calling a function.
○ It is a piece of information that’s passed from a function call to a function.
○ When we call the function, we place the value we want the function to work with in parentheses.

You may see these terms used interchangeably, but there is a subtle difference between them.

Returning Values:Functions can not only take in values, functions can return values.
For example, here is a function that returns two numbers added together. See how it uses a return statement on line four to return the result out
of the function.

You might also like