Python ch. 1 + 2 (Variables)

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Let's say that we're creating a game and want to welcome newcomers to the game. We'll want to greet the user and give an invitation to play.

#Greeting print ("Howdy!") #Invitation print ("Shall we play a game?") Output: Howdy! Shall we play a game?

Rules for naming and using variables

-Variable names can contain letters, numbers and underscores only. They can start with a letter or underscore but not with a number. -Spaces are not allowed in variable names, but underscores can be used to separate words. -Avoid using Python Keywords and function names as variable names. -They should be short but descriptive, example "name" rather than "n"

Main outlook with memory

A good way to think about this temporary working memory is like a set of boxes. Each box can contain some piece of information. If you want to use these boxes, you will need to be able to somehow refer to them. Each box needs a name. It's these regions of memory that have names and can hold pieces of information(values), that we refer to as variables.

method

A method is an action that Python can perform on a piece of data. Every method is followed by a set of parentheses because, because methods often need additional information to do their work.

Variables

A named location in memory which stores a value

Avoiding syntax errors with strings

A syntax error occurs when Python doesn't recognize a section of your program as valid Python code. If you use apostrophes within single quotes it will produce a syntax error.

syntax error

A syntax error occurs when Python doesn't recognize a section of your program as valid python code.

Interpreting

A way to translate computer programming into machine instructions in which each line of the program is encountered and immediately turned into machine instructions that are run.

Compiling

A way to translate computer programming into machine instructions where the whole program is taken at once and it tried to figure out the best machine instructions to do what that program meant to do.

Concantenation

Addition is also defined for strings. When we add two strings together the result is a new string with one string being added to the end of the other. This is represented with the addition sign.

Traceback

An record of where the program ran into trouble while trying to run your code.

how we store memories

As programmers we deal with storage based on what data we want to read in for attention or temporary working memory or write out to files that can store it.

CPU

Central processing unit: where all the operations that our computer has come to be processed. Located on the motherboard.

Integers in Python 2

Division of Integers in Python 2 results in an integer with the remainder omitted. Ex: 3/2 Output: 1

rstrip() method

Ensures there is no extra whitespace on the right side of a string. Ex: favorite_language = "python " favorite_language "python " favorite_language.rstrip() "python" favorite_language "python " #to remove the whitespace from the string permanently you need to store the stripped value back into the original variable. Ex: favorite_language = "python " favorite_language = favorite_language.rstrip() favorite_language "python"

Type

Every variable has a type, which is the way that the piece of information inside that box(variable) should be understood. Integers, floating point numbers and strings are all types.

Strings

Expressions in quotation marks; formed by characters strung together. A string is simply a series of characters and anything inside quotations is considered a string in python. Ex: "Pizza"

Convert a string to a number

If we wanted to treat a string like a number we have to convert each string to an integer or float. To do this we have to write "int" or "float" and then put the string in parentheses right afterward. Ex: a = "1" b = "3.14159" c = int(a) d = float(b) print(d) Output: 3.14159

Changing the value of one variable

If you change the value of one variable it does not change the value of any others. Even if those variables were originally defined from it. Ex: a = 2 + 5 b = a - 4 c = a * b a = 42 print(a) print(b) print(c) Output: 42 3 21

Print()

In Python the print command is a way of printing a line of data to the screen. This command consists of the word "print" followed by parentheses. Essentially the information inside the parentheses is going to be printed. We can also print multiple items at once just by listing them inside the parentheses and separating them by commas.

Whitespace

In Python whitespace refers to any nonprinting character such as spaces, tabs and end_of_line symbols.

Output statement

In the example below the first two lines assign variables a and b by asking a user to input values for each one. Let's say the user inputs the values 1 and 2. The final line is the output statement. Surprising the output statement will be 12 rather than 3. This happened because when we read data with the input command, the data we read always comes in as a string, even if the data is numerical. We didn't actually read in the numbers 1 and 2, rather the character string 1 and the character string 2. Even though they looked like numbers we were actually getting a string concatenation, not an addition. Ex: a = input("Enter value one:") b = input ("Enter value two:") print("The sum is") a + b Window: Enter value one:1 Enter value two:2 The sum is 12

Cache

In the same integrated circuit as the cpu.

Files

Input and output when we don't have any user prompt is common when we turn to files for input and output. With files we use commands called "open", "read" and "write". We don't give files any prompts before reading from them.

Combining/ concatenating strings

