1 / 151

Understanding the Basics

Understanding the Basics. PRINTING. Some Python codes. 6+9 Print 6+9 Print “6+9” aa=6+9 print aa aa=6 bb=9 aa+bb. Print. Python command print – Displays data, values, and expressions

dycus
Download Presentation

Understanding the Basics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Understanding the Basics

  2. PRINTING

  3. Some Python codes • 6+9 • Print 6+9 • Print “6+9” • aa=6+9 print aa • aa=6 bb=9 aa+bb

  4. Print Python command print – Displays data, values, and expressions The single and double quotation mark string objects, which are collections of texts surrounded by quotes.

  5. Be familiar with Python printing >>> print ("Hello, World! ") Hello, World! >>> "hello" 'hello' >>> "world" 'world' >>> "hello"+"world" 'helloworld'

  6. Be familiar with Python printing >>> "hello" * 3 'hellohellohello' >>> "hello" * 300

  7. Variables • Are not declared, just assigned • The variable is created the first time you assign it a value • Are references to objects • Type information is with the object, not the reference • Everything in Python is an object

  8. Variables • variable: A named piece of memory that can store a value. • Usage: • Compute an expression's result, • store that result into a variable, • and use that variable later in the program. • assignment statement: Stores a value into a variable. • Syntax: name = value • Examples: x = 5 gpa = 3.14 x 5 gpa 3.14 • A variable that has been given a value can be used in expressions. x + 4 is 9 • Exercise: Evaluate the quadratic equation for a given a, b, and c.

  9. Everything is an object • Everything means everything, including functions and classes (more on this later!) • Data type is a property of the object and not of the variable >>> x = 7 >>> x 7 >>> x = 'hello' >>> x 'hello' >>>

  10. Look at a sample of code… assignments, arithmetics, if, print Look at a sample of code… x = 34 - 23 # A comment. y = “Hello”# Another one. z = 3.45 if z == 3.45 or y == “Hello”: x = x + 1 y = y + “ World”# String concat. print x print y

  11. Declare a variable and assign its value Example: Area of a rectangle >>> width = 20 >>> height = 45 >>> area = width * height >>> area 900

  12. Evaluation of expressions in Python >>> print ("Hello, World! ") Hello, World! >>> 10 + 25 35 >>> 124 – 125 -1 >>> 1/3 0.333333333333333

  13. Print of long lines • print : Produces text output on the console. • Syntax: print "Message" print Expression • Prints the given text message or expression value on the console, and moves the cursor down to the next line. print Item1, Item2, ..., ItemN • Prints several messages and/or expressions on the same line. • Example: print "Hello, world!" age = 45 print "You have", 65 - age, "years until retirement" Output: Hello, world! You have 20 years until retirement

  14. Enough to Understand the Code • Assignment uses = and comparison uses ==. • For numbers +, -, *, /, % are as expected. • Special use of + for string concatenation. • Special use of % for string formatting. • Logical operators are words (and, or, not) not symbols (&&, ||, !). • The basic printing command is “print.” • First assignment to a variable will create it. • Variable types don’t need to be declared. • Python figures out the variable types on its own.

  15. Basic Datatypes • Integers (default for numbers) z = 5 / 2 # Answer is 2, integer division. • Floats x = 3.456 • Strings Can use “ ” or ‘ ’ to specify. “abc” ‘abc’ (Same thing.) Unmatched ones can occur within the string. “matt’s” Use triple double-quotes for multi-line strings or strings than contain both ‘ and “ inside of them: “““a‘b“c”””

  16. Comments • Start comments with # – the rest of line is ignored. • Can include a “documentation string” as the first line of any new function or class that you define. • The development environment, debugger, and other tools use it: it’s good style to include one. defmy_function(x, y): “““This is the docstring. This function does blah blah blah.”””# The code would go here...

  17. Python Build-in types • Numbers 3.1415 • Strings “Hello World” • Lists [1,2,3,4] • Dictionaries {‘test’: ‘yum’} • Files input=open(‘file.txt’, ‘r’)

  18. TEST: What are the outputs? Why? >>> a=3 >>> b=4 >>> a+1 >>> b*3 >>> b/3 >>> b/3.0 >>> b**2 >>> 2+4.0 >>> 2.0**b

  19. Hello World Program

  20. Hello World Program • Implement by three different languages • In C • In JAVA • In Python

  21. “Hello World” in C main() { printf("hello, world\n"); }

  22. “Hello World” in C #include <iostream> using namespace std; main() { cout<<“Hello World” ; }

  23. “Hello World” in JAVA class myfirstjavaprog { public static void main(String args[]) { System.out.println("Hello World!"); } }

  24. “Hello World” in Python print "hello World!"

  25. “Hello World” in Python print (“Hello World!!”)

  26. Your first Python program- hello.py # This program says hello and asks for my name. hello = 'Hello world! ' print(hello) print('What is your name?') myName = input() print('It is good to meet you, ' + myName)

  27. hello.py executed sequentially # This program says hello and asks for my name. Any text following a # sign is a comment. Comments are not for the computer, but for you, the programmer.  hello = 'Hello world! ' # assign the string to a name print(hello) # call the print( ) function print('What is your name?') # call the print( ) function myName = input() # call the input( ) function print('It is good to meet you, ' + myName)

  28. Arithmetic Expressions • expression: A data value or set of operations to compute a value. Examples: 1 + 4 * 3 42 • Arithmetic operators we will use: • + - * / addition, subtraction/negation, multiplication, division • % modulus, a.k.a. remainder • ** exponentiation • precedence: Order in which operations are computed. • * / % ** have a higher precedence than + -1 + 3 * 4 is 13 • Parentheses can be used to force a certain order of evaluation.(1 + 3) * 4 is 16

  29. Integer division • When we divide integers with / , the quotient is also an integer. 3 52 4 ) 14 27 ) 1425 12135 2 75 54 21 • More examples: • 35 / 5 is 7 • 84 / 10 is 8 • 156 / 100 is 1 • The % operator computes the remainder from a division of integers. 3 43 4 ) 14 5 ) 218 1220 2 18 15 3

  30. Real numbers • Python can also manipulate real numbers. • Examples: 6.022-15.999742.02.143e17 • The operators +-*/% **() all work for real numbers. • The / produces an exact answer: 15.0 / 2.0 is 7.5 • The same rules of precedence also apply to real numbers:Evaluate () before */% before +- • When integers and reals are mixed, the result is a real number. • Example: 1 / 2.0 is 0.5 • The conversion occurs on a per-operator basis. • 7 / 3 * 1.2 + 3 / 2 • 2 * 1.2 + 3 / 2 • 2.4 + 3 / 2 • 2.4 + 1 • 3.4

  31. Math commands • Python has useful commands for performing calculations. • To use many of these commands, you must write the following at the top of your Python program: from math import *

  32. Numbers

  33. Number in Action • Perhaps the best way to understand numerical objects is to see them in action. >>> a=3 #Name Created >>> b=4

  34. Number in Action >>> a+1, a-1 # (3+1), (3-1) (4,2) >>> b*3, b/2 (12,2)

  35. Number in Action >>> 1 / 2.0 0.5 >>> 1/2 0 >>> 1 % 2 1

  36. Simple Data Types • Triple quotes useful for multi-line strings >>> s = """ a long... string with "quotes" or anything else""">>> s' a long\012string with "quotes" or anything else' >>> len(s)45

  37. Numbers: Integers • Integer – the equivalent of a C long • Long Integer – an unbounded integer value. >>> 132224 132224 >>> 132323 ** 2 17509376329L >>>

  38. Numbers: Floating Point • int(x) converts x to an integer • float(x) converts x to a floating point • The interpreter shows a lot of digits >>> 1.23232 1.2323200000000001 >>> print 1.23232 1.23232 >>> 1.3E7 13000000.0 >>> int(2.0) 2 >>> float(2) 2.0

  39. exercises • Geometric calculations for robots • Speed and acceleration • Pythagoras Theorem • Braitenberg Vehicles. • Logic operators. • Defining functions. • If

  40. Numbers: Complex • Built into Python • Same operations are supported as integer and float >>> x = 3 + 2j >>> y = -1j >>> x + y (3+1j) >>> x * y (2-3j) End of lecture 1

  41. 4.5 4.5 7.5 x x y y Numbers are immutable >>> x = 4.5 >>> y = x >>> y += 3 >>> x 4.5 >>> y 7.5

  42. Strings

  43. Strings • The next major build-in type is the Python STRING --- an ordered collection of characters to store and represent text-based information • Python strings are categorized as immutable sequences --- meaning they have a left-to-right order(sequence) and cannot be changed in place (immutable) • This definition of immutable sequences is sufficient for now. You will learn more from examples.

  44. Single- and Double-Quoted • Single- and Double-Quoted strings are the same >>> ‘Hello World’ , “Hello World” • The reason for including both is that it allows you to embed a quote character of the other inside a string >>> “knight’s” , ‘knight”s’

  45. Strings in Action • Basic operations: 1. len() 2. + 3. * length concatenate repetition

  46. len() • The len build-in function returns the length of strings >>> len(‘abc’) >>> a=‘abc’ >>> len(a) length

  47. + • Adding two string objects creates a new string object >>> ‘abc’ + ‘def’ >>> a=‘Hello’ >>> b=‘World’ >>> a + b >>> a+ ‘ ’ +b Hello World with space Concatenation of strings

  48. * • Repetition may seem a bit obscure at first, but it comes in handy in a surprising number of contexts • For example, to print a line of 80 dashes >>> print ‘-’ * 80

  49. Slices and Indexes

  50. Indexes in slices • Characters in a string are numbered with indexes starting at 0: • Example: name = "P. Diddy" • Accessing an individual character of a string: variableName[index] • Example: print name, "starts with", name[0] Output: P. Diddy starts with P

More Related