python basics

of 30 /30
Python Basics: Statements Expressions Loops Strings Functions

Author: young-alista

Post on 23-Jan-2017




0 download

Embed Size (px)


Slide 1

Python Basics:StatementsExpressionsLoopsStringsFunctions

#ProgramA program is a sequence of instructions or statements.To run a program is to:create the sequence of instructions according to your design and the language rulesturn that program into the binary commands the processor understandsgive the binary code to the OS, so it can give it to the processorOS tells the processor to run the programwhen finished (or it dies :-), OS cleans up.


Example Code Listing# 1. prompt user for the radius, # 2. apply the area formula# 3. print the results

import mathradiusString = input("Enter the radius of your circle:")radiusFloat = float(radiusString)circumference = 2 * math.pi * radiusFloatarea = math.pi * radiusFloat * radiusFloat

print()print("The cirumference of your circle is:",circumference,\ ", and the area is:",area)


Getting InputThe function: input(Give me a value)prints Give me a value on the screen and waits until the user types something (anything), ending with [Enter] keyWarning! Input() returns a string (sequence of characters), no matter what is given. (1 is not the same as 1, different types)Convert from string to integerPython requires that you must convert a sequence of characters to an integerOnce converted, we can do math on the integers


Import of MathOne thing we did was to import the math module with import mathThis brought in python statements to support math (try it in the python window)We precede all operations of math with math.xxxmath.pi, for example, is pi. math.pow(x,y) raises x to the yth power.


Assignment StatementThe = sign is the assignment symbolThe value on the right is associated with the variable name on the leftA variable is a named location that can store values (information). A variable is somewhat like a file, but is in memory not on the HD.= Does not stand for equality here!What assignment means is:evaluate all the stuff on the rhs (right-hand-side) of the = and take the resulting value and associate it with the name on the lhs (left-h-s)

#Printing OutputmyVar = 12print(My var has a value of:,myVar)print() function takes a list of elements to print, separated by commasif the element is a string, prints it as isif the element is a variable, prints the value associated with the variableafter printing, moves on to a new line of output

#SyntaxLexical components.A Python program is (like a hierarchy):.A module (perhaps more than one)A module is just a file of python commandsEach module has python statementsStatements may have expressionsStatements are commands in Python.They perform some action, often called a side effect, but do not return any valuesExpressions perform some operation and return a value


Side Effects and ReturnsMake sure you understand the difference. What is the difference between a side effect and a return?1 + 2 returns a value (its an expression). You can catch the return value. However, nothing else changed as a resultprint hello doesnt return anything, but something else - the side effect - did happen. Something printed!

#Whitespacewhite space are characters that dont print (blanks, tabs, carriage returns etc.For the most part, you can place white space (spaces) anywhere in your programuse it to make a program more readableHowever, python is sensitive to end of line stuff. To make a line continue, use the \print this is a test, \ of continuationprintsthis is a test of continuation

#Python TokensKeywords:You are prevented from using them in a variable nameanddelfromnotwhileaselifglobalorwithassertelseifpassyieldbreakexceptimportprintclassexecinraisecontinuefinallyisreturndefforlambdatry

Reserved operators in Python (expressions):+-***///%>&|^~===!=


Python PunctuatorsPython punctuation/delimiters ($ and ? not allowed). #\()[]{}@,:.`=;+=-=*=/=//=%=&=|=^=>>= prints eprint helloStr[-1] => prints dprint helloStr[11] => ERROR

#Basic String Operations+ is concatenationnewStr = spam + - + spam-print newStr spam-spam-

* is repeat, the number is how many timesnewStr * 3 spam-spam-spam-spam-spam-spam-


String Function: lenThe len function takes as an argument a string and returns an integer, the length of a string.

myStr = Hello Worldlen(myStr) 11 # space counts

#ExampleA method represents a special program (function) that is applied in the context of a particular object. upper is the name of a string method. It generates a new string of all upper case characters of the string it was called with.myStr = Python Rules!myStr.upper() PYTHON RULES!

The string myStr called the upper() method, indicated by the dot between them.

#FunctionsFrom mathematics we know that functions perform some operation and return one value.Why to use them?Support divide-and-conquer strategyAbstraction of an operationReuse: once written, use againSharing: if tested, others can useSecurity: if well tested, then secure for reuseSimplify code: more readable


Python InvocationConsider a function which converts temps. in Celsius to temperatures in Fahrenheit:Formula: F = C * 1.8 + 32.0Math: f(C) = C*1.8 + 32.0Python def celsius2Fahrenheit (C): return C*1.8 + 32.0

Terminology: C is an argument to the function


Return StatementFunctions can have input (also called arguments) and output (optional)The return statement indicates the value that is returned by the function.The return statement is optional (a function can return nothing). If no return, the function may be called a procedure.


#from turtle import *

def draw_square (size): for i in range (4): forward (size) right(90)