It can be useful to combine strings. You might want to store and first name and last name in separate variables, and then combine them when you want someone's full name. Ex: first_name = "ada" last_name = "lovelace" *full_name = first_name + " " + last_name print(full_name) Output: ada lovelace Ex: Python uses the (+) signal to combine strings. We use the + to create a full name by combing a first_name, a space represented by (" ") and last_name. You can use concatenation to compose complete messages using the information you've stored in a variable. Ex: first_name = "ada" last_name = "lovelace" full_name = first_name + " " + last_name *print("Hello, " + full_name.title() + "!") Output: Hello, Ada Lovelace! #* Here, the full name is used at * in a sentence that greets the user, and the title() method is used to format the name appropriately. This code returns a simple but nicely formatted greeting:

Main memory

Main short term memory of the computer. The working memory where we keep all of the things that are running from the operating system that we are working inside of the programs that we're executing. (Main memory source that programmers care about)

Secondary memory

Memory in permanent storage. This is where we store longer term information, like files. (Hard drive or flash drive)

Offline memory

Memory that is stored remotely; offline or over a network. Can store massive amounts of data far more than on your computer. (Tertiary data)

strip()

Method that allow you to strip white space from both sides of a string.

lstrip()

Method used to strip whitespace from the left side of a string.

Undefined operation

Most arithmetic operations between different types aren't defined. You can't add a string to an integer. An exception in Python is that we can multiple a string by an integer to get the string repeated several times. Data of different types usually don't mix.

Numbers

Numbers are used often in Python to keep score in games, represent data in visualizations, store information in web applications and so on. Python treats numbers in several different ways depending on how they're being used. Python also follows the order of operations so you can use multiple operations in one function. You can also use parentheses to modify the order of operations so that Python can evaluate your expressions in the order you specify. Ex: 2 + 3*4 14 (2 + 3) * 4 20

Changing case in a string with methods

One of the simplest tasks you can do with a string is change the case of the words in a string. Try to determine what's happening the following code. Ex: name = "ada lovelace" print(name.title()) Output: Ada Lovelace #the lower case string "ads lovelace" is stored in the variable "name". The method "title()" appears after the variable in the print statement. The dot (.) after "name" in "name.title())" tells Python to make the "title()" method and on the variable "name." Every method is followed by a set of parentheses because, because methods often need additional information to do their work. The "title()" function doesn't need any additional information so the parentheses are empty. The "title()" function displays each word in title case where each begins with an uppercase letter.

Registers

Other type of memory built right into the cpu. (Really short term memory)

floats

Python considers any number with an integer a float.

Python programs are referred to as scripts because:

Python is an interpreted language that offers some powerful high level commands. It can be used to automate complex tasks in just a few lines of code.

Exponents

Python uses two multiplication symbols to represent an exponent. Ex: 3**2 Output: 9

Keywords

Python's built in commands, such as "print." They aren't able to be used as the name of a variable.

RAM

Random access memory between the mother board main memory source.

Avoiding type errors with the str() function

Say you want to wish someone a happy birthday. You may try to use the code below. Ex: age = 23 message = "Happy " + age + "rd Birthday!" print(message) Though you might think that you will get the desired result, you will end up with a syntax error because The program will not be able to decide if you are trying to print the integer "23" or the characters "2 and 3" Instead you should write the code like this. Ex: age = 23 message = "Happy " + str(age) + "rd Birthday!" print(message) Output: Happy 23rd Birthday!

Operations with variables

Standard operations/ such as subtraction, addition, multiplication and division -are built in to the CPU.

Comments

The comments are the lines that begin with the "#" pound sign. Comments are text that's meant for people reading the code. They're ignored by the computer so their only real purpose is to tell someone reading the code how to understand it.

Cloud storage

The computer treats tertiary memory like secondary memory.

Assignment Operator

The equal sign "=" in an assignment statement, takes the thing on the right hand side, and assigns it to the box on the left hand side.

ordering

The order that instructions are given is the order in which they'll be executed.

Printing in Python 2

The print statement has a slightly different syntax in Python 2. Ex: print "Hello Python 2.7 world!" Hello Python 2.7 world! # Parentheses aren't needed around the phrase to print in Python 2. Technically print is a function in Python 3 which is which it needs parentheses. In Python 2 some print statements will have parentheses but the behavior is a bit different than what you'll see in Python 3. Basically, when using Python two you'll see some print statements with and without parentheses.

Input()

The python command that is used to get input from the user. This can be used to get information that a user types in. The input command is put at the right side is a (variable) assignment statement. It gets whatever value a user types in so that it can be assigned to whatever variable is on the left.

Assigning values

The right hand side of an assignment can be more complex. It can be numbers with a decimal point called floating point number or floats. Or we can assign a word. For example x="make pizza"

Input/output commands

Third critical aspect of a computer is its input output or I/O. Computers can take input from a variety of sources and send output several places. Ex: If our I/O is a simple text window, input will be someone typing something into that window with a keyboard and output will be any text written out to that window.

Stripping whitespace

