Basics of Programming Working with Programs Programs dont
Basics of Programming
Working with Programs • Programs don’t work in isolation… they need inputs and need to produce something (outputs) • Outputs – your pictures – Often you want text outputs – answers to the question.
Outputs • Print command prints output to the console window. • print is a function – followed by () • Put what you want printed in the parentheses – string, numbers, etc. • Example: print(“Hello world”) print(‘Hello world’) print(‘‘‘Hello world My name is George. ’’’) print(5) print(3. 14 * 7)
Outputs • Why do you think you have the option of the single & double quotes? • Example: print(‘Hello world, call me “Mrs. Holmes” ’)
Comments • Comments start with the # • Use them to explain challenging code or to separate parts of your code. • They can be at the end of a line or can be a whole line • Don’t comment obvious lines • Use 3 quotes as multi-line comments: # written by Mrs. Holmes ‘‘‘ This is a multi-line comment ’’’
Variables and Types
Variables • We need to be able to store information that the program is working with. • A variable is just a place in memory. • The computer doesn’t care, but people don’t like working with memory addresses (Ex: A 95 BFC)
Variables You should name your variables with names that make sense. Examples: a, b, c - what are these? ? ? my. Name, age, grade – better
Variables Python has some rules for names (naming convention): – Start with lower case characters – Can contain numbers, underscores, and $. – Use bumpy caps (camel case) for readability, but always start with a lower case character. • They are case-sensitive: test and Test are two different variables according to Python. • Variables do not have a type – values do.
Variables We name our variables with names that make sense to us. Make them readable: grosspay payrate gross. Pay pay. Rate gross_Pay pay_rate
Assigning Values • In math, “=“ means “is equal to” • In Python, “=“ means “is assigned to” num. Students = 10 // assign 10 = num. Students // NOOOO
Variables Some words have special meaning to Python and cannot be used as variable names. These are called reserved words. and del as elif assert else break except class nonlocal continue def for from global if import in finally lambda not or pass print raise is try while with yield return
Variable Types
Number Types • int: This is the basic integer type in python. • float: This is a number that has a decimal (binary floating point).
Number Types • long: This is a integer number that's length is non-limited. In python 2. 2 and later, Ints are automatically turned into Long the value get too big for Int. • complex: This is a complex number. We aren’t doing anything with this type this year.
Working with Strings • String: A sequence of characters that are enclosed in quotes. • They can be included in a single quote (‘), double quote(“) or triple quotes (‘’’) • The triple quotes are used for multi-line strings. • Strings cannot be changed (immutable): When you change a string you actually are creating a new copy of it.
Functions • Functions are named bits of code that you can run. • There are MANY functions and operators you can use on strings, but we’ll talk about a few. • Function names are always followed by parentheses, sometimes with something inside.
General: Using Functions • You call functions by the function name followed by parentheses: print(“blue”) main() • If you need to give the function more information, it goes inside the parentheses. These values are called arguments.
Reading in Values Sometimes you need to get input from the user. You use the “input” command, which always reads in the number value. You can tell the user what you want them to type in using the prompt. variable = input(prompt) Example: dog. Age = input(“What is your dog’s age? ”)
Reading in Values If you want text (string) input from the user, you can use the input or the raw_input command. Examples: dog. Name = input(“What is your dog’s name? ”) ‘Fluffy’ dog. Name = raw_input(“What is your dog’s name? ”) Fluffy raw_input expects a string so you don’t have to type the “ “ in your answer.
Changing a Value’s Type Sometimes you need to change the type of a value. You can convert between types using int, float, or str: integer_variable = int(var) decimal_variable = float(var) string_variable = str(number) dog. Age = int(3. 7) dog. Weight = float(“ 35”)
Using Functions with Objects Sometimes you call a function on an object. When you are calling a function that operates on your variable, you use “dot-notation”: my. Variable. Name. the. Function() my. Circle. setfill(“blue”) Many of the string functions we are about to talk about are this type of function, so you’ll use: string. Name. function()
String Functions my. String = ‘The happy programmers loved Python’ upper: converts the string to uppercase. my. String. upper() lower: converts the string to lowercase. len: returns the length of the string len(my. String)
String Class Functions replace: replaces one string with another string my. String = ‘The happy programmers loved Python’ my. String. replace(‘The’, ’All the’) print(my. String) prints: All the happy programmers loved Python
String Class Functions concatenate: combines strings teacher = ‘Mrs. Holmes’ print(‘Three programmers and ’ + teacher) multiples: writes out the string multiple times print(‘blah ’ *3) prints: blah
String Functions String positions start at 0. my. String = "CS Rocks! " my. String C S 0 1 R o 2 3 4 c 5 k s ! 6 7 8
String Functions 1 my. String = "CS Rocks! " C S 0 1 R o 2 3 4 c 5 k s 6 7 ! 8 You can take slices of a string: my. String[ first pos to include: first pos not included ] Example: my. String[0: 2] =>
String Functions find: finds the starting place where the string in the parenthesis starts in my. String. find(‘happy’) my. String. find(‘sad’) # What happens?
• Give assignment at this point
Working with Functions You can pass a function to a function: print(input(“How old is your dog? ”)) dog. Height = float(input(“How tall is he? ”))
Operators – all are familiar
Operators: Note the Division Operators
Operators • Arithmetic: +, -, * for addition, subtraction, multiplication • Follows standard order of operation (PEMDAS) • Order goes left to right. • Logic / comparisons: >, <, ==, >=, <=, != • Logical operators have higher precedence (are executed before) arithmetic operators.
Division Operators • Division: / regular division – watch integer division • Remainder: % what remains after integer division 8/5= 8%5 =
Division Operators x = 10 y=3 z = x/y # what is z equal to? print(str(z)+" is " + str(type(z))) w = x/float(y) # what is w equal to? print(str(w)+" is " + str(type(w))) v = x%y # Modulo - remainder print(str(v)+" is " + str(type(v)))
Defining Functions The code for a function is known as a function definition. To execute the function, you write a statement that calls it. def functionname(arg 1, arg 2, . . . ): statement 1 statement 2 The indentation is how Python decides which statements are in the function. Where def is a Python reserved word. arg 1 and arg 2 are parameters (allows you to pass data into the method A function does not have to include parameters, but must have the parentheses.
Syntax: A function may do lots of things : def double. Value ( x ): ans = x + x print(“The answer is ”, ans) ## calling double. Value in the interactive part of Canopy double. Value ( 6 ) Notice that we called double. Value using 6 not x. x is the name of the variable INSIDE the function. It is assigned the value of 6 when we make the call.
Syntax: A function may give back an answer, in the form of a return value: def double. Value ( x ): return x + x ## calling double. Value: my. Val = double. Value ( 6 ) Notice that we called double. Value was assigned to a variable. If it hadn’t been, we would have lost the answer.
About Return Statements When Python executes the return statement, it exits the function. Any statements that follow the return statement will not be executed. Example: What will happen? def calc. Something(): x=4 y=5 return x return y
- Slides: 39