1 / 23

Elementary Python Programming

Elementary Python Programming. Quadratic Roots. Our goal is to write a simple Python script (program) to find the real roots of a quadratic equation. Here is what a run of the program should look like. First Steps. We first print the program description:

armina
Download Presentation

Elementary Python Programming

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. Elementary Python Programming

  2. Quadratic Roots • Our goal is to write a simple Python script (program) to find the real roots of a quadratic equation. • Here is what a run of the program should look like.

  3. First Steps We first print the program description: print("\nYou are to enter the", "coefficients a,b,c of the", "quadratic equation") print ("ax^2 + bx + c = 0 and the“, "solution will be presented\n")

  4. First Steps Next, prompt for, and input, the coefficients: a = int(raw_input("Enter coefficient a: ")) b = int(raw_input("Enter coefficient b: ")) c = int(raw_input("Enter coefficient c: ")) Why did we use the int() converter? Because the raw_input() function always return a string.

  5. Mathematical Solution

  6. Branching • Notice that we must do different things depending on the truth value of an expression • Most programming languages provide for these situations by means of ifstatements • Python versions: if <condition>: <statements1>else: <statements2> if <condition1>: <statements1>elif <condition2>: <statements2> else: <statements3>

  7. Square Roots • The square root function is not a Python built-in function • However, it is provided by the Python math module • So we must importthat module by placing the following statement at the top of our program file: import math • Now we may use the function sqrt to calculate a square root. • However, since it comes from an imported module, we must precede it by the module name and a .: math.sqrt()

  8. Finishing the Script • So here is the final part of our script. d = b*b-4*a*c # the discriminant if d < 0: print('The equation has no real roots') elif d == 0: print('The equation has unique root',-b/(2*a)) else: r1 = (-b + math.sqrt(d))/(2*a) r2 = (-b - math.sqrt(d))/(2*a) print('The roots of the equation are',r1,r2)

  9. A More Complicated Problem • We want to determine if a string could overlap itself. • For example s = 'abcdefabc' overlaps itself as follows: abcdefabcabcdefabc • So does the string t = 'abcda' : abcdaabcda • So we want to write a function that finds the minimum index i such that the first i characters are the same as the last i characters of a string.

  10. A More Complicated Problem • We want to write a function that finds the smallest positive index i such that the first i characters of a string s are the same as the last i characters of s. • How can we describe the first i characters of string s? • s[:i], which is the same as s[0:i] and consists of the characters at indices 0,1, …,i-1. • The last i characters are given by s[-i:]. • The obvious approach is to • compare s[:1] with s[-1] • then compare s[:2] with s[-2] • and so on until we either find a match or our comparison index reaches len(s) • Most programming languages provide ways to do repeated execution, and the while construct is a common methodology

  11. While Loops • The general form of a Python while statement is: while <condition>: <one or more statements> # body where <condition> is an expression that evaluates to either True or False. • Execution proceeds as follows: • <condition>is evaluated • if the result is False, execution continues with the statement after the while statement. • if the result is True, the body is executed and the condition is evaluated; • This continues until the condition becomes false.

  12. While Loops • Very simple example to print the numbers from 1 to 3: i = 1 while i <= 3: print(i) i += 1 Loop unwound:Output i = 1 1 <= 3 True print(1) 1 i= 2 2 <= 3 True print(2) 2 i = 3 3 <= 3 True print(3) 3 i = 4 4 <= 3 False, so done

  13. While Loops • So here is the code for our overlap function, which we would put in a file called, say, myoverlap.py. def overlaps(s): i = 1 while i < len(s) and s[:i] != s[-i:]:i += 1 if i == len(s): return -1 else: return i

  14. Simple Assignment • Assignment: Right Triangle • In a file called rightTriangle.py, create a python script in the file that • prompts for and inputs three integers; • then prints a statement indicating whether the numbers are the lengths of the sides of a right triangle. • Your output should be one of the following: The numbers are the side lengths of a right triangle The numbers are not the side lengths of a right triangle Note: three numbers are the side lengths of a right triangle if and only the square of one of them is the sum of the squares of the others.

  15. Random Module • The random module provides for the generation of (pseudo) random numbers • We will now illustrate the use of this module for a very, very simple simulation example. • The game of craps is played with two six-sided dice. • To start a game, the player rolls the dice and checks the total of the values on the up side of the two dice. • If the total is 7 or 11, the player wins immediately • If the total is 2, 3 or 12, the player loses immediately • Otherwise the total becomes the “point” • The player now continue to roll the dice until he hits either the point value or 7 • If he hits the point, he wins; if he hits 7, he loses

  16. Craps Simulation • We will put our code in a file named craps.py • First, we create a function named roll_and report()that simulates a single roll of the dice. • The function will generate a random integer between 1 and 6 for the value on the first die • Then generate a second value for the second die • Finally, roll_and report()will report the die values and the total to the user and return the total • Next, we create a function play_game to simulate the playing of one game • The rest of our script consists of a call to the play_game function • We will ignore for now the value returned by play_game

  17. Roll and Report Function import random # Now the methods from the random module are available def roll_and_report(): die1 = random.randint(1,6) # 1 ≤ die1 ≤ 6 die2 = random.randint(1,6) # 1 ≤ die2 ≤ 6 total = die1+die2 print( '\ndie1: ', die1, '\ndie2: ', die2, '\ntotal: ', total,'\n') return total

  18. Function play_game def play_game(): print("Here we go with your first roll.") total = roll_and_report() if total == 7 or total == 11: print("Congratulations! You won the game on the first roll.\n") elif total == 2 or total == 3 or total == 12: print("Uh-oh, you lost the game on the first roll!\n") # The total now becomes the “point” and we continue rolling the dice

  19. Function play_game else: raw_input("Hit enter to continue\n") # For better presentation on screen point = total print("You must roll a total of ", point, " to win") print("If you roll a 7 before ",point,", you lose") raw_input("\nHit enter to continue") total = roll_and_report() while total != 7 and total != point: total = roll_and_report() raw_input("\nHit enter to continue") if total == 7: print('\nGame over, you lose') return 0 else: print("\nYou hit the point, you win!") return 1

  20. Rest of the Script print("\n\nWelcome to the Casino game of Craps") play_game()

  21. Sample Runs of craps.py

  22. Sample Runs of craps.py

  23. Another Assignment • You are to modify the file craps.py so that the user plays a game, then is asked whether she wishes to play again (response should be ‘Y’ or ‘N’) • If ‘Y’, another game is played and the question asked again. • This continues until the player enters ‘N’ • Addendum: you might make your code a little more friendly by recognizing ‘y’ as ‘Y’ and ‘n’ as ‘N’.

More Related