To a programmer the strings "python" and "python " look like the same thing but to a program they are two different strings. Python detects the extra space in "python " and considers it significant unless you tell it otherwise. Python can look for extra whitespace on the right and left sides of a string. In order to ensure there's no extra whitespace on the right side of a string is the rstrip() method. In the real word these strip functions are used mostly to clean up user input before it's stored in a program.

Newline

To add a new line to a text use the character combination "\n" Ex: print("Languages:\nPython\nC\nJavascript") Output: Languages: Python C JavaScript

Tab

To add a tab to your text use the character combination "\t" as shown below. Ex: #without tab print(Python) Output: Python #with tab print(\tPython) Python

Adding white space to strings with Tabs or New lines

To add a tab to your text use the character combination "\t" as shown below. Ex: #without tab print(Python) Output: Python #with tab print(\tPython) Python To add a new line to a text use the character combination "\n" Ex: print("Languages:\nPython\nC\nJavascript") Output: Languages: Python C JavaScript

Prompt the user for input

To display some text on the screen to prompt a user for input, the input command also lets us include a quoted string inside the parentheses. This will be printed out right before the user types in input.

\n

To start a new line print a string with the code "\n" inside. The /n is called a "new line" character and is interpreted as end this line and go to the next.

Variables in memory

Variables(boxes) held in temporary memory.

If no string included

We don't have to give a prompt to get input from a user. If our program has an input command that doesn't include a string in the parameters, our program will just wait for the user to type in input.

hello_world.py

When you run the file hello_world.py, the ending .py indicates that the file is a Python Program. Your editor then run the file through the python interpreter, which reads through the program and determines what each word In the program means. For example when the interpreter sees the word print, it prints to the screen whatever is between the two parentheses.

Memory

Where the variables in a program live

Integers

You can (*), subtract (-), divide (/) or (*) multiply integers in Python.

Combining tabs and newlines

You can also combine tabs and newlines within a script. The string "\n\t" tells Python to move to a newline and to start the newline with a tab. Ex: print("Languages:\n\tPython\n\tC\n\tJavascript") Output: Languages: Python C Javascript

Basic example of operations with variables

a = 2 + 5 b = a - 4 c = a * b print(a) print(b) print(c) Output: 7 3 21

Print command examples

a = input("Enter a value:") print(a) b = input() print("You entered", b) Output: Enter a value:

variable assignment

an instruction that sets a variable to a value. Ex: X=3 The left hand side of the assignment is always gong to be the name of the variable (in this case x). The equal sign "=" is called an assignment operator. The 3 is the value assigned to the variable.

Store entire message in variable using concatenation

first_name = "ada" last_name = "lovelace" full_name = first_name + " " + last_name message = "Hello, " + full_name.title() + "!" print(message) Output: Hello, Ada Lovelace! #in this example we use concatenation to compose an entire message and then store it in a variable. This makes the final print statement much simpler though you can get the same result in other ways.

Avoiding name errors when using variables

message = "Hello Python Crash Course reader!" print(mesage) #When an error occurs in your program, the python interpreter does it best to help you figure out what that error is. The interpreter provides a traceback(a record of where the program ran into trouble) when a program cannot run successfully. Ex: Traceback (most recent call last): 1) File "hello_world.py", line 2, in <module> 2) print(mesage) 3)NameError: name 'mesage' is not defined # 1) reports than an error occurred in line 2 in the file hello_world.py. 2) tells us what kind of error it found. 3) in this case it found a name area and reports that the variable 'mesage' which is being printed was not defined.

Printing a second message

message = "Hello Python World!" print(message) message = "Hello Python crash course!" print(message) Output: Hello Python World Hello Python crash course

hello_world variable example

message = "Hello Python World!" print(message) Output: Hello Python World! #the variable in this case is "message" and the value assigned to this variable was "Hello Python World!"

How to use single quotes and double quotes correctly

message = "One of Python's strengths is its diverse community" print(message) Output: One of Python's strengths is its diverse community #however this is what will happen if we use single quotes in this code will produce a syntax error. message = 'One of Python's strengths is its diverse community' print(message) Output: File "apostrophe.py", line 1 message = 'One of Python's strengths is its diverse community.' SyntaxError: invalid syntax

Two Other useful basic methods

name = "ada lovelace" print(name.uppercase()) print(name.lowercase()) Output: ADA LOVELACE ada lovelace #the lower case method is particularly useful for storing data. Many times you won't want to trust the capitalization that your users provide, so you'll convert strings to lowercase before storing them. Then when you want to display the information, you'll use the case that makes the most sense for each string.


Set pelajaran terkait

CH. 10: Understanding Meats and Game

View Set

Chapter 9: From Here to Your Career

View Set

Business Law Chapter 1: The Nature and Sources of Law

View Set