Text
stringlengths
1
9.41k
We start by setting it equal to the user’s first number.
Then, every time we get a new number from the user, we check to see if the user’s number is larger than the current largest value (which is stored in largest).
If it is, then we set largest equal to the user’s number. If, instead, we want the smallest value, the only change necessary is that > becomes <, though it would also be good to rename the variable largest to smallest. Later on, when we get to lists, we will see a shorter way to find the largest and smallest values, ...
Here is an example that determines if a number is prime.|Col2| |---|---| ||| |num = eval(input('Enter number: ')) flag = 0 for i in range(2,num): if num%i==0: flag = 1 if flag==1: print('Not prime') else: print('Prime')|| |ommon programming task is to find the largest or smallest value in a series of values.
Here is example where we ask the user to enter ten positive numbers and then we print the largest one.|Col2| |---|---| ||| |largest = eval(input('Enter a positive number: ')) for i in range(9): num = eval(input('Enter a positive number: ')) if num>largest: largest=num print('Largest number:', largest)|| ----- _5.6.
COMMENTS_ 37 ###### 5.6 Comments A comment is a message to someone reading your program.
Comments are often used to describe what a section of code does or how it works, especially with tricky sections of code.
Comments have no effect on your program. **Single-line comments** For a single-line comment, use the # character. _# a slightly sneaky way to get two values at once_ num1, num2 = eval(input('Enter two numbers separated by commas: ')) You can also put comments at the end of a line: count = count + 2 _# each divisor...
Often you will want to modify your program but don’t want to delete your old code in case your changes don’t work.
You could comment out the old code so that it is still there if you need it, and it will be ignored when your new program is run.
Here is a simple example: """ print('This line and the next are inside a comment.') print('These lines will not get executed.') """ **print('This line is not in a comment and it will be executed.')** ###### 5.7 Simple debugging Here are two simple techniques for figuring out why a program is not working: 1.
Use the Python shell.
After your program has run, you can type in the names of your program’s variables to inspect their values and see which ones have the values you expect them to have and which don’t.
You can also use the Shell to type in small sections of your program and see if they are working. 2. Add print statements to your program.
You can add these at any point in your program to see what the values of your variables are. You can also add a print statement to see if a point in your code is even being reached.
For instance, if you think you might have an error in ----- 38 _CHAPTER 5.
MISCELLANEOUS TOPICS I_ a condition of an if statement, you can put a print statement into the if block to see if the condition is being triggered. Here is an example from the part of the primes program from earlier in this chapter.
We put a print statement into the for loop to see exactly when the flag variable is being set: flag = 0 num = eval(input('Enter number: ')) **for i in range(2,num):** **if num%i==0:** flag = 1 **print(i, flag)** 3.
An empty input statement, like below, can be used to pause your program at a specific point: |re is an example from the part of the primes program from earlier in this chapter.
We put rint statement into the for loop to see exactly when the flag variable is being set:|Col2| |---|---| ||| |flag = 0 num = eval(input('Enter number: ')) for i in range(2,num): if num%i==0: flag = 1 print(i, flag)|| **input()** ###### 5.8 Example programs It is a valuable skill is to be able to read code.
In this section we will look in depth at some simple programs and try to understand how they work. **Example 1** The following program prints Hello a random number of times between 5 and 25. **from random import randint** rand_num = randint(5,25) **for i in range(rand_num):** **print('Hello')** The first line in t...
This just needs to appear once, usually near the beginning of your program. The next line generates a random number between 5 and 25.
Then, remember that to repeat something a specified number of times, we use a for loop. To repeat something 50 times, we would use range(50) in our for loop.
To repeat something 100 times, we would use range(100). To repeat something a random number of times, we can use range(rand_num), where rand_num is a variable holding a random number.
Although if we want, we can skip the variable and put the randint statement directly in the range function, as shown below. |ample 1 The following program prints Hello a random number of times between 5 and 25.|Col2| |---|---| ||| |from random import randint rand_num = randint(5,25) for i in range(rand_num): print('He...
EXAMPLE PROGRAMS_ 39 **Example 2** Compare the following two programs. **from random import randint** **from random import randint** rand_num = randint(1,5) **for i in range(6):** **for i in range(6):** rand_num = randint(1,5) **print('Hello'*rand_num)** **print('Hello'*rand_num)** ###### Hello Hello Hello Hello ...
In the first program, it is located outside of the for loop, and this means that rand_num is set once at the beginning of the program and retains that same value for the life of the program.
Thus every print statement will print Hello the same number of times. In the second program, the rand_num statement is within the loop.
Right before each print statement, rand_num is assigned a new random number, and so the number of times Hello is printed will vary from line to line. **Example 3** Let us write a program that generates 10000 random numbers between 1 and 100 and counts how many of them are multiples of 12.
Here are the things we will need: - Because we are using random numbers, the first line of the program should import the random module. - We will require a for loop to run 10000 times. - Inside the loop, we will need to generate a random number, check to see if it is divisible by 12, and if so, add 1 to the co...
MISCELLANEOUS TOPICS I_ ###### Indentation matters A common mistake is incorrect indentation.
Suppose we take the above and indent the last line. The program will still run, but it won’t run as expected. **from random import randint** count = 0 **for i in range(10000):** num = randint(1, 100) **if num%12==0:** count=count+1 **print('Number of multiples of 12:', count)** When we run it, it outputs a whole ...
The reason for this is that by indenting the print statement, we have made it a part of the for loop, so the print statement will be executed 10,000 times. Suppose we indent the print statement one step further, like below. **from random import randint** count = 0 **for i in range(10000):** num = randint(1, 100) **...
What will happen is every time we find a new multiple of 12, we will print the count. Neither this, nor the previous example, is what we want.
We just want to print the count once at the end of the program, so we don’t want the print statement indented at all. ###### 5.9 Exercises 1.
Write a program that counts how many of the squares of the numbers from 1 to 100 end in a 1. 2.
Write a program that counts how many of the squares of the numbers from 1 to 100 end in a 4 and how many end in a 9. 3.
Write a program that asks the user to enter a value n, and then computes (1 + 2[1] [+][ 1]3 [+] _[···]_ [+][ 1]n [)] _[−]_ ln(n).
The ln function is log in the math module. |ommon mistake is incorrect indentation. Suppose we take the above and indent the last line.
e program will still run, but it won’t run as expected.|Col2| |---|---| ||| |from random import randint count = 0 for i in range(10000): num = randint(1, 100) if num%12==0: count=count+1 print('Number of multiples of 12:', count)|| |ppose we indent the print statement one step further, like below.|Col2| |---|---| ||| ...
Write a program to compute the sum 1 − 2 + 3 − 4 + ··· + 1999 − 2000. ----- _5.9. EXERCISES_ 41 5.
Write a program that asks the user to enter a number and prints the sum of the divisors of that number. The sum of the divisors of a number is an important function in number theory. 6.
A number is called a perfect number if it is equal to the sum of all of its divisors, not including the number itself.
For instance, 6 is a perfect number because the divisors of 6 are 1, 2, 3, 6 and 6 = 1 + 2 + 3.
As another example, 28 is a perfect number because its divisors are 1, 2, 4, 7, 14, 28 and 28 = 1 + 2 + 4 + 7 + 14.
However, 15 is not a perfect number because its divisors are 1, 3, 5, 15 and 15 ̸= 1 + 3 + 5. Write a program that finds all four of the perfect numbers that are less than 10000. 7.
An integer is called squarefree if it is not divisible by any perfect squares other than 1.
For instance, 42 is squarefree because its divisors are 1, 2, 3, 6, 7, 21, and 42, and none of those numbers (except 1) is a perfect square.
On the other hand, 45 is not squarefree because it is divisible by 9, which is a perfect square. Write a program that asks the user for an integer and tells them if it is squarefree or not. 8.
Write a program that swaps the values of three variables x, y, and z, so that x gets the value of y, y gets the value of z, and z gets the value of x. 9.
Write a program to count how many integers from 1 to 1000 are not perfect squares, perfect cubes, or perfect fifth powers. 10. Ask the user to enter 10 test scores.
Write a program to do the following: (a) Print out the highest and lowest scores. (b) Print out the average of the scores. (c) Print out the second largest score. (d) If any of the scores is greater than 100, then after all the scores have been entered, print a message warning the user that a value over 100 has bee...
Write a program that computes the factorial of a number. The factorial, n!, of a number n is the product of all the integers between 1 and n, including n. For instance, 5!
= 1 · 2 · 3 · 4 · 5 = 120. [Hint: Try using a multiplicative equivalent of the summing technique.] 12. Write a program that asks the user to guess a random number between 1 and 10.
If they guess right, they get 10 points added to their score, and they lose 1 point for an incorrect guess.
Give the user five numbers to guess and print their score after all the guessing is done. 13. In the last chapter there was an exercise that asked you to create a multiplication game for kids.
Improve your program from that exercise to keep track of the number of right and wrong answers.
At the end of the program, print a message that varies depending on how many questions the player got right. 14. This exercise is about the well-known Monty Hall problem.
In the problem, you are a contestant on a game show. The host, Monty Hall, shows you three doors. Behind one of those doors is a prize, and behind the other two doors are goats. You pick a door.
Monty Hall, who ----- 42 _CHAPTER 5. MISCELLANEOUS TOPICS I_ knows behind which door the prize lies, then opens up one of the doors that doesn’t contain the prize.
There are now two doors left, and Monty gives you the opportunity to change your choice.
Should you keep the same door, change doors, or does it not matter? (a) Write a program that simulates playing this game 10000 times and calculates what percentage of the time you would win if you switch and what percentage of the time you would win by not switching. (b) Try the above but with four doors instead of t...
There is still only one prize, and Monty still opens up one door and then gives you the opportunity to switch. ----- ### Chapter 6 ## Strings Strings are a data type in Python for dealing with text.
Python has a number of powerful features for manipulating strings. ###### 6.1 Basics **Creating a string** A string is created by enclosing text in quotes.
You can use either single quotes, ', or double quotes, ". A triple-quote can be used for multi-line strings.
Here are some examples: s = 'Hello' t = "Hello" m = """This is a long string that is spread across two lines.""" **Input** Recall from Chapter 1 that when getting numerical input we use an eval statement with the input statement, but when getting text, we do not use eval.
The difference is illustrated below: num = eval(input('Enter a number: ')) string = input('Enter a string: ') **Empty string** The empty string '' is the string equivalent of the number 0.
It is a string with nothing in it.
We have seen it before, in the print statement’s optional argument, sep=''. **Length** To get the length of a string (how many characters it has), use the built-in function len. For example, len('Hello') is 5. 43 ----- 44 _CHAPTER 6.
STRINGS_ ###### 6.2 Concatenation and repetition The operators + and * can be used on strings. The + operator combines two strings. This operation is called concatenation.
The * repeats a string a certain number of times.
Here are some examples. Expression Result 'AB'+'cd' 'ABcd' 'A'+'7'+'B' 'A7B' 'Hi'*4 'HiHiHiHi' **Example 1** If we want to print a long row of dashes, we can do the following **print('-'*75)** **Example 2** The + operator can be used to build up a string, piece by piece, analogously to the way we built up counts...
Here is an example that repeatedly asks the user to enter a letter and builds up a string consisting of only the vowels that the user entered. s = '' **for i in range(10):** t = input('Enter a letter: ') **if t=='a' or t=='e' or t=='i' or t=='o' or t=='u':** s = s + t **print(s)** This technique is very useful. #...
For example: **if 'a' in string:** **print('Your string contains the letter a.')** |ample 2 The + operator can be used to build up a string, piece by piece, analogously to the way built up counts and sums in Sections 5.1 and 5.2.
Here is an example that repeatedly asks the r to enter a letter and builds up a string consisting of only the vowels that the user entered.|Col2| |---|---| ||| |s = '' for i in range(10): t = input('Enter a letter: ') if t=='a' or t=='e' or t=='i' or t=='o' or t=='u': s = s + t print(s)|| You can combine in with the ...
INDEXING_ 45 ###### 6.4 Indexing We will often want to pick out individual characters from a string. Python uses square brackets to do this.
The table below gives some examples of indexing the string s='Python'. Statement Result Description s[0] P first character of s s[1] y second character of s s[-1] n last character of s s[-2] o second-to-last character of s - The first character of s is s[0], not s[1].
Remember that in programming, counting usually starts at 0, not 1. - Negative indices count backwards from the end of the string. **A common error** Suppose s='Python' and we try to do s[12].
There are only six characters in the string and Python will raise the following error message: ###### IndexError: string index out of range You will see this message again.
Remember that it happens when you try to read past the end of a string. ###### 6.5 Slices A slice is used to pick out part of a string.
It behaves like a combination of indexing and the range function.
Below we have some examples with the string s='abcdefghij'. index: 0 1 2 3 4 5 6 7 8 9 letters: a b c d e f g h i j Code Result Description s[2:5] cde characters at indices 2, 3, 4 s[ :5] abcde first five characters s[5: ] fghij characters from index 5 to the end s[-2: ] ij last two characters s[ : ] abcdefghij ...
STRINGS_ - The basic structure is _string name[starting location : ending location+1]_ Slices have the same quirk as the range function in that they do not include the ending location.
For instance, in the example above, s[2:5] gives the characters in indices 2, 3, and 4, but not the character in index 5. - We can leave either the starting or ending locations blank.
If we leave the starting location blank, it defaults to the start of the string. So s[:5] gives the first five characters of s.
If we leave the ending location blank, it defaults to the end of the string. So s[5:] will give all the characters from index 5 to the end.
If we use negative indices, we can get the ending characters of the string.
For instance, s[-2:] gives the last two characters. - There is an optional third argument, just like in the range statement, that can specify the step. For example, s[1:7:2] steps through the string by twos, selecting the characters at indices 1, 3, and 5 (but not 7, because of the aforementioned quirk).
The most useful step is -1, which steps backwards through the string, reversing the order of the characters. ###### 6.6 Changing individual characters of a string Suppose we have a string called s and we want to change the character at index 4 of s to 'X'.
It is tempting to try s[4]='X', but that unfortunately will not work. Python strings are immutable, which means we can’t modify any part of them. There is more on why this is in Section 19.1.
If we want to change a character of s, we have to instead build a new string from s and reassign it to s. Here is code that will change the character at index 4 to 'X': s = s[:4] + 'X' + s[5:] The idea of this is we take all the characters up to index 4, then X, and then all of the characters after index 4. ######...
A for loop like the one below can be used to do that.
It loops through a string called s, printing the string, character by character, each on a separate line: **for i in range(len(s)):** **print (s[i])** In the range statement we have len(s) that returns how long s is.
So, if s were 5 characters long, this would be like having range(5) and the loop variable i would run from 0 to 4. This means that s[i] will run through the characters of s.
This way of looping is useful if we need to keep track of our location in the string during the loop. If we don’t need to keep track of our location, then there is a simpler type of loop we can use: ----- _6.8.
STRING METHODS_ 47 **for c in s:** **print(c)** This loop will step through s, character by character, with c holding the current character.
You can almost read this like an English sentence, “For every character c in s, print that character.” ###### 6.8 String methods Strings come with a ton of methods, functions that return information about the string or return a new string that is a modified version of the original.
Here are some of the most useful ones: Method Description lower() returns a string with every letter of the original in lowercase upper() returns a string with every letter of the original in uppercase replace(x,y) returns a string with every occurrence of x replaced by y count(x) counts the number of occurrences ...
If you want to change a string, s, to all lowercase, it is not enough to just use s.lower().
You need to do the following: s = s.lower() **Short examples** Here are some examples of string methods in action: Statement Description **print(s.count(' '))** prints the number of spaces in the string s = s.upper() changes the string to all caps s = s.replace('Hi','Hello') replaces each 'Hi' in s with 'Hello'...