https://artofproblemsolving.com/wiki/api.php?action=feedcontributions&user=Bestaops&feedformat=atom
AoPS Wiki - User contributions [en]
2020-08-05T16:45:56Z
User contributions
MediaWiki 1.31.1
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=105612
Basic Programming With Python
2019-05-04T00:16:43Z
<p>Bestaops: Rearrangement</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
(Note: This is a really long article. To learn the most from this article, you need to read everything in order and skip nothing, unless you are '''absolutely absolutely sure that that content is way too easy for you.''')<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
Note that this article has lots of program examples. It is recommended (but not required) to try these on your own before looking at the solutions.<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
for i in range(1,51):<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
<br />
We must not forget to print the total at the end!<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
print(total)<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
i = 3<br />
total = 0<br />
while i < 1000:<br />
total += i<br />
i += 3<br />
print(total)<br />
<br />
In this code, the while loop loops 333 times, until <math>i</math> becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
n = 1<br />
total = 0<br />
while n <= 50:<br />
total += 2**n<br />
n += 1<br />
print(total)<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2)<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
def up_down_arrow(a,b):<br />
return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
return ((a * b * up_down_arrow(a,b)) ** 2)<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
def add_one(x):<br />
return x + 1<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
def add_one(x):<br />
return x + 1<br />
print(add_one(2))<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
def print_function(x):<br />
print(x)<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
def print_function(x):<br />
print(x)<br />
return<br />
print_function("print_function")<br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
if 10*5 > 9:<br />
if 10*5 < 100:<br />
print("Yes")<br />
else:<br />
print("No")<br />
else:<br />
print("No")<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
print("Yes") <br />
else:<br />
print("No")<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
for i in range(10,100):<br />
if check(i):<br />
print(i)<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
=="Soft Coding" Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad. Hard coding programs refers to coding a program that is hard to modify. For example:<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
def check(a, min, max):<br />
if a*5 > min - 1 and a*5 < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999)<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
print_check(100, 999, 100, 999)<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
def check(a, min, max, factor):<br />
if a*factor > min - 1 and a*factor < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max, check_factor):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check() line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
import random<br />
print(random.randint(1,6))<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
import random<br />
count = 0<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
for i in range(1, 1001):<br />
if roll() == 6:<br />
count += 1<br />
<br />
print(count)<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
print(count(10000))<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
total += count(i)<br />
<br />
print(total)<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
def count2(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count(i)<br />
return total<br />
<br />
def count3(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count2(i)<br />
return total<br />
<br />
print(count3(20))<br />
<br />
(Our program is so long!)<br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while!<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is to soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!<br />
<br />
==Very Basic Datatypes==<br />
<br />
An integer is a basic datatype in Python. Basically, all variables with the datatype of '''int''' is an integer.<br />
<br />
A string is another basic datatype, and it is a string of characters enclosed by quotes.<br />
<br />
===Why Are Datatypes So Important?===<br />
<br />
Let's say we wanted to make a program that would add 2 and 3. Some bogus code would be:<br />
<br />
x="2"<br />
y="3"<br />
print(x+y)<br />
<br />
If you ran this code, you would get 23. Why is that?<br />
<br />
Well, here, x and y are strings. When you perform the addition operator to strings in Python, it concatenates the strings, giving 23.<br />
<br />
The real code is:<br />
<br />
x=2<br />
y=3<br />
print(x+y)<br />
<br />
If you run this, you will get <math>5</math>, which is correct.<br />
<br />
Here's another reason datatypes are important. Now, we will introduce the datatype called the '''floating point number''', or '''float'''. A floating point number is a number with a decimal point.<br />
<br />
Let's go back to the IDLE. Type "0.1*10". The result is 1.0. Notice the decimal point.<br />
<br />
Let's type something different. Type <math>0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1.</math><br />
<br />
'''WHAT!?'''<br />
<br />
You would have expected the answer to be 1, but it isn't 1. What happened?<br />
<br />
'''Float approximation''' happened. Most (almost all) programming languages have a bad float approximation. That means that 1.0 can turn into 0.99999999999999 and 0.5 can turn into 0.49999999999999999993. That only happens with floats, so we should try to use floats as sparingly as possible.<br />
<br />
==Lists==<br />
<br />
A for loop iterates over a '''list'''. A list is a bunch of objects stored in one variable. (Hey! A list is a datatype!) For loops are highly related to lists.<br />
<br />
Let's say we wanted to make a program to print all the items in a list.<br />
<br />
We will first create the list, using the code:<br />
<br />
myList = [1,4,6,8]<br />
<br />
This is a list with four items: 1, 4, 6, and 8.<br />
<br />
We must now print all elements of it with a for loop:<br />
<br />
myList = [1,4,6,8]<br />
for i in myList:<br />
print(i)<br />
<br />
When we run this program, we get the numbers 1, 4, 6, and 8, as expected.<br />
<br />
===Accessing Values===<br />
<br />
Let's say we wanted to print out the second item in a list. We will use '''indexes'''.<br />
<br />
The index of the first item in a list is always 0. The index of the second is 1. The index of the <math>n</math>th is <math>n-1.</math><br />
<br />
To print out the second item, we will use an index of 1, like this:<br />
<br />
myList = [1,4,6,8]<br />
print(myList[1])<br />
<br />
Notice that the index is inside of the square brackets.<br />
<br />
===Adding Values===<br />
<br />
We can use the list.append() function to add an object to the end of a list.<br />
<br />
myList.append(10)<br />
<br />
will add 10 to the list, which makes myList = [1,4,6,8,10].<br />
<br />
===Removing Items From Lists===<br />
<br />
We can use the list.remove() function to remove a specific item in a list.<br />
<br />
For example, consider this code.<br />
<br />
myList = [1,2,3]<br />
myList.remove(3)<br />
<br />
This code will make myList turn into [1,2]. The element, 3, gets removed.<br />
<br />
===len(list)===<br />
<br />
The len(list) function returns the length of a list.<br />
<br />
This code will print 3.<br />
<br />
myList = [1,2,3]<br />
print(len(myList))<br />
<br />
The length of myList is 3, so Python prints 3.<br />
<br />
===All Kinds Of Lists===<br />
<br />
Lists don't have to be only integers!<br />
<br />
myList = [1,"Hi","Hello world", 3.5, 3.14159265358979323]<br />
<br />
If fact, there can be lists inside of lists!<br />
<br />
myList = [[1,2,3], [3,4,5], [5,6,"Hello world"], "BOB", 3.1415926]<br />
<br />
Even this!<br />
<br />
myList = [[1, [1, [1,2,3],3],3], [[[3,["Hello world", 4],5],4,5],4,5], [5,6,7,[1,[1,2,3],3],"Hello world"], "BOB", 3.1415926, True]<br />
<br />
If you look at that list carefully, you will find lists inside of lists inside of lists inside of lists! And, a boolean at the end!<br />
<br />
Like variables, you can have as many lists in a program as you want (a list is a variable)!<br />
<br />
myList = [1,2,3,4]<br />
yourList = [5,6,7,8]<br />
hisList = [9,10,11,12]<br />
herList = [13,14,15,16]<br />
theirList = [17,18,19,20]<br />
ourList = [21,22,23,24]<br />
listsOfLists = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20],[21,22,23,24]]<br />
<br />
==Dictionaries==<br />
<br />
A dictionary (a type of datatype) is a bunch of keys and values. There is a major difference between dictionaries and lists. Lists are ordered; dictionaries are not.<br />
<br />
Here is the '''syntax''' of creating a dictionary:<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
<br />
This dictionary has two key/value pairs. Notice it is surrounded in curly braces. The keys are 1 and 2; the values are "one" and "two."<br />
<br />
How is this useful? Let's make a simple program to test it out.<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
print(myDictionary[1])<br />
print(myDictionary[2])<br />
<br />
===Accessing Values===<br />
<br />
To access a value in a dictionary, you put in the key.<br />
<br />
myDictionary[1]<br />
<br />
returns one, because 1 is the key to "one."<br />
<br />
===Adding New Values===<br />
<br />
To overwrite a value, we do this.<br />
<br />
myDictionary[1] = "won"<br />
<br />
The value to the key 1 is now "won."<br />
<br />
To add a value, we do the same thing!<br />
<br />
myDictionary[3] = "three"<br />
<br />
This adds a key 3 with a value of "three."<br />
<br />
==Misc Concepts==<br />
<br />
This section will talk about some concepts that we haven't learned yet.<br />
<br />
====Concatenating Strings====<br />
<br />
Concatenating strings is putting them together. For example, "one" concatenated with "two" gives "onetwo."<br />
<br />
The following string,<br />
<br />
"Hello, " + person2 + "! How are you?"<br />
<br />
depends on what person2 was. If person2 was Bob, the string would be:<br />
<br />
"Hello, Bob! How are you?"<br />
<br />
It fits together perfectly!<br />
<br />
You cannot concatenate strings with integers. For example, doing this:<br />
<br />
"2" + 3<br />
<br />
will not work. Instead, to get an answer of "23", you must do this:<br />
<br />
"2" + str(3)<br />
<br />
That turns 3 into a string so it is "3", and the result will be "23".<br />
<br />
====Line Breaks====<br />
<br />
We can use multiple line breaks to make our code more organized. There are some places that you cannot line break. For example, this code will produce an error:<br />
<br />
myList =<br />
[1,2,3]<br />
<br />
This code does not work.<br />
<br />
This code '''does work''':<br />
<br />
myList = [<br />
1,2,3]<br />
<br />
It is accepted when you break a line right after the [. It is also accepted right after a comma. (And right before the ending ].)<br />
<br />
myList = [<br />
1,<br />
2,<br />
3<br />
]<br />
<br />
==Challenge Program==<br />
<br />
In this section, we will attempt the hardest program so far in this article.<br />
<br />
'''Make a conversation generator that will generate random conversations between different people.'''<br />
<br />
First, we will generate the people. We can use a list and generate two random numbers.<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will",<br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
(I made it more organized by separating the long lines of code into multiple lines. It only works when you have a line break right after each item in the list.)<br />
<br />
Here, we use the remove() function to remove person1 from the list to make sure we don't use the same name twice. <br />
<br />
We also used the len() function to find the length of the list (soft-coding!)<br />
<br />
Now, we need to create a list of possible values for the first thing that person1 says (person1 will always be the first one to talk). <br />
<br />
Then, we will print it out.<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will",<br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = [<br />
"Hi!",<br />
"Hello!",<br />
"Good morning!",<br />
"Hello, " + person2 + "!",<br />
"Hi.",<br />
"Hi, " + person2 + "!"<br />
]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
<br />
If we test out this program, we can confirm that this part indeed does work. This program is already getting long! Now, we will use the same method and create the second message.<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will",<br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = [<br />
"Hi!",<br />
"Hello!",<br />
"Good morning!",<br />
"Hello, " + person2 + "!",<br />
"Hi.",<br />
"Hi, " + person2 + "!"<br />
]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
<br />
second = [<br />
"Hi! How are you today?",<br />
"Hello! How are you?",<br />
"Good morning! How are you today?",<br />
"Hello, " + person1 + "! How are you?",<br />
"Hi. How are you?",<br />
"Hi, " + person1 + "! How are you today?"<br />
]<br />
print(person2 + ": " + second[random.randint(0, (len(second) - 1))])<br />
<br />
We will repeat this for the rest of the conversation:<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will", <br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = [<br />
"Hi!",<br />
"Hello!",<br />
"Good morning!",<br />
"Hello, " + person2 + "!",<br />
"Hi.",<br />
"Hi, " + person2 + "!"<br />
]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
<br />
second = [<br />
"Hi! How are you today?",<br />
"Hello! How are you?",<br />
"Good morning! How are you today?",<br />
"Hello, " + person1 + "! How are you?",<br />
"Hi. How are you?",<br />
"Hi, " + person1 + "! How are you today?"<br />
]<br />
print(person2 + ": " + second[random.randint(0, (len(second) - 1))])<br />
<br />
third = [<br />
"I'm feeling awesome! And you?",<br />
"I'm feeling alright! How are you?",<br />
"I'm good, thank you. How are you feeling?",<br />
"I'm fine!" ,<br />
"How are you today?"<br />
]<br />
print(person1 + ": " + third[random.randint(0, (len(third) - 1))])<br />
<br />
fourth = [<br />
"I'm feeling great!",<br />
"I'm awesome!",<br />
"Thanks for asking! I am feeling good today!",<br />
"I'm feeling awesome today! Yippee!"<br />
] <br />
print(person2 + ": " + fourth[random.randint(0, (len(fourth) - 1))])<br />
<br />
fifth = [<br />
"It's so nice out today!",<br />
"Today is such a cloudy day.",<br />
"I hate it when it is so cloudy outside!",<br />
"It's partly cloudy today!"<br />
]<br />
print(person1 + ": " + fifth[random.randint(0, (len(fifth) - 1))])<br />
<br />
sixth = [<br />
"I know, right?",<br />
"I know.",<br />
"Yeah!",<br />
"True."<br />
]<br />
print(person2 + ": " + sixth[random.randint(0, (len(sixth) - 1))])<br />
<br />
seventh = [<br />
"Sorry, I need to leave. Bye!",<br />
"I gotta go. Bye!",<br />
"Sorry, I don't have time to stay and chat. I've got to go somewhere. Bye!"<br />
]<br />
print(person1 + ": " + seventh[random.randint(0, (len(seventh) - 1))])<br />
<br />
eighth = [<br />
"Bye!",<br />
"Good-bye!",<br />
"Bye, " + person1 + "."<br />
]<br />
print(person2 + ": " + eighth[random.randint(0, (len(eighth) - 1))])<br />
<br />
Whew! So long!<br />
<br />
Once we run our program. It works! This program really wasn't that hard.<br />
<br />
Congrats! You've made it so far!</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=105611
Basic Programming With Python
2019-05-04T00:07:16Z
<p>Bestaops: /* Soft Coding Programs */</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
(Note: This is a really long article. To learn the most from this article, you need to read everything in order and skip nothing, unless you are '''absolutely absolutely sure that that content is way too easy for you.''')<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
Note that this article has lots of program examples. It is recommended (but not required) to try these on your own before looking at the solutions.<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
for i in range(1,51):<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
<br />
We must not forget to print the total at the end!<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
print(total)<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
i = 3<br />
total = 0<br />
while i < 1000:<br />
total += i<br />
i += 3<br />
print(total)<br />
<br />
In this code, the while loop loops 333 times, until <math>i</math> becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
n = 1<br />
total = 0<br />
while n <= 50:<br />
total += 2**n<br />
n += 1<br />
print(total)<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2)<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
def up_down_arrow(a,b):<br />
return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
return ((a * b * up_down_arrow(a,b)) ** 2)<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
def add_one(x):<br />
return x + 1<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
def add_one(x):<br />
return x + 1<br />
print(add_one(2))<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
def print_function(x):<br />
print(x)<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
def print_function(x):<br />
print(x)<br />
return<br />
print_function("print_function")<br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
if 10*5 > 9:<br />
if 10*5 < 100:<br />
print("Yes")<br />
else:<br />
print("No")<br />
else:<br />
print("No")<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
print("Yes") <br />
else:<br />
print("No")<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
for i in range(10,100):<br />
if check(i):<br />
print(i)<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
=="Soft Coding" Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad. Hard coding programs refers to coding a program that is hard to modify. For example:<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
def check(a, min, max):<br />
if a*5 > min - 1 and a*5 < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999)<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
print_check(100, 999, 100, 999)<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
def check(a, min, max, factor):<br />
if a*factor > min - 1 and a*factor < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max, check_factor):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check() line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
import random<br />
print(random.randint(1,6))<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
import random<br />
count = 0<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
for i in range(1, 1001):<br />
if roll() == 6:<br />
count += 1<br />
<br />
print(count)<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
print(count(10000))<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
total += count(i)<br />
<br />
print(total)<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
def count2(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count(i)<br />
return total<br />
<br />
def count3(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count2(i)<br />
return total<br />
<br />
print(count3(20))<br />
<br />
(Our program is so long!)<br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while!<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is to soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!<br />
<br />
==Very Basic Datatypes==<br />
<br />
An integer is a basic datatype in Python. Basically, all variables with the datatype of '''int''' is an integer.<br />
<br />
A string is another basic datatype, and it is a string of characters enclosed by quotes.<br />
<br />
===Why Are Datatypes So Important?===<br />
<br />
Let's say we wanted to make a program that would add 2 and 3. Some bogus code would be:<br />
<br />
x="2"<br />
y="3"<br />
print(x+y)<br />
<br />
If you ran this code, you would get 23. Why is that?<br />
<br />
Well, here, x and y are strings. When you perform the addition operator to strings in Python, it concatenates the strings, giving 23.<br />
<br />
The real code is:<br />
<br />
x=2<br />
y=3<br />
print(x+y)<br />
<br />
If you run this, you will get <math>5</math>, which is correct.<br />
<br />
Here's another reason datatypes are important. Now, we will introduce the datatype called the '''floating point number''', or '''float'''. A floating point number is a number with a decimal point.<br />
<br />
Let's go back to the IDLE. Type "0.1*10". The result is 1.0. Notice the decimal point.<br />
<br />
Let's type something different. Type <math>0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1.</math><br />
<br />
'''WHAT!?'''<br />
<br />
You would have expected the answer to be 1, but it isn't 1. What happened?<br />
<br />
'''Float approximation''' happened. Most (almost all) programming languages have a bad float approximation. That means that 1.0 can turn into 0.99999999999999 and 0.5 can turn into 0.49999999999999999993. That only happens with floats, so we should try to use floats as sparingly as possible.<br />
<br />
==Lists==<br />
<br />
A for loop iterates over a '''list'''. A list is a bunch of objects stored in one variable. (Hey! A list is a datatype!) For loops are highly related to lists.<br />
<br />
Let's say we wanted to make a program to print all the items in a list.<br />
<br />
We will first create the list, using the code:<br />
<br />
myList = [1,4,6,8]<br />
<br />
This is a list with four items: 1, 4, 6, and 8.<br />
<br />
We must now print all elements of it with a for loop:<br />
<br />
myList = [1,4,6,8]<br />
for i in myList:<br />
print(i)<br />
<br />
When we run this program, we get the numbers 1, 4, 6, and 8, as expected.<br />
<br />
===Accessing Values===<br />
<br />
Let's say we wanted to print out the second item in a list. We will use '''indexes'''.<br />
<br />
The index of the first item in a list is always 0. The index of the second is 1. The index of the <math>n</math>th is <math>n-1.</math><br />
<br />
To print out the second item, we will use an index of 1, like this:<br />
<br />
myList = [1,4,6,8]<br />
print(myList[1])<br />
<br />
Notice that the index is inside of the square brackets.<br />
<br />
===Adding Values===<br />
<br />
We can use the list.append() function to add an object to the end of a list.<br />
<br />
myList.append(10)<br />
<br />
will add 10 to the list, which makes myList = [1,4,6,8,10].<br />
<br />
===All Kinds Of Lists===<br />
<br />
Lists don't have to be only integers!<br />
<br />
myList = [1,"Hi","Hello world", 3.5, 3.14159265358979323]<br />
<br />
If fact, there can be lists inside of lists!<br />
<br />
myList = [[1,2,3], [3,4,5], [5,6,"Hello world"], "BOB", 3.1415926]<br />
<br />
Even this!<br />
<br />
myList = [[1, [1, [1,2,3],3],3], [[[3,["Hello world", 4],5],4,5],4,5], [5,6,7,[1,[1,2,3],3],"Hello world"], "BOB", 3.1415926, True]<br />
<br />
If you look at that list carefully, you will find lists inside of lists inside of lists inside of lists! And, a boolean at the end!<br />
<br />
Like variables, you can have as many lists in a program as you want (a list is a variable)!<br />
<br />
myList = [1,2,3,4]<br />
yourList = [5,6,7,8]<br />
hisList = [9,10,11,12]<br />
herList = [13,14,15,16]<br />
theirList = [17,18,19,20]<br />
ourList = [21,22,23,24]<br />
listsOfLists = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20],[21,22,23,24]]<br />
<br />
==Dictionaries==<br />
<br />
A dictionary (a type of datatype) is a bunch of keys and values. There is a major difference between dictionaries and lists. Lists are ordered; dictionaries are not.<br />
<br />
Here is the '''syntax''' of creating a dictionary:<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
<br />
This dictionary has two key/value pairs. Notice it is surrounded in curly braces. The keys are 1 and 2; the values are "one" and "two."<br />
<br />
How is this useful? Let's make a simple program to test it out.<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
print(myDictionary[1])<br />
print(myDictionary[2])<br />
<br />
===Accessing Values===<br />
<br />
To access a value in a dictionary, you put in the key.<br />
<br />
myDictionary[1]<br />
<br />
returns one, because 1 is the key to "one."<br />
<br />
===Adding New Values===<br />
<br />
To overwrite a value, we do this.<br />
<br />
myDictionary[1] = "won"<br />
<br />
The value to the key 1 is now "won."<br />
<br />
To add a value, we do the same thing!<br />
<br />
myDictionary[3] = "three"<br />
<br />
This adds a key 3 with a value of "three."<br />
<br />
==Challenge Program==<br />
<br />
In this section, we will attempt the hardest program so far in this article.<br />
<br />
'''Make a conversation generator that will generate random conversations between different people.'''<br />
<br />
First, we will generate the people. We can use a list and generate two random numbers.<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will",<br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
(I made it more organized by separating the long lines of code into multiple lines. It only works when you have a line break right after each item in the list.)<br />
<br />
Here, we use the remove() function to remove person1 from the list to make sure we don't use the same name twice. <br />
<br />
We also used the len() function to find the length of the list (soft-coding!)<br />
<br />
Now, we need to create a list of possible values for the first thing that person1 says (person1 will always be the first one to talk). <br />
<br />
Then, we will print it out.<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will",<br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = [<br />
"Hi!",<br />
"Hello!",<br />
"Good morning!",<br />
"Hello, " + person2 + "!",<br />
"Hi.",<br />
"Hi, " + person2 + "!"<br />
]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
<br />
If we test out this program, we can confirm that this part indeed does work. This program is already getting long! Now, we will use the same method and create the second message.<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will",<br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = [<br />
"Hi!",<br />
"Hello!",<br />
"Good morning!",<br />
"Hello, " + person2 + "!",<br />
"Hi.",<br />
"Hi, " + person2 + "!"<br />
]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
<br />
second = [<br />
"Hi! How are you today?",<br />
"Hello! How are you?",<br />
"Good morning! How are you today?",<br />
"Hello, " + person1 + "! How are you?",<br />
"Hi. How are you?",<br />
"Hi, " + person1 + "! How are you today?"<br />
]<br />
print(person2 + ": " + second[random.randint(0, (len(second) - 1))])<br />
<br />
We will repeat this for the rest of the conversation:<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will", <br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = [<br />
"Hi!",<br />
"Hello!",<br />
"Good morning!",<br />
"Hello, " + person2 + "!",<br />
"Hi.",<br />
"Hi, " + person2 + "!"<br />
]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
<br />
second = [<br />
"Hi! How are you today?",<br />
"Hello! How are you?",<br />
"Good morning! How are you today?",<br />
"Hello, " + person1 + "! How are you?",<br />
"Hi. How are you?",<br />
"Hi, " + person1 + "! How are you today?"<br />
]<br />
print(person2 + ": " + second[random.randint(0, (len(second) - 1))])<br />
<br />
third = [<br />
"I'm feeling awesome! And you?",<br />
"I'm feeling alright! How are you?",<br />
"I'm good, thank you. How are you feeling?",<br />
"I'm fine!" ,<br />
"How are you today?"<br />
]<br />
print(person1 + ": " + third[random.randint(0, (len(third) - 1))])<br />
<br />
fourth = [<br />
"I'm feeling great!",<br />
"I'm awesome!",<br />
"Thanks for asking! I am feeling good today!",<br />
"I'm feeling awesome today! Yippee!"<br />
] <br />
print(person2 + ": " + fourth[random.randint(0, (len(fourth) - 1))])<br />
<br />
fifth = [<br />
"It's so nice out today!",<br />
"Today is such a cloudy day.",<br />
"I hate it when it is so cloudy outside!",<br />
"It's partly cloudy today!"<br />
]<br />
print(person1 + ": " + fifth[random.randint(0, (len(fifth) - 1))])<br />
<br />
sixth = [<br />
"I know, right?",<br />
"I know.",<br />
"Yeah!",<br />
"True."<br />
]<br />
print(person2 + ": " + sixth[random.randint(0, (len(sixth) - 1))])<br />
<br />
seventh = [<br />
"Sorry, I need to leave. Bye!",<br />
"I gotta go. Bye!",<br />
"Sorry, I don't have time to stay and chat. I've got to go somewhere. Bye!"<br />
]<br />
print(person1 + ": " + seventh[random.randint(0, (len(seventh) - 1))])<br />
<br />
eighth = [<br />
"Bye!",<br />
"Good-bye!",<br />
"Bye, " + person1 + "."<br />
]<br />
print(person2 + ": " + eighth[random.randint(0, (len(eighth) - 1))])<br />
<br />
Whew! So long!<br />
<br />
Once we run our program. It works! This program really wasn't that hard.<br />
<br />
Congrats! You've made it so far!<br />
<br />
We are not done yet.<br />
<br />
There are quite a few things we need to cover.<br />
<br />
We have used a bit of code in our program that we have not learned yet.<br />
<br />
===Concepts===<br />
<br />
This section will talk about some concepts in our code that we haven't learned yet.<br />
<br />
====Concatenating Strings====<br />
<br />
Concatenating strings is putting them together. For example, "one" concatenated with "two" gives "onetwo."<br />
<br />
In our code, we concatenated strings.<br />
<br />
"Hello, " + person2 + "! How are you?"<br />
<br />
depends on what person2 was. If person2 was Bob, the string would be:<br />
<br />
"Hello, Bob! How are you?"<br />
<br />
It fits together perfectly!<br />
<br />
You cannot concatenate strings with integers. For example, doing this:<br />
<br />
"2" + 3<br />
<br />
will not work. Instead, to get an answer of "23", you must do this:<br />
<br />
"2" + str(3)<br />
<br />
That turns 3 into a string so it is "3", and the result will be "23".<br />
<br />
====Removing Items From Lists====<br />
<br />
We can use the list.remove() function to remove a specific item in a list.<br />
<br />
For example, consider this code.<br />
<br />
myList = [1,2,3]<br />
myList.remove(3)<br />
<br />
This code will make myList turn into [1,2]. The element, 3, gets removed.<br />
<br />
====Line Breaks====<br />
<br />
In our code, we used multiple line breaks to make our code more organized. There are some places that you cannot line break. For example, this code will produce an error:<br />
<br />
myList =<br />
[1,2,3]<br />
<br />
This code does not work.<br />
<br />
This code '''does work''':<br />
<br />
myList = [<br />
1,2,3]<br />
<br />
It is accepted when you break a line right after the [. It is also accepted right after a comma. (And right before the ending ].)<br />
<br />
myList = [<br />
1,<br />
2,<br />
3<br />
]<br />
<br />
That is what we did in our code.<br />
<br />
====len(list)====<br />
<br />
The len(list) function returns the length of a list.<br />
<br />
This code will print 3.<br />
<br />
myList = [1,2,3]<br />
print(len(myList))<br />
<br />
The length of myList is 3, so Python prints 3.<br />
<br />
Now look back at our final conversation program code. Make sure you '''understand every bit of it'''. It '''must''' be crystal clear to you or you will not benefit from this. Make sure you are not just '''copy and pasting''' the code! That will not help you at all!</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=1999_AMC_8_Problems/Problem_1&diff=96301
1999 AMC 8 Problems/Problem 1
2018-07-16T21:25:40Z
<p>Bestaops: /* Solution */</p>
<hr />
<div>==Problem==<br />
<br />
<math>(6?3) + 4 - (2 - 1) = 5.</math> To make this statement true, the question mark between the 6 and the 3 should be replaced by<br />
<br />
<math>\text{(A)} \div \qquad \text{(B)}\ \times \qquad \text{(C)} + \qquad \text{(D)}\ - \qquad \text{(E)}\ \text{None of these}</math><br />
<br />
==Solution==<br />
<br />
Simplifying the given expression, we get: <math>(6?3)=2.</math><br />
<br />
At this point, it becomes clear that it should be <math>(\textrm{A}) \div</math>.<br />
<br />
==See Also==<br />
{{AMC8 box|year=1999|before=First<br />Question|num-a=2}}<br />
{{MAA Notice}}</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=1999_AMC_8_Problems/Problem_1&diff=96300
1999 AMC 8 Problems/Problem 1
2018-07-16T21:25:24Z
<p>Bestaops: /* Solution */</p>
<hr />
<div>==Problem==<br />
<br />
<math>(6?3) + 4 - (2 - 1) = 5.</math> To make this statement true, the question mark between the 6 and the 3 should be replaced by<br />
<br />
<math>\text{(A)} \div \qquad \text{(B)}\ \times \qquad \text{(C)} + \qquad \text{(D)}\ - \qquad \text{(E)}\ \text{None of these}</math><br />
<br />
==Solution==<br />
<br />
Simplifying the given expression, we get: <math>(6?3)=2.</math><br />
<br />
At this point, it becomes clear that it should be <math>(A) \div</math>.<br />
<br />
==See Also==<br />
{{AMC8 box|year=1999|before=First<br />Question|num-a=2}}<br />
{{MAA Notice}}</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=1999_AMC_8_Problems/Problem_1&diff=96299
1999 AMC 8 Problems/Problem 1
2018-07-16T21:24:52Z
<p>Bestaops: /* Solution */</p>
<hr />
<div>==Problem==<br />
<br />
<math>(6?3) + 4 - (2 - 1) = 5.</math> To make this statement true, the question mark between the 6 and the 3 should be replaced by<br />
<br />
<math>\text{(A)} \div \qquad \text{(B)}\ \times \qquad \text{(C)} + \qquad \text{(D)}\ - \qquad \text{(E)}\ \text{None of these}</math><br />
<br />
==Solution==<br />
<br />
Simplifying the given expression, we get: <math>(6?3)=2.</math><br />
<br />
At this point, it becomes clear that it should be <math> \div (A) </math>.<br />
<br />
==See Also==<br />
{{AMC8 box|year=1999|before=First<br />Question|num-a=2}}<br />
{{MAA Notice}}</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=1999_AMC_8_Problems/Problem_1&diff=96298
1999 AMC 8 Problems/Problem 1
2018-07-16T21:24:08Z
<p>Bestaops: /* Solution */</p>
<hr />
<div>==Problem==<br />
<br />
<math>(6?3) + 4 - (2 - 1) = 5.</math> To make this statement true, the question mark between the 6 and the 3 should be replaced by<br />
<br />
<math>\text{(A)} \div \qquad \text{(B)}\ \times \qquad \text{(C)} + \qquad \text{(D)}\ - \qquad \text{(E)}\ \text{None of these}</math><br />
<br />
==Solution==<br />
<br />
Simplifying the given expression, we get: <math>(6?3)=2.</math><br />
<br />
At this point, it becomes clear that it should be <math> \div,</math> so the answer is <math> \boxed{A} </math>.<br />
<br />
==See Also==<br />
{{AMC8 box|year=1999|before=First<br />Question|num-a=2}}<br />
{{MAA Notice}}</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=1999_AMC_8_Problems/Problem_1&diff=96297
1999 AMC 8 Problems/Problem 1
2018-07-16T21:23:58Z
<p>Bestaops: /* Solution */</p>
<hr />
<div>==Problem==<br />
<br />
<math>(6?3) + 4 - (2 - 1) = 5.</math> To make this statement true, the question mark between the 6 and the 3 should be replaced by<br />
<br />
<math>\text{(A)} \div \qquad \text{(B)}\ \times \qquad \text{(C)} + \qquad \text{(D)}\ - \qquad \text{(E)}\ \text{None of these}</math><br />
<br />
==Solution==<br />
<br />
Simplifying the given expression, we get: <math>(6?3)=2</math><br />
<br />
At this point, it becomes clear that it should be <math> \div,</math> so the answer is <math> \boxed{A} </math>.<br />
<br />
==See Also==<br />
{{AMC8 box|year=1999|before=First<br />Question|num-a=2}}<br />
{{MAA Notice}}</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Art_of_Problem_Solving&diff=95236
Art of Problem Solving
2018-06-17T22:16:54Z
<p>Bestaops: /* AoPS For The Win */</p>
<hr />
<div>'''Art of Problem Solving''' ('''AoPS''') is an educational resources company founded by [[Richard Rusczyk]] in 2003. <br />
<br />
<br />
=== Tradition of Excellence ===<br />
The accomplishments of every student are unique, and there is no way to measure that success. However, we try to record and celebrate [[AoPS Community Awards | achievements of AoPS students, faculty, and community members]].<br />
<br />
== Resources on AoPS ==<br />
=== AoPSWiki ===<br />
You're in the [[AoPSWiki]] now!<br />
<br />
* [[AoPSWiki:Table of Contents]] -- a basic guide to AoPSWiki content<br />
* [[Academic competitions]] including a huge [[List of mathematics competitions]]<br />
* [[Math books]]<br />
* [[Academic scholarships]] including a large list of [[Mathematics scholarships]]<br />
<br />
=== AoPS Books ===<br />
<br />
==== Subject textbooks ====<br />
AoPS subject texts provide instruction to excellent students of mathematics. This modern curriculum is both comprehensive and challenging enough for brilliant young mathematical minds.<br />
* [http://www.artofproblemsolving.com/Books/AoPS_B_Item.php?item_id=200 Introduction to Algebra]<br />
* [http://www.artofproblemsolving.com/Books/AoPS_B_Item.php?item_id=202 Introduction to Counting & Probability]<br />
* [http://www.artofproblemsolving.com/Books/AoPS_B_Item.php?item_id=204 Introduction to Geometry]<br />
* [http://www.artofproblemsolving.com/Books/AoPS_B_Item.php?item_id=206 Introduction to Number Theory]<br />
* [http://www.artofproblemsolving.com/Store/viewitem.php?item=interm:algebra Intermediate Algebra]<br />
* [http://www.artofproblemsolving.com/Books/AoPS_B_Item.php?item_id=302 Intermediate Counting & Probability]<br />
* [http://www.artofproblemsolving.com/Store/viewitem.php?item=precalc Precalculus]<br />
* [http://www.artofproblemsolving.com/Store/viewitem.php?item=calculus Calculus]<br />
<br />
==== Problem solving books ====<br />
The original Art of Problem Solving books cover a variety of topics of interest to top students of mathematics.<br />
* [http://www.artofproblemsolving.com/Books/AoPS_B_Item.php?page_id=1 Art of Problem Solving Volume 1]<br />
* [http://www.artofproblemsolving.com/Books/AoPS_B_Item.php?page_id=2 Art of Problem Solving Volume 2]<br />
<br />
==== Other math books ====<br />
AoPS sells numerous other math books at the [http://www.artofproblemsolving.com/Books/AoPS_B_About.php AoPS Bookstore]. Many of these books focus on competitions such as the [[AMC]], the [[Mandelbrot Competition]], [[Mathcounts]], or [[MOEMS]].<br />
<br />
=== AoPS Online School ===<br />
The [[AoPS Online School]] hosts math classes primarily for bright middle and high school students. Students of the online math school include winners of nearly every major mathematics competition in the U.S.<br />
<br />
<br />
=== AoPS Forums ===<br />
The [http://www.artofproblemsolving.com/Forum/index.php AoPS Forums] are a place where students and problem solvers of all ages can discuss mathematics and problem solving. Visit [[AoPSWiki:AoPS forums]] for more details.<br />
<br />
=== AoPS For The Win ===<br />
[http://www.artofproblemsolving.com/Edutainment/g1/index.php For The Win] is an online interactive game for students to participate in activities similar to Countdown Round in [[MathCounts]].<br />
<br />
=== TeX/LaTeX Resources ===<br />
The [http://www.artofproblemsolving.com/community AoPS Forums] are [[LaTeX]]-enabled, allowing users to post nice mathematics.<br />
<br />
=== Math contest problem database ===<br />
<br />
AoPS members help organize a large and well-organized <url>resources.php list of problems and solutions</url> from [[mathematics competitions]] all over the world.<br />
<br />
=== Articles ===<br />
<br />
AoPS resources include [http://artofproblemsolving.com/articles numerous very good articles] for students, parents, and teachers.<br />
<br />
== Philanthropy ==<br />
Many of the features of the Art of Problem Solving website are made available for free so that every student interested in mathematics can use them.<br />
<br />
Additionally, AoPS instructors provide hundreds of hours of teaching and support time for the [[San Diego Math Circle]].<br />
<br />
The [[Art of Problem Solving Foundation]] is a nonprofit corporation founded by AoPS CEO [[Richard Rusczyk]] with largely the same fundamental mission as AoPS itself, but with greater focus on providing educational resources where they are lacking. AoPS donates a portion of its book and class sales to the foundation. A link can be found [http://www.artofproblemsolving.org here]. Make sure it is .org if you want to see the foundation website, otherwise, you'll see the homepage of the current website you're on. <br />
<br />
<br />
<br />
[[Category:Art of Problem Solving]]</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=2007_AMC_8_Problems/Problem_20&diff=95235
2007 AMC 8 Problems/Problem 20
2018-06-17T22:10:10Z
<p>Bestaops: /* Solution */</p>
<hr />
<div>==Problem==<br />
<!-- don't remove the following tag, for PoTW on the Wiki front page--><onlyinclude>Before the district play, the Unicorns had won <math>45</math>% of their basketball games. During district play, they won six more games and lost two, to finish the season having won half their games. How many games did the Unicorns play in all?<!-- don't remove the following tag, for PoTW on the Wiki front page--></onlyinclude><br />
<br />
<math> \textbf{(A)}\ 48\qquad\textbf{(B)}\ 50\qquad\textbf{(C)}\ 52\qquad\textbf{(D)}\ 54\qquad\textbf{(E)}\ 60 </math><br />
<br />
==Solution 1==<br />
<br />
At the beginning of the problem, the Unicorns had played <math>y</math> games and they had won <math>x</math> of these games. From the information given in the problem, we can say that <math>\frac{x}{y}=0.45.</math> Next, the Unicorns win 6 more games and lose 2 more, for a total of <math>6+2=8</math> games played during district play. We are told that they end the season having won half of their games, or <math>0.5 </math> of their games. We can write another equation: <math>\frac{x+6}{y+8}=0.5.</math> This gives us a system of equations:<br />
<math>\frac{x}{y}=0.45</math> and <math>\frac{x+6}{y+8}=0.5.</math><br />
We first multiply both sides of the first equation by <math>y</math> to get <math>x=0.45y.</math> Then, we multiply both sides of the second equation by <math>(y+8)</math> to get <math>x+6=0.5(y+8).</math> Applying the Distributive Property gives yields <math>x+6=0.5y+4.</math> Now we substitute <math>0.45y</math> for <math>x</math> to get <math>0.45y+6=0.5y+4.</math> Solving gives us <math>y=40.</math> Since the problem asks for the total number of games, we add on the last 8 games to get the solution <math>\boxed{\textbf{(A)}\ 48}</math>.<br />
<br />
==Solution 2==<br />
Simplifying 45% to <math>\frac{9}{20}</math>, we see that the numbers of games are a multiple of 20. After that the Unicorns played 8 more games to the total number of games is in the form of 20x+8 where x is any positive integer. The only answer choice is <math>\boxed{48}</math>, which is 20(2)+8.<br />
<br />
-harsha12345<br />
<br />
==Solution 3==<br />
First we 45% to <math>\frac{9}{20}</math>. After he won 6 more games and lost 2 more games the number of games he won is <math>9x+6</math>, and the total number of games is <math>20x+8</math>. Turning it into a fraction we get <math>\frac{9x+6}{20x+8}=\frac{1}{2}</math>, so solving for <math>x</math> we get <math>x=2.</math> Plugging in 2 for <math>x</math> we get <math>20(2)+8=\boxed{48}</math>.<br />
<br />
-harsha12345<br />
<br />
==See Also==<br />
{{AMC8 box|year=2007|num-b=19|num-a=21}}<br />
{{MAA Notice}}</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=AoPS_Wiki:FAQ&diff=94918
AoPS Wiki:FAQ
2018-06-04T22:11:59Z
<p>Bestaops: /* Can I change my username? */</p>
<hr />
<div>{{shortcut|[[A:FAQ]]}}<br />
<br />
This is a community created list of Frequently Asked Questions about Art of Problem Solving. If you have a request to edit or add a question on this page, please make it [http://www.artofproblemsolving.com/Forum/viewtopic.php?f=416&t=414129 here].<br />
<br />
== General==<br />
<br />
<br />
==== Can I change my username? ====<br />
<br />
No, unless it has private info in it.<br />
<br />
==== Why can't I change my avatar? ====<br />
<br />
: You must be a user for two weeks before being able to change your avatar.<br />
: It is almost impossible to get a small enough photo to fit the 24 KB restrictions (unless you can somehow edit the pic).<br />
: Just be happy with what you have.<br />
<br />
==== Something looks weird (e.g., blurry, missing line, etc.) ====<br />
<br />
: This is likely due to your browser zoom level. Please make sure your zoom level is at 100% for correct rendering of the web page.<br />
<br />
==== Can I make more than one account?==== <br />
<br />
:Short answer: No.<br />
<br />
:Long answer: Multiple accounts (multis) are banned on AoPS. Having more than one account leads to issues of not remembering on what account you did what. Using multiple accounts to "game" the system, (e.g. increase rating for posts or in online games) will lead to bans on all accounts associated with you. If you have already made additional accounts, please choose one account and stop using the others.<br />
<br />
====What software does Art of Problem Solving use to run the website?====<br />
<br />
:* Search: Solr<br />
:* Wiki: MediaWiki<br />
:* Asymptote and <math>\text{\LaTeX}</math> are generated through their respective binary packages<br />
:* Videos: YouTube<br />
<br />
:All other parts of the website are custom built.<br />
<br />
====Can you make an AoPS App?====<br />
<br />
:No. The logistics and costs involved are too great and there would be very little, if any benefit to the app over the website page itself, as some features of the desktop site would be missing.<br />
<br />
== Forums ==<br />
<br />
====How do I create a forum?====<br />
<br />
:To create an AoPS forum, a user must be on the AoPS community for at least 2 weeks. To create a forum, hover over the community tab, then click "My AoPS." You should now see your avatar, and a list of your friends. Now, click on the "My Forums" tab. There, you would be able to see which forum you moderate or administrate, as well as the private forums you can access. Click on the "+" button at the top right. This should lead you to a forum creating page.<br />
<br />
====Why do some posts say they were posted in the future?====<br />
:The AoPS clock is based on the official Naval Observatory time. This is considered the most accurate time. If your computer's system clock is behind the correct time, recent posts may indicate they were posted in the future. Please correct your computer's clock or enable clock synchronization so that your clock is always correct. Mac users may wish to check [http://www.macinstruct.com/node/92 Synchronize your Mac's Clock With A Time Server]. You can also check [http://www.time.gov the US offical time.]<br />
<br />
====I've lost admin access to a forum or blog I created, how do I get it back?====<br />
:Please send an email to sheriff@aops.com. They will research your request and restore admin access to your forum if appropriate.<br />
<br />
====What should I do if I find a glitch in the community?====<br />
:First, search the Site Support forum to check if your issue has already been reported. You can search here.<br />
<br />
:If your issue isn't reported, try refreshing your browser page. Most issues go away after a refresh and there is no need to report the issue unless it continues after you refresh your browser. You can refresh on most browsers in Windows with Ctrl + Shift + R and on Mac with Cmd + Shift + R.<br />
<br />
:Some commonly known glitches that should not be reported are avatars appearing twice in the topic list or private message, friends appearing more than once in the friend list, the edit icon showing next to a message when it shouldn't, and not being able to search for a forum after going back a page in the community.<br />
<br />
:Some glitches I have found that should be reported is a little space like thing that counts as <math>8</math> characters, and capitol quote and hide tags to nest more than <math>3</math>.<br />
<br />
==== How do I format my post, e.g. bold text, add URLs, etc.? ====<br />
<br />
:AoPS is based on a markup language called BBCode. A tutorial of its functions on AoPS and how to use them can be found [[BBCode:Tutorial|here]].<br />
<br />
==== How do I hide content in the forums? ====<br />
:Wrap the content you want to hide in [hide] tags.<br />
[hide]Content[/hide]<br />
:If you want to customize the label, instead of saying "Click here to reveal hidden text", you can do something like:<br />
[hide=Label to display]Content[/hide]<br />
<br />
====I got the message "Too many messages." when trying to send a private message, why?====<br />
:To prevent PM spam abuse<br />
like "hvbowibvibviorybvirusbshbiuovvisuvib", users with less than five forum posts are limited to four private messages within a forty-eight hour period.<br />
<br />
==== If I make more posts, it means I'm a better user, right? ====<br />
:Post quality is far more important than post quantity.<br />
<br />
==== I have made some posts but my post count did not increase. Why? ====<br />
:When you post in some of the forums, such as the Test Forum, Mafia Forum, Fun Factory, and most user created forums, the post does not count towards your overall post count. And still. Quality over quantity.<br />
<br />
==== I believe a post needs corrective action. What should I do? ====<br />
:If you believe a post needs moderative action, you may report it by clicking the "!" icon on the upper-right corner of that post. If it's a minor mistake, you may want to PM the offending user instead and explain how they can make their post better. Usually, you shouldn't publicly post such things on a thread itself, which is called "backseat moderation" and is considered rude and unproductive.<br />
<br />
==== How do I post images? ====<br />
:While AoPS forums have the ability to attach images, we do not generally recommend doing so, as we can not guarantee the images will be available through upgrades, restorations, etc. We also have limited disk space which causes us to remove attachments from time to time. Therefore, we recommend using a third party image hosting solution. There are many options, but we recommend imgur.com.<br />
<br />
:* Go to imgur.com<br />
:* Click upload images<br />
:* Follow the on screen instructions to upload the image to imgur.<br />
:* After uploading, view your image<br />
:* Right click (cmd-click on mac) and select something similar to "Copy image address"<br />
:* In your post, paste the image address and surround it by [img]..[/img] tags<br />
<br />
====How do I become a moderator of a forum?====<br />
:The creators of user-created forums select moderators in several different ways. Contact the creator(s) of the forum for more information.<br />
<br />
:The AoPS staff will select moderators for the major forums on an as-needed basis. If the AoPS staff determines that a forum needs additional moderators, then the staff will reach out to productive users and invite them to become moderators. These are some features that the AoPS staff may consider when selecting new moderators.<br />
<br />
:* An established history of productive posting. No unproductive, spammy, or troll posts in the past several years. (For example, a high school student might have made some poor choices while in elementary school -- but then learned from those mistakes.)<br />
:* No use of \8char or other strategies to get around rules or restrictions on the forums.<br />
:* When the user reports posts, the report is useful and helpful, and the reported post (or thread, or user) really did reflect a serious issue worthy of administrators' attention. The user filled in the "Further details" field with valuable information. The user does not report the use of phrases such as "gosh, golly gee" as profanity.<br />
:* No multis.<br />
:* No backseat moderating, no posting of "\requestlock".<br />
:* When the user revives an old thread, the new post is valuable and relevant.<br />
:* The user does not use the forums to cheat on Alcumus, homework, contests, or similar activities.<br />
<br />
== Blogs ==<br />
==== How come I can't create a blog? ====<br />
:One needs to have at least 5 posts in order to make a blog.<br />
<br />
==== How do I make my blog look nice? ====<br />
:Many AoPSers make their blogs look awesome by applying [[CSS|CSS]], which is a high-level stylesheet language. This can be done by typing CSS code into the CSS box in the Blog Control Panel.<br />
<br />
== Alcumus ==<br />
<br />
==== How is rating computed? ====<br />
:The rating is more of a prediction of what percentage of problems in the topic the Alcumus engine believes you will get correct. As you get more and more correct, the rating will go up slower and slower. However, if you are predicted to get most correct, and you miss one or two problems, the rating, or prediction of percentage correct, will go down.<br />
<br />
==== I am stuck on a problem, and changing the topic does not change the problem. ====<br />
:Alcumus provides review problems to make sure you still recall information learned from the past. You are not able to skip these problems. You will need to answer the problem before moving on.<br />
<br />
==== Why can't I change topics? ====<br />
:Alcumus provides review problems to make sure you still recall information learned from the past. You are not able to skip these problems. You will need to answer the problem before the topic changes to the currently selected topic.<br />
<br />
== Contests ==<br />
==== Where can I find past contest questions and solutions? ====<br />
:In the [http://www.artofproblemsolving.com/Forum/resources.php Contests] section.<br />
<br />
==== How do I get problems onto the contest page? ====<br />
<br />
:Make a topic for each question in the appropriate forum, copy/paste the urls to the National Olympiad. Your problems may eventually be submitted into the Contest page.<br />
<br />
==== What are the guidelines for posting problems to be added to the contests section? ====<br />
:Refer to the [http://www.artofproblemsolving.com/Forum/viewtopic.php?f=144&t=195579 guidelines in this post].<br />
<br />
==== Why is the wiki missing many contest questions? ====<br />
:Generally, it is because users have not yet posted them onto the wiki (translation difficulties, not having access to the actual problems, lack of interest, etc). If you have a copy, please post the problems in the Community Section! In some cases, however, problems may be missing due to copyright claims from maths organizations.<br />
<br />
== LaTeX and Asymptote ==<br />
==== What is LaTeX, and how do I use it? ====<br />
<br />
:<math>\text{\LaTeX}</math> is a typesetting markup language that is useful to produce properly formatted mathematical and scientific expressions.<br />
<br />
==== How can I download LaTeX to use on the forums? ====<br />
<br />
:There are no downloads necessary; the forums and the wiki render LaTeX commands between dollar signs. <br />
<br />
==== How can I download LaTeX for personal use? ====<br />
:You can download TeXstudio [http://texstudio.sourceforge.net here] or TeXnicCenter [http://www.texniccenter.org here]<br />
<br />
==== Where can I find a list of LaTeX commands? ====<br />
:See [[LaTeX:Symbols|here]].<br />
<br />
==== Where can I test LaTeX commands? ====<br />
<br />
:[[A:SAND|Sandbox]] or [http://www.artofproblemsolving.com/Resources/texer.php TeXeR]. You can also use our [http://artofproblemsolving.com/community/c67_test_forum Test Forum].<br />
<br />
==== Where can I find examples of Asymptote diagrams and code? ====<br />
<br />
:Search this wiki for the <tt><nowiki><asy></nowiki></tt> tag or the Forums for the <tt><nowiki>[asy]</nowiki></tt> tag. See also [[Asymptote:_Useful_commands_and_their_Output|these examples]] and [[Proofs without words|this article]] (click on the images to obtain the code).<br />
<br />
==== How can I draw 3D diagrams? ====<br />
<br />
:See [[Asymptote: 3D graphics]].<br />
<br />
==== What is the cse5 package? ==== <br />
<br />
:See [http://www.artofproblemsolving.com/Forum/viewtopic.php?f=519&t=149650 here]. The package contains a set of shorthand commands that implement the behavior of usual commands, for example <tt>D()</tt> for <tt>draw()</tt> and <tt>dot()</tt>, and so forth.<br />
<br />
==== What is the olympiad package? ====<br />
<br />
:See [http://www.artofproblemsolving.com/Forum/viewtopic.php?f=519&t=165767 here]. The package contains a set of commands useful for drawing diagrams related to [[:Category:Olympiad Geometry Problems|olympiad geometry problems]].<br />
<br />
== AoPSWiki ==<br />
==== Is there a guide for wiki syntax? ====<br />
<br />
:See [http://en.wikipedia.org/wiki/Help:Wiki_markup wiki markup], [[AoPSWiki:Tutorial]], and [[Help:Contents]].<br />
<br />
==== What do I do if I see a mistake in the wiki? ====<br />
<br />
:Click "edit" and correct the error! (But like, don't touch the acronyms. Plz.)<br />
<br />
== Miscellaneous ==<br />
==== Is it possible to join the AoPS Staff? ====<br />
<br />
:Yes. Mr. Rusczyk will sometimes hire a small army of college students to work as interns, graders, and teaching assistants. You must be at least in your second semester of your senior year and be legal to work in the U.S. (at least 16).<br />
<br />
==== What is the minimum age to be an assistant in an Art of Problem Solving class? ====<br />
<br />
:You must have graduated from high school, or at least be in the second term of your senior year.<br />
<br />
==AoPS Acronyms==<br />
*'''AFK'''- Away from keyboard<br />
*'''AoPS'''- Art of Problem Solving<br />
*'''AIME'''- American Invitational Mathematics Examination<br />
*'''AMC'''- American Math Competitions<br />
*'''AMO'''-USA Mathematical Olympiad<br />
*'''ATM'''- At the Moment/Automated teller machine<br />
*'''brb'''- Be right Back<br />
*'''BTW'''- By the way<br />
*'''CEMC''' - Centre for Mathematics and Computing<br />
*'''C&P or C+P or CP''' - Counting and Probability or Contests and Programs<br />
*'''cbrt''' - Cube Root<br />
*'''EBWOP'''- Editing by way of post<br />
*'''FTFY''' - Fixed that for you<br />
*'''FTW'''- For the Win, a game on AoPS<br />
*'''gg'''- Good Game<br />
*'''gj'''- Good Job<br />
*'''glhf'''-Good Luck Have Fun<br />
*'''gtg''' - Got to go<br />
*'''HSM''' - High School Math Forum<br />
*'''ID(R or E)K'''-I Don't (Really or Even) Know<br />
*'''ID(R or E)C'''-I Don't (Really or Even) Care<br />
*'''iff'''-If and only if<br />
*'''IIRC'''- If I recall correctly<br />
*'''IKR'''- I know, right?<br />
*'''IMO'''- In my opinion (or International Math Olympiad, depending on context)<br />
*'''IMHO'''- In my humble/honest opinion <br />
*'''JMO'''- United States of America Junior Mathematical Olympiad<br />
*'''lol'''- Laugh Out Loud<br />
*'''MC'''- Mathcounts, a popular math contest for Middle School students.<br />
*'''NFL'''- Not for long/No friends left/National Football League<br />
*'''NHL'''-National Hockey League<br />
*'''mod(s)'''- Moderator(s)<br />
*'''MOEMS'''- Math Olympiads for Elementary and Middle Schools<br />
*'''MO(S)P'''- Mathematical Olympiad (Summer) Program<br />
*'''MSM'''- Middle School Math Forum<br />
*'''NIMO'''-National Internet Math Olympiad<br />
*'''NT'''- Number Theory<br />
*'''OBC'''- Online by computer<br />
*'''OMG'''- Oh My Gosh<br />
*'''OMO'''-Online Math Open<br />
*'''OP'''- Original Poster/Original Post/Original Problem, or Overpowered/Overpowering<br />
*'''OSPD'''- Oatsquire Pedigree<br />
*'''PIG'''- Poorly Intellectual Guy/Girl<br />
*'''QED'''- Quod erat demonstrandum, Latin for "Which was to be proven"; some English mathematicians use it as an acronym for Quite Elegantly Done<br />
*'''QS&A'''- Questions, Suggestions, and Announcements Forum<br />
*'''ro(t)fl''' - Rolling on the floor laughing<br />
*'''smh''' - Shaking my head/somehow<br />
*'''sqrt''' - Square root<br />
*'''Sticky'''- A post pinned to the top of a forum - a thing you really should read<br />
*'''ToS'''- Terms of Service - a thing you really should read<br />
*'''USA(J)MO'''- USA (Junior) Mathematical Olympiad<br />
*'''V/LA'''- Vacation or Long Absence/Limited Access<br />
*'''WLOG'''- Without loss of generality<br />
*'''wrt'''- With respect to<br />
*'''wtg''' - Way to go<br />
*'''tytia'''- Thank you, that is all<br />
*'''xD'''- Bursting Laugh<br />
<br />
== FTW! ==<br />
<br />
Please see the [//artofproblemsolving.com/ftw/faq For the Win! FAQ] for many common questions.<br />
<br />
== School ==<br />
<br />
==== What if I miss a class? ====<br />
:There are classroom transcripts available under My Classes, available at the top right of the web site. You can view these transcripts in order to review any missed material. You can also ask questions on the class message board. Don't worry, though, classroom participation usually isn't weighted heavily.<br />
<br />
==== Is there audio or video in class? ====<br />
:There is generally no audio or video in the class. The classes are generally text and image based, in an interactive chat room environment, which allows students to ask questions at any time during the class. In addition to audio and video limiting interactivity and being less pedagogically effective, the technology isn't quite there yet for all students to be able to adequately receive streaming audio and video.<br />
<br />
==== What if I want to drop out of a class? ====<br />
:For any course with more than 2 classes, students can drop the course any time before the third class begins and receive a full refund. No drops are allowed after the third class has started. To drop the class, go to the My Classes section by clicking the My Classes link at the top-right of the website. Then find the area on the right side of the page that lets you drop the class. A refund will be processed within 10 business days.<br />
<br />
==== For my homework, there is supposed to be a green bar but it's orange, why? ====<br />
<br />
:For the bar to turn green, the writing problem must be attempted. Once it is attempted the bar will turn green.<br />
<br />
==== I need more time for my homework, what should I do? ====<br />
<br />
:There is a "Request Extension" button in the homework tab of your class. This will automatically extend the due date to 2 days after the normal deadline. If you want more time you need to ask for it in the little comment box, stating the reason why you want the extension, and how much time you want. This request will be looked at by the teachers and they will decide if you get the extension or not. Note that you can only use this button 3 times.<br />
:Otherwise, you can send an email to extensions@aops.com with your username, class name and ID (the number in the class page URL after https://artofproblemsolving.com/class/) and reason for extension. Someone should get back to you within a couple days.</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93308
Basic Programming With Python
2018-03-17T22:22:27Z
<p>Bestaops: /* Challenge Program */ final bugs fixed</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
(Note: This is a really long article. To learn the most from this article, you need to read everything in order and skip nothing, unless you are '''absolutely absolutely sure that that content is way to easy for you.''')<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
Note that this article has lots of program examples. It is recommended (but not required) to try these on your own before looking at the solutions.<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
for i in range(1,51):<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
<br />
We must not forget to print the total at the end!<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
print(total)<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
i = 3<br />
total = 0<br />
while i < 1000:<br />
total += i<br />
i += 3<br />
print(total)<br />
<br />
In this code, the while loop loops 333 times, until <math>i</math> becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
n = 1<br />
total = 0<br />
while n <= 50:<br />
total += 2**n<br />
n += 1<br />
print(total)<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2)<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
def up_down_arrow(a,b):<br />
return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
return ((a * b * up_down_arrow(a,b)) ** 2)<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
def add_one(x):<br />
return x + 1<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
def add_one(x):<br />
return x + 1<br />
print(add_one(2))<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
def print_function(x):<br />
print(x)<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
def print_function(x):<br />
print(x)<br />
return<br />
print_function("print_function")<br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
if 10*5 > 9:<br />
if 10*5 < 100:<br />
print("Yes")<br />
else:<br />
print("No")<br />
else:<br />
print("No")<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
print("Yes") <br />
else:<br />
print("No")<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
for i in range(10,100):<br />
if check(i):<br />
print(i)<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
def check(a, min, max):<br />
if a*5 > min - 1 and a*5 < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999)<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
print_check(100, 999, 100, 999)<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
def check(a, min, max, factor):<br />
if a*factor > min - 1 and a*factor < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max, check_factor):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check() line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
import random<br />
print(random.randint(1,6))<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
import random<br />
count = 0<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
for i in range(1, 1001):<br />
if roll() == 6:<br />
count += 1<br />
<br />
print(count)<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
print(count(10000))<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
total += count(i)<br />
<br />
print(total)<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
def count2(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count(i)<br />
return total<br />
<br />
def count3(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count2(i)<br />
return total<br />
<br />
print(count3(20))<br />
<br />
(Our program is so long!)<br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while!<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is to soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!<br />
<br />
==Very Basic Datatypes==<br />
<br />
An integer is a basic datatype in Python. Basically, all variables with the datatype of '''int''' is an integer.<br />
<br />
A string is another basic datatype, and it is a string of characters enclosed by quotes.<br />
<br />
===Why Are Datatypes So Important?===<br />
<br />
Let's say we wanted to make a program that would add 2 and 3. Some bogus code would be:<br />
<br />
x="2"<br />
y="3"<br />
print(x+y)<br />
<br />
If you ran this code, you would get 23. Why is that?<br />
<br />
Well, here, x and y are strings. When you perform the addition operator to strings in Python, it concatenates the strings, giving 23.<br />
<br />
The real code is:<br />
<br />
x=2<br />
y=3<br />
print(x+y)<br />
<br />
If you run this, you will get <math>5</math>, which is correct.<br />
<br />
Here's another reason datatypes are important. Now, we will introduce the datatype called the '''floating point number''', or '''float'''. A floating point number is a number with a decimal point.<br />
<br />
Let's go back to the IDLE. Type "0.1*10". The result is 1.0. Notice the decimal point.<br />
<br />
Let's type something different. Type <math>0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1.</math><br />
<br />
'''WHAT!?'''<br />
<br />
You would have expected the answer to be 1, but it isn't 1. What happened?<br />
<br />
'''Float approximation''' happened. Most (almost all) programming languages have a bad float approximation. That means that 1.0 can turn into 0.99999999999999 and 0.5 can turn into 0.49999999999999999993. That only happens with floats, so we should try to use floats as sparingly as possible.<br />
<br />
==Lists==<br />
<br />
A for loop iterates over a '''list'''. A list is a bunch of objects stored in one variable. (Hey! A list is a datatype!) For loops are highly related to lists.<br />
<br />
Let's say we wanted to make a program to print all the items in a list.<br />
<br />
We will first create the list, using the code:<br />
<br />
myList = [1,4,6,8]<br />
<br />
This is a list with four items: 1, 4, 6, and 8.<br />
<br />
We must now print all elements of it with a for loop:<br />
<br />
myList = [1,4,6,8]<br />
for i in myList:<br />
print(i)<br />
<br />
When we run this program, we get the numbers 1, 4, 6, and 8, as expected.<br />
<br />
===Accessing Values===<br />
<br />
Let's say we wanted to print out the second item in a list. We will use '''indexes'''.<br />
<br />
The index of the first item in a list is always 0. The index of the second is 1. The index of the <math>n</math>th is <math>n-1.</math><br />
<br />
To print out the second item, we will use an index of 1, like this:<br />
<br />
myList = [1,4,6,8]<br />
print(myList[1])<br />
<br />
Notice that the index is inside of the square brackets.<br />
<br />
===Adding Values===<br />
<br />
We can use the list.append() function to add an object to the end of a list.<br />
<br />
myList.append(10)<br />
<br />
will add 10 to the list, which makes myList = [1,4,6,8,10].<br />
<br />
===All Kinds Of Lists===<br />
<br />
Lists don't have to be only integers!<br />
<br />
myList = [1,"Hi","Hello world", 3.5, 3.14159265358979323]<br />
<br />
If fact, there can be lists inside of lists!<br />
<br />
myList = [[1,2,3], [3,4,5], [5,6,"Hello world"], "BOB", 3.1415926]<br />
<br />
Even this!<br />
<br />
myList = [[1, [1, [1,2,3],3],3], [[[3,["Hello world", 4],5],4,5],4,5], [5,6,7,[1,[1,2,3],3],"Hello world"], "BOB", 3.1415926, True]<br />
<br />
If you look at that list carefully, you will find lists inside of lists inside of lists inside of lists! And, a boolean at the end!<br />
<br />
Like variables, you can have as many lists in a program as you want (a list is a variable)!<br />
<br />
myList = [1,2,3,4]<br />
yourList = [5,6,7,8]<br />
hisList = [9,10,11,12]<br />
herList = [13,14,15,16]<br />
theirList = [17,18,19,20]<br />
ourList = [21,22,23,24]<br />
listsOfLists = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20],[21,22,23,24]]<br />
<br />
==Dictionaries==<br />
<br />
A dictionary (a type of datatype) is a bunch of keys and values. There is a major difference between dictionaries and lists. Lists are ordered; dictionaries are not.<br />
<br />
Here is the '''syntax''' of creating a dictionary:<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
<br />
This dictionary has two key/value pairs. Notice it is surrounded in curly braces. The keys are 1 and 2; the values are "one" and "two."<br />
<br />
How is this useful? Let's make a simple program to test it out.<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
print(myDictionary[1])<br />
print(myDictionary[2])<br />
<br />
===Accessing Values===<br />
<br />
To access a value in a dictionary, you put in the key.<br />
<br />
myDictionary[1]<br />
<br />
returns one, because 1 is the key to "one."<br />
<br />
===Adding New Values===<br />
<br />
To overwrite a value, we do this.<br />
<br />
myDictionary[1] = "won"<br />
<br />
The value to the key 1 is now "won."<br />
<br />
To add a value, we do the same thing!<br />
<br />
myDictionary[3] = "three"<br />
<br />
This adds a key 3 with a value of "three."<br />
<br />
==Challenge Program==<br />
<br />
In this section, we will attempt the hardest program so far in this article.<br />
<br />
'''Make a conversation generator that will generate random conversations between different people.'''<br />
<br />
First, we will generate the people. We can use a list and generate two random numbers.<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will",<br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
(I made it more organized by separating the long lines of code into multiple lines. It only works when you have a line break right after each item in the list.)<br />
<br />
Here, we use the remove() function to remove person1 from the list to make sure we don't use the same name twice. <br />
<br />
We also used the len() function to find the length of the list (soft-coding!)<br />
<br />
Now, we need to create a list of possible values for the first thing that person1 says (person1 will always be the first one to talk). <br />
<br />
Then, we will print it out.<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will",<br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = [<br />
"Hi!",<br />
"Hello!",<br />
"Good morning!",<br />
"Hello, " + person2 + "!",<br />
"Hi.",<br />
"Hi, " + person2 + "!"<br />
]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
<br />
If we test out this program, we can confirm that this part indeed does work. This program is already getting long! Now, we will use the same method and create the second message.<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will",<br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = [<br />
"Hi!",<br />
"Hello!",<br />
"Good morning!",<br />
"Hello, " + person2 + "!",<br />
"Hi.",<br />
"Hi, " + person2 + "!"<br />
]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
<br />
second = [<br />
"Hi! How are you today?",<br />
"Hello! How are you?",<br />
"Good morning! How are you today?",<br />
"Hello, " + person1 + "! How are you?",<br />
"Hi. How are you?",<br />
"Hi, " + person1 + "! How are you today?"<br />
]<br />
print(person2 + ": " + second[random.randint(0, (len(second) - 1))])<br />
<br />
We will repeat this for the rest of the conversation:<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will", <br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = [<br />
"Hi!",<br />
"Hello!",<br />
"Good morning!",<br />
"Hello, " + person2 + "!",<br />
"Hi.",<br />
"Hi, " + person2 + "!"<br />
]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
<br />
second = [<br />
"Hi! How are you today?",<br />
"Hello! How are you?",<br />
"Good morning! How are you today?",<br />
"Hello, " + person1 + "! How are you?",<br />
"Hi. How are you?",<br />
"Hi, " + person1 + "! How are you today?"<br />
]<br />
print(person2 + ": " + second[random.randint(0, (len(second) - 1))])<br />
<br />
third = [<br />
"I'm feeling awesome! And you?",<br />
"I'm feeling alright! How are you?",<br />
"I'm good, thank you. How are you feeling?",<br />
"I'm fine!" ,<br />
"How are you today?"<br />
]<br />
print(person1 + ": " + third[random.randint(0, (len(third) - 1))])<br />
<br />
fourth = [<br />
"I'm feeling great!",<br />
"I'm awesome!",<br />
"Thanks for asking! I am feeling good today!",<br />
"I'm feeling awesome today! Yippee!"<br />
] <br />
print(person2 + ": " + fourth[random.randint(0, (len(fourth) - 1))])<br />
<br />
fifth = [<br />
"It's so nice out today!",<br />
"Today is such a cloudy day.",<br />
"I hate it when it is so cloudy outside!",<br />
"It's partly cloudy today!"<br />
]<br />
print(person1 + ": " + fifth[random.randint(0, (len(fifth) - 1))])<br />
<br />
sixth = [<br />
"I know, right?",<br />
"I know.",<br />
"Yeah!",<br />
"True."<br />
]<br />
print(person2 + ": " + sixth[random.randint(0, (len(sixth) - 1))])<br />
<br />
seventh = [<br />
"Sorry, I need to leave. Bye!",<br />
"I gotta go. Bye!",<br />
"Sorry, I don't have time to stay and chat. I've got to go somewhere. Bye!"<br />
]<br />
print(person1 + ": " + seventh[random.randint(0, (len(seventh) - 1))])<br />
<br />
eighth = [<br />
"Bye!",<br />
"Good-bye!",<br />
"Bye, " + person1 + "."<br />
]<br />
print(person2 + ": " + eighth[random.randint(0, (len(eighth) - 1))])<br />
<br />
Whew! So long!<br />
<br />
Once we run our program. It works! This program really wasn't that hard.<br />
<br />
Congrats! You've made it so far!<br />
<br />
We are not done yet.<br />
<br />
There are quite a few things we need to cover.<br />
<br />
We have used a bit of code in our program that we have not learned yet.<br />
<br />
===Concepts===<br />
<br />
This section will talk about some concepts in our code that we haven't learned yet.<br />
<br />
====Concatenating Strings====<br />
<br />
Concatenating strings is putting them together. For example, "one" concatenated with "two" gives "onetwo."<br />
<br />
In our code, we concatenated strings.<br />
<br />
"Hello, " + person2 + "! How are you?"<br />
<br />
depends on what person2 was. If person2 was Bob, the string would be:<br />
<br />
"Hello, Bob! How are you?"<br />
<br />
It fits together perfectly!<br />
<br />
You cannot concatenate strings with integers. For example, doing this:<br />
<br />
"2" + 3<br />
<br />
will not work. Instead, to get an answer of "23", you must do this:<br />
<br />
"2" + str(3)<br />
<br />
That turns 3 into a string so it is "3", and the result will be "23".<br />
<br />
====Removing Items From Lists====<br />
<br />
We can use the list.remove() function to remove a specific item in a list.<br />
<br />
For example, consider this code.<br />
<br />
myList = [1,2,3]<br />
myList.remove(3)<br />
<br />
This code will make myList turn into [1,2]. The element, 3, gets removed.<br />
<br />
====Line Breaks====<br />
<br />
In our code, we used multiple line breaks to make our code more organized. There are some places that you cannot line break. For example, this code will produce an error:<br />
<br />
myList =<br />
[1,2,3]<br />
<br />
This code does not work.<br />
<br />
This code '''does work''':<br />
<br />
myList = [<br />
1,2,3]<br />
<br />
It is accepted when you break a line right after the [. It is also accepted right after a comma. (And right before the ending ].)<br />
<br />
myList = [<br />
1,<br />
2,<br />
3<br />
]<br />
<br />
That is what we did in our code.<br />
<br />
====len(list)====<br />
<br />
The len(list) function returns the length of a list.<br />
<br />
This code will print 3.<br />
<br />
myList = [1,2,3]<br />
print(len(myList))<br />
<br />
The length of myList is 3, so Python prints 3.<br />
<br />
Now look back at our final conversation program code. Make sure you '''understand every bit of it'''. It '''must''' be crystal clear to you or you will not benefit from this. Make sure you are not just '''copy and pasting''' the code! That will not help you at all!</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93307
Basic Programming With Python
2018-03-17T22:16:15Z
<p>Bestaops: /* Challenge Program */ added contents more of them!</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
(Note: This is a really long article. To learn the most from this article, you need to read everything in order and skip nothing, unless you are '''absolutely absolutely sure that that content is way to easy for you.''')<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
Note that this article has lots of program examples. It is recommended (but not required) to try these on your own before looking at the solutions.<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
for i in range(1,51):<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
<br />
We must not forget to print the total at the end!<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
print(total)<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
i = 3<br />
total = 0<br />
while i < 1000:<br />
total += i<br />
i += 3<br />
print(total)<br />
<br />
In this code, the while loop loops 333 times, until <math>i</math> becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
n = 1<br />
total = 0<br />
while n <= 50:<br />
total += 2**n<br />
n += 1<br />
print(total)<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2)<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
def up_down_arrow(a,b):<br />
return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
return ((a * b * up_down_arrow(a,b)) ** 2)<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
def add_one(x):<br />
return x + 1<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
def add_one(x):<br />
return x + 1<br />
print(add_one(2))<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
def print_function(x):<br />
print(x)<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
def print_function(x):<br />
print(x)<br />
return<br />
print_function("print_function")<br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
if 10*5 > 9:<br />
if 10*5 < 100:<br />
print("Yes")<br />
else:<br />
print("No")<br />
else:<br />
print("No")<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
print("Yes") <br />
else:<br />
print("No")<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
for i in range(10,100):<br />
if check(i):<br />
print(i)<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
def check(a, min, max):<br />
if a*5 > min - 1 and a*5 < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999)<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
print_check(100, 999, 100, 999)<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
def check(a, min, max, factor):<br />
if a*factor > min - 1 and a*factor < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max, check_factor):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check() line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
import random<br />
print(random.randint(1,6))<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
import random<br />
count = 0<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
for i in range(1, 1001):<br />
if roll() == 6:<br />
count += 1<br />
<br />
print(count)<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
print(count(10000))<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
total += count(i)<br />
<br />
print(total)<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
def count2(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count(i)<br />
return total<br />
<br />
def count3(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count2(i)<br />
return total<br />
<br />
print(count3(20))<br />
<br />
(Our program is so long!)<br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while!<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is to soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!<br />
<br />
==Very Basic Datatypes==<br />
<br />
An integer is a basic datatype in Python. Basically, all variables with the datatype of '''int''' is an integer.<br />
<br />
A string is another basic datatype, and it is a string of characters enclosed by quotes.<br />
<br />
===Why Are Datatypes So Important?===<br />
<br />
Let's say we wanted to make a program that would add 2 and 3. Some bogus code would be:<br />
<br />
x="2"<br />
y="3"<br />
print(x+y)<br />
<br />
If you ran this code, you would get 23. Why is that?<br />
<br />
Well, here, x and y are strings. When you perform the addition operator to strings in Python, it concatenates the strings, giving 23.<br />
<br />
The real code is:<br />
<br />
x=2<br />
y=3<br />
print(x+y)<br />
<br />
If you run this, you will get <math>5</math>, which is correct.<br />
<br />
Here's another reason datatypes are important. Now, we will introduce the datatype called the '''floating point number''', or '''float'''. A floating point number is a number with a decimal point.<br />
<br />
Let's go back to the IDLE. Type "0.1*10". The result is 1.0. Notice the decimal point.<br />
<br />
Let's type something different. Type <math>0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1.</math><br />
<br />
'''WHAT!?'''<br />
<br />
You would have expected the answer to be 1, but it isn't 1. What happened?<br />
<br />
'''Float approximation''' happened. Most (almost all) programming languages have a bad float approximation. That means that 1.0 can turn into 0.99999999999999 and 0.5 can turn into 0.49999999999999999993. That only happens with floats, so we should try to use floats as sparingly as possible.<br />
<br />
==Lists==<br />
<br />
A for loop iterates over a '''list'''. A list is a bunch of objects stored in one variable. (Hey! A list is a datatype!) For loops are highly related to lists.<br />
<br />
Let's say we wanted to make a program to print all the items in a list.<br />
<br />
We will first create the list, using the code:<br />
<br />
myList = [1,4,6,8]<br />
<br />
This is a list with four items: 1, 4, 6, and 8.<br />
<br />
We must now print all elements of it with a for loop:<br />
<br />
myList = [1,4,6,8]<br />
for i in myList:<br />
print(i)<br />
<br />
When we run this program, we get the numbers 1, 4, 6, and 8, as expected.<br />
<br />
===Accessing Values===<br />
<br />
Let's say we wanted to print out the second item in a list. We will use '''indexes'''.<br />
<br />
The index of the first item in a list is always 0. The index of the second is 1. The index of the <math>n</math>th is <math>n-1.</math><br />
<br />
To print out the second item, we will use an index of 1, like this:<br />
<br />
myList = [1,4,6,8]<br />
print(myList[1])<br />
<br />
Notice that the index is inside of the square brackets.<br />
<br />
===Adding Values===<br />
<br />
We can use the list.append() function to add an object to the end of a list.<br />
<br />
myList.append(10)<br />
<br />
will add 10 to the list, which makes myList = [1,4,6,8,10].<br />
<br />
===All Kinds Of Lists===<br />
<br />
Lists don't have to be only integers!<br />
<br />
myList = [1,"Hi","Hello world", 3.5, 3.14159265358979323]<br />
<br />
If fact, there can be lists inside of lists!<br />
<br />
myList = [[1,2,3], [3,4,5], [5,6,"Hello world"], "BOB", 3.1415926]<br />
<br />
Even this!<br />
<br />
myList = [[1, [1, [1,2,3],3],3], [[[3,["Hello world", 4],5],4,5],4,5], [5,6,7,[1,[1,2,3],3],"Hello world"], "BOB", 3.1415926, True]<br />
<br />
If you look at that list carefully, you will find lists inside of lists inside of lists inside of lists! And, a boolean at the end!<br />
<br />
Like variables, you can have as many lists in a program as you want (a list is a variable)!<br />
<br />
myList = [1,2,3,4]<br />
yourList = [5,6,7,8]<br />
hisList = [9,10,11,12]<br />
herList = [13,14,15,16]<br />
theirList = [17,18,19,20]<br />
ourList = [21,22,23,24]<br />
listsOfLists = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20],[21,22,23,24]]<br />
<br />
==Dictionaries==<br />
<br />
A dictionary (a type of datatype) is a bunch of keys and values. There is a major difference between dictionaries and lists. Lists are ordered; dictionaries are not.<br />
<br />
Here is the '''syntax''' of creating a dictionary:<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
<br />
This dictionary has two key/value pairs. Notice it is surrounded in curly braces. The keys are 1 and 2; the values are "one" and "two."<br />
<br />
How is this useful? Let's make a simple program to test it out.<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
print(myDictionary[1])<br />
print(myDictionary[2])<br />
<br />
===Accessing Values===<br />
<br />
To access a value in a dictionary, you put in the key.<br />
<br />
myDictionary[1]<br />
<br />
returns one, because 1 is the key to "one."<br />
<br />
===Adding New Values===<br />
<br />
To overwrite a value, we do this.<br />
<br />
myDictionary[1] = "won"<br />
<br />
The value to the key 1 is now "won."<br />
<br />
To add a value, we do the same thing!<br />
<br />
myDictionary[3] = "three"<br />
<br />
This adds a key 3 with a value of "three."<br />
<br />
==Challenge Program==<br />
<br />
In this section, we will attempt the hardest program so far in this article.<br />
<br />
'''Make a conversation generator that will generate random conversations between different people.'''<br />
<br />
First, we will generate the people. We can use a list and generate two random numbers.<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will",<br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
(I made it more organized by separating the long lines of code into multiple lines. It only works when you have a line break right after each item in the list.)<br />
<br />
Here, we use the remove() function to remove person1 from the list to make sure we don't use the same name twice. <br />
<br />
We also used the len() function to find the length of the list (soft-coding!)<br />
<br />
Now, we need to create a list of possible values for the first thing that person1 says (person1 will always be the first one to talk). <br />
<br />
Then, we will print it out.<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will",<br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = [<br />
"Hi!",<br />
"Hello!",<br />
"Good morning!",<br />
"Hello, " + person2 + "!",<br />
"Hi.",<br />
"Hi, " + person2 + "!"<br />
]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
<br />
If we test out this program, we can confirm that this part indeed does work. This program is already getting long! Now, we will use the same method and create the second message.<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will",<br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = [<br />
"Hi!",<br />
"Hello!",<br />
"Good morning!",<br />
"Hello, " + person2 + "!",<br />
"Hi.",<br />
"Hi, " + person2 + "!"<br />
]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
<br />
second = [<br />
"Hi! How are you today?",<br />
"Hello! How are you?",<br />
"Good morning! How are you today?",<br />
"Hello, " + person2 + "! How are you?",<br />
"Hi. How are you?",<br />
"Hi, " + person2 + "! How are you today?"<br />
]<br />
print(person2 + ": " + second[random.randint(0, (len(second) - 1))])<br />
<br />
We will repeat this for the rest of the conversation:<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will", <br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = [<br />
"Hi!",<br />
"Hello!",<br />
"Good morning!",<br />
"Hello, " + person2 + "!",<br />
"Hi.",<br />
"Hi, " + person2 + "!"<br />
]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
<br />
second = [<br />
"Hi! How are you today?",<br />
"Hello! How are you?",<br />
"Good morning! How are you today?",<br />
"Hello, " + person2 + "! How are you?",<br />
"Hi. How are you?",<br />
"Hi, " + person2 + "! How are you today?"<br />
]<br />
print(person2 + ": " + second[random.randint(0, (len(second) - 1))])<br />
<br />
third = [<br />
"I'm feeling awesome! And you?",<br />
"I'm feeling alright! How are you?",<br />
"I'm good, thank you. How are you feeling?",<br />
"I'm fine!" <br />
"How are you today?"<br />
]<br />
print(person1 + ": " + third[random.randint(0, (len(third) - 1))])<br />
<br />
fourth = [<br />
"I'm feeling great!",<br />
"I'm awesome!",<br />
"Thanks for asking! I am feeling good today!",<br />
"I'm feeling awesome today! Yippee!"<br />
] <br />
print(person2 + ": " + fourth[random.randint(0, (len(fourth) - 1))])<br />
<br />
fifth = [<br />
"It's so nice out today!",<br />
"Today is such a cloudy day.",<br />
"I hate it when it is so cloudy outside!",<br />
"It's partly cloudy today!"<br />
]<br />
print(person1 + ": " + fifth[random.randint(0, (len(fifth) - 1))])<br />
<br />
sixth = [<br />
"I know, right?",<br />
"I know.",<br />
"Yeah!",<br />
"True."<br />
]<br />
print(person2 + ": " + sixth[random.randint(0, (len(sixth) - 1))])<br />
<br />
seventh = [<br />
"Sorry, I need to leave. Bye!",<br />
"I gotta go. Bye!",<br />
"Sorry, I don't have time to stay and chat. I've got to go somewhere. Bye!"<br />
]<br />
print(person1 + ": " + seventh[random.randint(0, (len(seventh) - 1))])<br />
<br />
eighth = [<br />
"Bye!",<br />
"Good-bye!",<br />
"Bye, " + person1 + "."<br />
]<br />
print(person2 + ": " + eighth[random.randint(0, (len(eighth) - 1))])<br />
<br />
Whew! So long!<br />
<br />
Once we run our program. It works! This program really wasn't that hard.<br />
<br />
Congrats! You've made it so far!<br />
<br />
We are not done yet.<br />
<br />
There are quite a few things we need to cover.<br />
<br />
We have used a bit of code in our program that we have not learned yet.<br />
<br />
===Concepts===<br />
<br />
This section will talk about some concepts in our code that we haven't learned yet.<br />
<br />
====Concatenating Strings====<br />
<br />
Concatenating strings is putting them together. For example, "one" concatenated with "two" gives "onetwo."<br />
<br />
In our code, we concatenated strings.<br />
<br />
"Hello, " + person2 + "! How are you?"<br />
<br />
depends on what person2 was. If person2 was Bob, the string would be:<br />
<br />
"Hello, Bob! How are you?"<br />
<br />
It fits together perfectly!<br />
<br />
You cannot concatenate strings with integers. For example, doing this:<br />
<br />
"2" + 3<br />
<br />
will not work. Instead, to get an answer of "23", you must do this:<br />
<br />
"2" + str(3)<br />
<br />
That turns 3 into a string so it is "3", and the result will be "23".<br />
<br />
====Removing Items From Lists====<br />
<br />
We can use the list.remove() function to remove a specific item in a list.<br />
<br />
For example, consider this code.<br />
<br />
myList = [1,2,3]<br />
myList.remove(3)<br />
<br />
This code will make myList turn into [1,2]. The element, 3, gets removed.<br />
<br />
====Line Breaks====<br />
<br />
In our code, we used multiple line breaks to make our code more organized. There are some places that you cannot line break. For example, this code will produce an error:<br />
<br />
myList =<br />
[1,2,3]<br />
<br />
This code does not work.<br />
<br />
This code '''does work''':<br />
<br />
myList = [<br />
1,2,3]<br />
<br />
It is accepted when you break a line right after the [. It is also accepted right after a comma. (And right before the ending ].)<br />
<br />
myList = [<br />
1,<br />
2,<br />
3<br />
]<br />
<br />
That is what we did in our code.<br />
<br />
====len(list)====<br />
<br />
The len(list) function returns the length of a list.<br />
<br />
This code will print 3.<br />
<br />
myList = [1,2,3]<br />
print(len(myList))<br />
<br />
The length of myList is 3, so Python prints 3.<br />
<br />
Now look back at our final conversation program code. Make sure you '''understand every bit of it'''. It '''must''' be crystal clear to you or you will not benefit from this. Make sure you are not just '''copy and pasting''' the code! That will not help you at all!</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93306
Basic Programming With Python
2018-03-17T21:56:38Z
<p>Bestaops: Fixed Bugs</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
(Note: This is a really long article. To learn the most from this article, you need to read everything in order and skip nothing, unless you are '''absolutely absolutely sure that that content is way to easy for you.''')<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
Note that this article has lots of program examples. It is recommended (but not required) to try these on your own before looking at the solutions.<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
for i in range(1,51):<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
<br />
We must not forget to print the total at the end!<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
print(total)<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
i = 3<br />
total = 0<br />
while i < 1000:<br />
total += i<br />
i += 3<br />
print(total)<br />
<br />
In this code, the while loop loops 333 times, until <math>i</math> becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
n = 1<br />
total = 0<br />
while n <= 50:<br />
total += 2**n<br />
n += 1<br />
print(total)<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2)<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
def up_down_arrow(a,b):<br />
return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
return ((a * b * up_down_arrow(a,b)) ** 2)<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
def add_one(x):<br />
return x + 1<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
def add_one(x):<br />
return x + 1<br />
print(add_one(2))<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
def print_function(x):<br />
print(x)<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
def print_function(x):<br />
print(x)<br />
return<br />
print_function("print_function")<br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
if 10*5 > 9:<br />
if 10*5 < 100:<br />
print("Yes")<br />
else:<br />
print("No")<br />
else:<br />
print("No")<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
print("Yes") <br />
else:<br />
print("No")<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
for i in range(10,100):<br />
if check(i):<br />
print(i)<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
def check(a, min, max):<br />
if a*5 > min - 1 and a*5 < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999)<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
print_check(100, 999, 100, 999)<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
def check(a, min, max, factor):<br />
if a*factor > min - 1 and a*factor < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max, check_factor):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check() line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
import random<br />
print(random.randint(1,6))<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
import random<br />
count = 0<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
for i in range(1, 1001):<br />
if roll() == 6:<br />
count += 1<br />
<br />
print(count)<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
print(count(10000))<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
total += count(i)<br />
<br />
print(total)<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
def count2(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count(i)<br />
return total<br />
<br />
def count3(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count2(i)<br />
return total<br />
<br />
print(count3(20))<br />
<br />
(Our program is so long!)<br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while!<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is to soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!<br />
<br />
==Very Basic Datatypes==<br />
<br />
An integer is a basic datatype in Python. Basically, all variables with the datatype of '''int''' is an integer.<br />
<br />
A string is another basic datatype, and it is a string of characters enclosed by quotes.<br />
<br />
===Why Are Datatypes So Important?===<br />
<br />
Let's say we wanted to make a program that would add 2 and 3. Some bogus code would be:<br />
<br />
x="2"<br />
y="3"<br />
print(x+y)<br />
<br />
If you ran this code, you would get 23. Why is that?<br />
<br />
Well, here, x and y are strings. When you perform the addition operator to strings in Python, it concatenates the strings, giving 23.<br />
<br />
The real code is:<br />
<br />
x=2<br />
y=3<br />
print(x+y)<br />
<br />
If you run this, you will get <math>5</math>, which is correct.<br />
<br />
Here's another reason datatypes are important. Now, we will introduce the datatype called the '''floating point number''', or '''float'''. A floating point number is a number with a decimal point.<br />
<br />
Let's go back to the IDLE. Type "0.1*10". The result is 1.0. Notice the decimal point.<br />
<br />
Let's type something different. Type <math>0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1.</math><br />
<br />
'''WHAT!?'''<br />
<br />
You would have expected the answer to be 1, but it isn't 1. What happened?<br />
<br />
'''Float approximation''' happened. Most (almost all) programming languages have a bad float approximation. That means that 1.0 can turn into 0.99999999999999 and 0.5 can turn into 0.49999999999999999993. That only happens with floats, so we should try to use floats as sparingly as possible.<br />
<br />
==Lists==<br />
<br />
A for loop iterates over a '''list'''. A list is a bunch of objects stored in one variable. (Hey! A list is a datatype!) For loops are highly related to lists.<br />
<br />
Let's say we wanted to make a program to print all the items in a list.<br />
<br />
We will first create the list, using the code:<br />
<br />
myList = [1,4,6,8]<br />
<br />
This is a list with four items: 1, 4, 6, and 8.<br />
<br />
We must now print all elements of it with a for loop:<br />
<br />
myList = [1,4,6,8]<br />
for i in myList:<br />
print(i)<br />
<br />
When we run this program, we get the numbers 1, 4, 6, and 8, as expected.<br />
<br />
===Accessing Values===<br />
<br />
Let's say we wanted to print out the second item in a list. We will use '''indexes'''.<br />
<br />
The index of the first item in a list is always 0. The index of the second is 1. The index of the <math>n</math>th is <math>n-1.</math><br />
<br />
To print out the second item, we will use an index of 1, like this:<br />
<br />
myList = [1,4,6,8]<br />
print(myList[1])<br />
<br />
Notice that the index is inside of the square brackets.<br />
<br />
===Adding Values===<br />
<br />
We can use the list.append() function to add an object to the end of a list.<br />
<br />
myList.append(10)<br />
<br />
will add 10 to the list, which makes myList = [1,4,6,8,10].<br />
<br />
===All Kinds Of Lists===<br />
<br />
Lists don't have to be only integers!<br />
<br />
myList = [1,"Hi","Hello world", 3.5, 3.14159265358979323]<br />
<br />
If fact, there can be lists inside of lists!<br />
<br />
myList = [[1,2,3], [3,4,5], [5,6,"Hello world"], "BOB", 3.1415926]<br />
<br />
Even this!<br />
<br />
myList = [[1, [1, [1,2,3],3],3], [[[3,["Hello world", 4],5],4,5],4,5], [5,6,7,[1,[1,2,3],3],"Hello world"], "BOB", 3.1415926, True]<br />
<br />
If you look at that list carefully, you will find lists inside of lists inside of lists inside of lists! And, a boolean at the end!<br />
<br />
Like variables, you can have as many lists in a program as you want (a list is a variable)!<br />
<br />
myList = [1,2,3,4]<br />
yourList = [5,6,7,8]<br />
hisList = [9,10,11,12]<br />
herList = [13,14,15,16]<br />
theirList = [17,18,19,20]<br />
ourList = [21,22,23,24]<br />
listsOfLists = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20],[21,22,23,24]]<br />
<br />
==Dictionaries==<br />
<br />
A dictionary (a type of datatype) is a bunch of keys and values. There is a major difference between dictionaries and lists. Lists are ordered; dictionaries are not.<br />
<br />
Here is the '''syntax''' of creating a dictionary:<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
<br />
This dictionary has two key/value pairs. Notice it is surrounded in curly braces. The keys are 1 and 2; the values are "one" and "two."<br />
<br />
How is this useful? Let's make a simple program to test it out.<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
print(myDictionary[1])<br />
print(myDictionary[2])<br />
<br />
===Accessing Values===<br />
<br />
To access a value in a dictionary, you put in the key.<br />
<br />
myDictionary[1]<br />
<br />
returns one, because 1 is the key to "one."<br />
<br />
===Adding New Values===<br />
<br />
To overwrite a value, we do this.<br />
<br />
myDictionary[1] = "won"<br />
<br />
The value to the key 1 is now "won."<br />
<br />
To add a value, we do the same thing!<br />
<br />
myDictionary[3] = "three"<br />
<br />
This adds a key 3 with a value of "three."<br />
<br />
==Challenge Program==<br />
<br />
In this section, we will attempt the hardest program so far in this article.<br />
<br />
'''Make a conversation generator that will generate random conversations between different people.'''<br />
<br />
First, we will generate the people. We can use a list and generate two random numbers.<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will",<br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
(I made it more organized by separating the long lines of code into multiple lines. It only works when you have a line break right after each item in the list.)<br />
<br />
Here, we use the remove() function to remove person1 from the list to make sure we don't use the same name twice. <br />
<br />
We also used the len() function to find the length of the list (soft-coding!)<br />
<br />
Now, we need to create a list of possible values for the first thing that person1 says (person1 will always be the first one to talk). <br />
<br />
Then, we will print it out.<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will",<br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = [<br />
"Hi!",<br />
"Hello!",<br />
"Good morning!",<br />
"Hello, " + person2 + "!",<br />
"Hi.",<br />
"Hi, " + person2 + "!"<br />
]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
<br />
If we test out this program, we can confirm that this part indeed does work. This program is already getting long! Now, we will use the same method and create the second message.<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will",<br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = [<br />
"Hi!",<br />
"Hello!",<br />
"Good morning!",<br />
"Hello, " + person2 + "!",<br />
"Hi.",<br />
"Hi, " + person2 + "!"<br />
]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
<br />
second = [<br />
"Hi! How are you today?",<br />
"Hello! How are you?",<br />
"Good morning! How are you today?",<br />
"Hello, " + person2 + "! How are you?",<br />
"Hi. How are you?",<br />
"Hi, " + person2 + "! How are you today?"<br />
]<br />
print(person2 + ": " + second[random.randint(0, (len(second) - 1))])<br />
<br />
We will repeat this for the rest of the conversation:<br />
<br />
import random<br />
<br />
peopleNames = [<br />
"Bob",<br />
"Kyle",<br />
"James",<br />
"Richard",<br />
"Zachary",<br />
"Olivia",<br />
"Jonathan",<br />
"Will", <br />
"Bobby",<br />
"Kevin"<br />
]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = [<br />
"Hi!",<br />
"Hello!",<br />
"Good morning!",<br />
"Hello, " + person2 + "!",<br />
"Hi.",<br />
"Hi, " + person2 + "!"<br />
]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
<br />
second = [<br />
"Hi! How are you today?",<br />
"Hello! How are you?",<br />
"Good morning! How are you today?",<br />
"Hello, " + person2 + "! How are you?",<br />
"Hi. How are you?",<br />
"Hi, " + person2 + "! How are you today?"<br />
]<br />
print(person2 + ": " + second[random.randint(0, (len(second) - 1))])<br />
<br />
third = [<br />
"I'm feeling awesome! And you?",<br />
"I'm feeling alright! How are you?",<br />
"I'm good, thank you. How are you feeling?",<br />
"I'm fine!" <br />
"How are you today?"<br />
]<br />
print(person1 + ": " + third[random.randint(0, (len(third) - 1))])<br />
<br />
fourth = [<br />
"I'm feeling great!",<br />
"I'm awesome!",<br />
"Thanks for asking! I am feeling good today!",<br />
"I'm feeling awesome today! Yippee!"<br />
] <br />
print(person2 + ": " + fourth[random.randint(0, (len(fourth) - 1))])<br />
<br />
fifth = [<br />
"It's so nice out today!",<br />
"Today is such a cloudy day.",<br />
"I hate it when it is so cloudy outside!",<br />
"It's partly cloudy today!"<br />
]<br />
print(person1 + ": " + fifth[random.randint(0, (len(fifth) - 1))])<br />
<br />
sixth = [<br />
"I know, right?",<br />
"I know.",<br />
"Yeah!",<br />
"True."<br />
]<br />
print(person2 + ": " + sixth[random.randint(0, (len(sixth) - 1))])<br />
<br />
seventh = [<br />
"Sorry, I need to leave. Bye!",<br />
"I gotta go. Bye!",<br />
"Sorry, I don't have time to stay and chat. I've got to go somewhere. Bye!"<br />
]<br />
print(person1 + ": " + seventh[random.randint(0, (len(seventh) - 1))])<br />
<br />
eighth = [<br />
"Bye!",<br />
"Good-bye!",<br />
"Bye, " + person1 + "."<br />
]<br />
print(person2 + ": " + eighth[random.randint(0, (len(eighth) - 1))])<br />
<br />
Whew! So long!<br />
<br />
Once we run our program. It works! This program really wasn't that hard.<br />
<br />
Congrats! You've made it so far!<br />
<br />
We are not done yet.</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Talk:2018_AIME_I_Problems/Problem_11&diff=93305
Talk:2018 AIME I Problems/Problem 11
2018-03-17T21:34:55Z
<p>Bestaops: </p>
<hr />
<div>First and second solutions are identical.<br />
<br />
Also, is it now convention to write your username below your solutions?<br />
<br />
I know right? It's not.</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93289
Basic Programming With Python
2018-03-16T19:00:35Z
<p>Bestaops: /* Challenge Program */ finished content</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
(Note: This is a really long article. To learn the most from this article, you need to read everything in order and skip nothing, unless you are '''absolutely absolutely sure that that content is way to easy for you.''')<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
Note that this article has lots of program examples. It is recommended (but not required) to try these on your own before looking at the solutions.<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
for i in range(1,51):<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
<br />
We must not forget to print the total at the end!<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
print(total)<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
i = 3<br />
total = 0<br />
while i < 1000:<br />
total += i<br />
i += 3<br />
print(total)<br />
<br />
In this code, the while loop loops 333 times, until <math>i</math> becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
n = 1<br />
total = 0<br />
while n <= 50:<br />
total += 2**n<br />
n += 1<br />
print(total)<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2)<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
def up_down_arrow(a,b):<br />
return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
return ((a * b * up_down_arrow(a,b)) ** 2)<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
def add_one(x):<br />
return x + 1<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
def add_one(x):<br />
return x + 1<br />
print(add_one(2))<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
def print_function(x):<br />
print(x)<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
def print_function(x):<br />
print(x)<br />
return<br />
print_function("print_function")<br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
if 10*5 > 9:<br />
if 10*5 < 100:<br />
print("Yes")<br />
else:<br />
print("No")<br />
else:<br />
print("No")<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
print("Yes") <br />
else:<br />
print("No")<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
for i in range(10,100):<br />
if check(i):<br />
print(i)<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
def check(a, min, max):<br />
if a*5 > min - 1 and a*5 < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999)<br />
<br />
(Note: This is all in one program. The boxes are separate because it is a relatively long program and I like to keep it organized.)<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
print_check(100, 999, 100, 999)<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
def check(a, min, max, factor):<br />
if a*factor > min - 1 and a*factor < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max, check_factor):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check() line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
import random<br />
print(random.randint(1,6))<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
import random<br />
count = 0<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
for i in range(1, 1001):<br />
if roll() == 6:<br />
count += 1<br />
<br />
print(count)<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
print(count(10000))<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
total += count(i)<br />
<br />
print(total)<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
def count2(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count(i)<br />
return total<br />
<br />
def count3(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count2(i)<br />
return total<br />
<br />
print(count3(20))<br />
<br />
(Our program is so long!)<br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while!<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is to soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!<br />
<br />
==Very Basic Datatypes==<br />
<br />
An integer is a basic datatype in Python. Basically, all variables with the datatype of '''int''' is an integer.<br />
<br />
A string is another basic datatype, and it is a string of characters enclosed by quotes.<br />
<br />
===Why Are Datatypes So Important?===<br />
<br />
Let's say we wanted to make a program that would add 2 and 3. Some bogus code would be:<br />
<br />
x="2"<br />
y="3"<br />
print(x+y)<br />
<br />
If you ran this code, you would get 23. Why is that?<br />
<br />
Well, here, x and y are strings. When you perform the addition operator to strings in Python, it concatenates the strings, giving 23.<br />
<br />
The real code is:<br />
<br />
x=2<br />
y=3<br />
print(x+y)<br />
<br />
If you run this, you will get <math>5</math>, which is correct.<br />
<br />
Here's another reason datatypes are important. Now, we will introduce the datatype called the '''floating point number''', or '''float'''. A floating point number is a number with a decimal point.<br />
<br />
Let's go back to the IDLE. Type "0.1*10". The result is 1.0. Notice the decimal point.<br />
<br />
Let's type something different. Type <math>0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1.</math><br />
<br />
'''WHAT!?'''<br />
<br />
You would have expected the answer to be 1, but it isn't 1. What happened?<br />
<br />
'''Float approximation''' happened. Most (almost all) programming languages have a bad float approximation. That means that 1.0 can turn into 0.99999999999999 and 0.5 can turn into 0.49999999999999999993. That only happens with floats, so we should try to use floats as sparingly as possible.<br />
<br />
==Lists==<br />
<br />
A for loop iterates over a '''list'''. A list is a bunch of objects stored in one variable. (Hey! A list is a datatype!) For loops are highly related to lists.<br />
<br />
Let's say we wanted to make a program to print all the items in a list.<br />
<br />
We will first create the list, using the code:<br />
<br />
myList = [1,4,6,8]<br />
<br />
This is a list with four items: 1, 4, 6, and 8.<br />
<br />
We must now print all elements of it with a for loop:<br />
<br />
myList = [1,4,6,8]<br />
for i in myList:<br />
print(i)<br />
<br />
When we run this program, we get the numbers 1, 4, 6, and 8, as expected.<br />
<br />
===Accessing Values===<br />
<br />
Let's say we wanted to print out the second item in a list. We will use '''indexes'''.<br />
<br />
The index of the first item in a list is always 0. The index of the second is 1. The index of the <math>n</math>th is <math>n-1.</math><br />
<br />
To print out the second item, we will use an index of 1, like this:<br />
<br />
myList = [1,4,6,8]<br />
print(myList[1])<br />
<br />
Notice that the index is inside of the square brackets.<br />
<br />
===Adding Values===<br />
<br />
We can use the list.append() function to add an object to the end of a list.<br />
<br />
myList.append(10)<br />
<br />
will add 10 to the list, which makes myList = [1,4,6,8,10].<br />
<br />
===All Kinds Of Lists===<br />
<br />
Lists don't have to be only integers!<br />
<br />
myList = [1,"Hi","Hello world", 3.5, 3.14159265358979323]<br />
<br />
If fact, there can be lists inside of lists!<br />
<br />
myList = [[1,2,3], [3,4,5], [5,6,"Hello world"], "BOB", 3.1415926]<br />
<br />
Even this!<br />
<br />
myList = [[1, [1, [1,2,3],3],3], [[[3,["Hello world", 4],5],4,5],4,5], [5,6,7,[1,[1,2,3],3],"Hello world"], "BOB", 3.1415926, True]<br />
<br />
If you look at that list carefully, you will find lists inside of lists inside of lists inside of lists! And, a boolean at the end!<br />
<br />
Like variables, you can have as many lists in a program as you want (a list is a variable)!<br />
<br />
myList = [1,2,3,4]<br />
yourList = [5,6,7,8]<br />
hisList = [9,10,11,12]<br />
herList = [13,14,15,16]<br />
theirList = [17,18,19,20]<br />
ourList = [21,22,23,24]<br />
listsOfLists = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20],[21,22,23,24]]<br />
<br />
==Dictionaries==<br />
<br />
A dictionary (a type of datatype) is a bunch of keys and values. There is a major difference between dictionaries and lists. Lists are ordered; dictionaries are not.<br />
<br />
Here is the '''syntax''' of creating a dictionary:<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
<br />
This dictionary has two key/value pairs. Notice it is surrounded in curly braces. The keys are 1 and 2; the values are "one" and "two."<br />
<br />
How is this useful? Let's make a simple program to test it out.<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
print(myDictionary[1])<br />
print(myDictionary[2])<br />
<br />
===Accessing Values===<br />
<br />
To access a value in a dictionary, you put in the key.<br />
<br />
myDictionary[1]<br />
<br />
returns one, because 1 is the key to "one."<br />
<br />
===Adding New Values===<br />
<br />
To overwrite a value, we do this.<br />
<br />
myDictionary[1] = "won"<br />
<br />
The value to the key 1 is now "won."<br />
<br />
To add a value, we do the same thing!<br />
<br />
myDictionary[3] = "three"<br />
<br />
This adds a key 3 with a value of "three."<br />
<br />
==Challenge Program==<br />
<br />
In this section, we will attempt the hardest program so far in this article.<br />
<br />
'''Make a conversation generator that will generate random conversations between different people.'''<br />
<br />
First, we will generate the people. We can use a list and generate two random numbers.<br />
<br />
import random<br />
peopleNames = ["Bob", "Kyle", "James", "Richard", "Zachary", "Olivia", "Jonathan", "Will", "Bobby", "Kevin"]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
Here, we use the remove() function to remove person1 from the list to make sure we don't use the same name twice. <br />
<br />
We also used the len() function to find the length of the list (soft-coding!)<br />
<br />
Now, we need to create a list of possible values for the first thing that person1 says (person1 will always be the first one to talk). Then, we will print it out.<br />
<br />
import random<br />
<br />
peopleNames = ["Bob", "Kyle", "James", "Richard", "Zachary", "Olivia", "Jonathan", "Will", "Bobby", "Kevin"]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = ["Hi!", "Hello!", "Good morning!", "Hello, " + person2 + "!", "Hi.", "Hi, " + person2 + "!"]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
<br />
If we test out this program, we can confirm that this part indeed does work. This program is already getting long! Now, we will use the same method and create the second message.<br />
<br />
import random<br />
<br />
peopleNames = ["Bob", "Kyle", "James", "Richard", "Zachary", "Olivia", "Jonathan", "Will", "Bobby", "Kevin"]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = ["Hi!", "Hello!", "Good morning!", "Hello, " + person2 + "!", "Hi.", "Hi, " + person2 + "!"]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
second = ["Hi! How are you today?", "Hello! How are you?", "Good morning! How are you today?", "Hello, " + person2 + "! How are you?", <br />
"Hi. How are you?", "Hi, " + person2 + "! How are you today?"]<br />
print(person2 + ": " + second[random.randint(0, (len(second) - 1))])<br />
<br />
We will repeat this for the rest of the conversation:<br />
<br />
import random<br />
<br />
peopleNames = ["Bob", "Kyle", "James", "Richard", "Zachary", "Olivia", "Jonathan", "Will", "Bobby", "Kevin"]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = ["Hi!", "Hello!", "Good morning!", "Hello, " + person2 + "!", "Hi.", "Hi, " + person2 + "!"]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
second = ["Hi! How are you today?", "Hello! How are you?", "Good morning! How are you today?", "Hello, " + person2 + "! How are you?", " <br />
Hi. How are you?", "Hi, " + person2 + "! How are you today?"]<br />
print(person2 + ": " + second[random.randint(0, (len(second) - 1))])<br />
third = ["I'm feeling awesome! And you?", "I'm feeling alright! How are you?", "I'm good, thank you. How are you feeling?", "I'm fine! <br />
How are you today?"]<br />
print(person1 + ": " + third[random.randint(0, (len(third) - 1))])<br />
fourth = ["I'm feeling great!", "I'm awesome!", "Thanks for asking! I am feeling good today!", "I'm feeling awesome today! Yippee!"]<br />
print(person2 + ": " + fourth[random.randint(0, (len(fourth) - 1))])<br />
fifth = ["It's so nice out today!", "Today is such a cloudy day.", "I hate it when it is so cloudy outside!", "It's partly cloudy today!"]<br />
print(person1 + ": " + fifth[random.randint(0, (len(fifth) - 1))])<br />
sixth = ["I know, right?", "I know.", "Yeah!", "True."]<br />
print(person2 + ": " + sixth[random.randint(0, (len(sixth) - 1))])<br />
seventh = ["Sorry, I need to leave. Bye!", "I gotta go. Bye!", "Sorry, I don't have time to stay and chat. I've got to go somewhere. <br />
Bye!"]<br />
print(person1 + ": " + seventh[random.randint(0, (len(seventh) - 1))])<br />
<br />
Once we run our program. It works! This program really wasn't that hard.<br />
<br />
Congrats! You've made it so far!</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=One&diff=93288
One
2018-03-16T18:02:54Z
<p>Bestaops: /* Exponents */ contents</p>
<hr />
<div>The positive integer one or 1 is smallest positive integer that is greater than zero. It is commonly shown using the Arabic number, 1. <br />
<br />
==PEMDAS Operations==<br />
<br />
===Addition===<br />
When a number is added by one, the number is increased by one.<br />
<br />
For example, 3+1=4.<br />
<br />
===Subtraction===<br />
When a number is subtracted by one, the number is decreased by one.<br />
Examples: 2-1=1, 4-1=3<br />
<br />
When one is subtracted by a number, it depends on what the number is.<br />
<br />
For example: 1-2=-1, 1-(-2)=3<br />
<br />
===Multiplication===<br />
Any number multiplied by One equals the number.<br />
<br />
===Division===<br />
Any number divided by one is that same number.<br />
<br />
===Exponents===<br />
<br />
Any number to the power of 1 is that number.<br />
{{Stub}}</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=One&diff=93287
One
2018-03-16T18:02:33Z
<p>Bestaops: /* Division */ added contents</p>
<hr />
<div>The positive integer one or 1 is smallest positive integer that is greater than zero. It is commonly shown using the Arabic number, 1. <br />
<br />
==PEMDAS Operations==<br />
<br />
===Addition===<br />
When a number is added by one, the number is increased by one.<br />
<br />
For example, 3+1=4.<br />
<br />
===Subtraction===<br />
When a number is subtracted by one, the number is decreased by one.<br />
Examples: 2-1=1, 4-1=3<br />
<br />
When one is subtracted by a number, it depends on what the number is.<br />
<br />
For example: 1-2=-1, 1-(-2)=3<br />
<br />
===Multiplication===<br />
Any number multiplied by One equals the number.<br />
<br />
===Division===<br />
Any number divided by one is that same number.<br />
<br />
===Exponents===<br />
<br />
{{Stub}}</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93251
Basic Programming With Python
2018-03-15T00:55:11Z
<p>Bestaops: /* Challenge Program */ added contents</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
(Note: This is a really long article. To learn the most from this article, you need to read everything in order and skip nothing, unless you are '''absolutely absolutely sure that that content is way to easy for you.''')<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
Note that this article has lots of program examples. It is recommended (but not required) to try these on your own before looking at the solutions.<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
for i in range(1,51):<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
<br />
We must not forget to print the total at the end!<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
print(total)<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
i = 3<br />
total = 0<br />
while i < 1000:<br />
total += i<br />
i += 3<br />
print(total)<br />
<br />
In this code, the while loop loops 333 times, until <math>i</math> becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
n = 1<br />
total = 0<br />
while n <= 50:<br />
total += 2**n<br />
n += 1<br />
print(total)<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2)<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
def up_down_arrow(a,b):<br />
return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
return ((a * b * up_down_arrow(a,b)) ** 2)<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
def add_one(x):<br />
return x + 1<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
def add_one(x):<br />
return x + 1<br />
print(add_one(2))<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
def print_function(x):<br />
print(x)<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
def print_function(x):<br />
print(x)<br />
return<br />
print_function("print_function")<br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
if 10*5 > 9:<br />
if 10*5 < 100:<br />
print("Yes")<br />
else:<br />
print("No")<br />
else:<br />
print("No")<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
print("Yes") <br />
else:<br />
print("No")<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
for i in range(10,100):<br />
if check(i):<br />
print(i)<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
def check(a, min, max):<br />
if a*5 > min - 1 and a*5 < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999)<br />
<br />
(Note: This is all in one program. The boxes are separate because it is a relatively long program and I like to keep it organized.)<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
print_check(100, 999, 100, 999)<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
def check(a, min, max, factor):<br />
if a*factor > min - 1 and a*factor < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max, check_factor):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check() line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
import random<br />
print(random.randint(1,6))<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
import random<br />
count = 0<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
for i in range(1, 1001):<br />
if roll() == 6:<br />
count += 1<br />
<br />
print(count)<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
print(count(10000))<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
total += count(i)<br />
<br />
print(total)<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
def count2(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count(i)<br />
return total<br />
<br />
def count3(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count2(i)<br />
return total<br />
<br />
print(count3(20))<br />
<br />
(Our program is so long!)<br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while!<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is to soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!<br />
<br />
==Very Basic Datatypes==<br />
<br />
An integer is a basic datatype in Python. Basically, all variables with the datatype of '''int''' is an integer.<br />
<br />
A string is another basic datatype, and it is a string of characters enclosed by quotes.<br />
<br />
===Why Are Datatypes So Important?===<br />
<br />
Let's say we wanted to make a program that would add 2 and 3. Some bogus code would be:<br />
<br />
x="2"<br />
y="3"<br />
print(x+y)<br />
<br />
If you ran this code, you would get 23. Why is that?<br />
<br />
Well, here, x and y are strings. When you perform the addition operator to strings in Python, it concatenates the strings, giving 23.<br />
<br />
The real code is:<br />
<br />
x=2<br />
y=3<br />
print(x+y)<br />
<br />
If you run this, you will get <math>5</math>, which is correct.<br />
<br />
Here's another reason datatypes are important. Now, we will introduce the datatype called the '''floating point number''', or '''float'''. A floating point number is a number with a decimal point.<br />
<br />
Let's go back to the IDLE. Type "0.1*10". The result is 1.0. Notice the decimal point.<br />
<br />
Let's type something different. Type <math>0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1.</math><br />
<br />
'''WHAT!?'''<br />
<br />
You would have expected the answer to be 1, but it isn't 1. What happened?<br />
<br />
'''Float approximation''' happened. Most (almost all) programming languages have a bad float approximation. That means that 1.0 can turn into 0.99999999999999 and 0.5 can turn into 0.49999999999999999993. That only happens with floats, so we should try to use floats as sparingly as possible.<br />
<br />
==Lists==<br />
<br />
A for loop iterates over a '''list'''. A list is a bunch of objects stored in one variable. (Hey! A list is a datatype!) For loops are highly related to lists.<br />
<br />
Let's say we wanted to make a program to print all the items in a list.<br />
<br />
We will first create the list, using the code:<br />
<br />
myList = [1,4,6,8]<br />
<br />
This is a list with four items: 1, 4, 6, and 8.<br />
<br />
We must now print all elements of it with a for loop:<br />
<br />
myList = [1,4,6,8]<br />
for i in myList:<br />
print(i)<br />
<br />
When we run this program, we get the numbers 1, 4, 6, and 8, as expected.<br />
<br />
===Accessing Values===<br />
<br />
Let's say we wanted to print out the second item in a list. We will use '''indexes'''.<br />
<br />
The index of the first item in a list is always 0. The index of the second is 1. The index of the <math>n</math>th is <math>n-1.</math><br />
<br />
To print out the second item, we will use an index of 1, like this:<br />
<br />
myList = [1,4,6,8]<br />
print(myList[1])<br />
<br />
Notice that the index is inside of the square brackets.<br />
<br />
===Adding Values===<br />
<br />
We can use the list.append() function to add an object to the end of a list.<br />
<br />
myList.append(10)<br />
<br />
will add 10 to the list, which makes myList = [1,4,6,8,10].<br />
<br />
===All Kinds Of Lists===<br />
<br />
Lists don't have to be only integers!<br />
<br />
myList = [1,"Hi","Hello world", 3.5, 3.14159265358979323]<br />
<br />
If fact, there can be lists inside of lists!<br />
<br />
myList = [[1,2,3], [3,4,5], [5,6,"Hello world"], "BOB", 3.1415926]<br />
<br />
Even this!<br />
<br />
myList = [[1, [1, [1,2,3],3],3], [[[3,["Hello world", 4],5],4,5],4,5], [5,6,7,[1,[1,2,3],3],"Hello world"], "BOB", 3.1415926, True]<br />
<br />
If you look at that list carefully, you will find lists inside of lists inside of lists inside of lists! And, a boolean at the end!<br />
<br />
Like variables, you can have as many lists in a program as you want (a list is a variable)!<br />
<br />
myList = [1,2,3,4]<br />
yourList = [5,6,7,8]<br />
hisList = [9,10,11,12]<br />
herList = [13,14,15,16]<br />
theirList = [17,18,19,20]<br />
ourList = [21,22,23,24]<br />
listsOfLists = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20],[21,22,23,24]]<br />
<br />
==Dictionaries==<br />
<br />
A dictionary (a type of datatype) is a bunch of keys and values. There is a major difference between dictionaries and lists. Lists are ordered; dictionaries are not.<br />
<br />
Here is the '''syntax''' of creating a dictionary:<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
<br />
This dictionary has two key/value pairs. Notice it is surrounded in curly braces. The keys are 1 and 2; the values are "one" and "two."<br />
<br />
How is this useful? Let's make a simple program to test it out.<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
print(myDictionary[1])<br />
print(myDictionary[2])<br />
<br />
===Accessing Values===<br />
<br />
To access a value in a dictionary, you put in the key.<br />
<br />
myDictionary[1]<br />
<br />
returns one, because 1 is the key to "one."<br />
<br />
===Adding New Values===<br />
<br />
To overwrite a value, we do this.<br />
<br />
myDictionary[1] = "won"<br />
<br />
The value to the key 1 is now "won."<br />
<br />
To add a value, we do the same thing!<br />
<br />
myDictionary[3] = "three"<br />
<br />
This adds a key 3 with a value of "three."<br />
<br />
==Challenge Program==<br />
<br />
In this section, we will attempt the hardest program so far in this article.<br />
<br />
'''Make a conversation generator that will generate random conversations between different people.'''<br />
<br />
First, we will generate the people. We can use a list and generate two random numbers.<br />
<br />
import random<br />
peopleNames = ["Bob", "Kyle", "James", "Richard", "Zachary", "Olivia", "Jonathan", "Will", "Bobby", "Kevin"]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
Here, we use the remove() function to remove person1 from the list to make sure we don't use the same name twice. <br />
<br />
We also used the len() function to find the length of the list (soft-coding!)<br />
<br />
Now, we need to create a list of possible values for the first thing that person1 says (person1 will always be the first one to talk). Then, we will print it out.<br />
<br />
import random<br />
<br />
peopleNames = ["Bob", "Kyle", "James", "Richard", "Zachary", "Olivia", "Jonathan", "Will", "Bobby", "Kevin"]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = ["Hi!", "Hello!", "Good morning!", "Hello, " + person2 + "!", "Hi.", "Hi, " + person2 + "!"]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
<br />
If we test out this program, we can confirm that this part indeed does work. This program is already getting long! Now, we will use the same method and create the second message.<br />
<br />
import random<br />
<br />
peopleNames = ["Bob", "Kyle", "James", "Richard", "Zachary", "Olivia", "Jonathan", "Will", "Bobby", "Kevin"]<br />
person1 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
peopleNames.remove(person1)<br />
person2 = peopleNames[random.randint(0, (len(peopleNames) - 1))]<br />
<br />
first = ["Hi!", "Hello!", "Good morning!", "Hello, " + person2 + "!", "Hi.", "Hi, " + person2 + "!"]<br />
print(person1 + ": " + first[random.randint(0, (len(first) - 1))])<br />
second = ["Hi! How are you today?", "Hello! How are you?", "Good morning! How are you today?", "Hello, " + person2 + "! How are you?", <br />
"Hi. How are you?", "Hi, " + person2 + "! How are you today?"]<br />
print(person2 + ": " + second[random.randint(0, (len(second) - 1))])<br />
<br />
We will repeat this for the rest of the conversation:<br />
<br />
This is an unfinished article.</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93249
Basic Programming With Python
2018-03-14T21:55:59Z
<p>Bestaops: /* Adding New Values */ added section header</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
(Note: This is a really long article. To learn the most from this article, you need to read everything in order and skip nothing, unless you are '''absolutely absolutely sure that that content is way to easy for you.''')<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
Note that this article has lots of program examples. It is recommended (but not required) to try these on your own before looking at the solutions.<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
for i in range(1,51):<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
<br />
We must not forget to print the total at the end!<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
print(total)<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
i = 3<br />
total = 0<br />
while i < 1000:<br />
total += i<br />
i += 3<br />
print(total)<br />
<br />
In this code, the while loop loops 333 times, until <math>i</math> becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
n = 1<br />
total = 0<br />
while n <= 50:<br />
total += 2**n<br />
n += 1<br />
print(total)<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2)<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
def up_down_arrow(a,b):<br />
return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
return ((a * b * up_down_arrow(a,b)) ** 2)<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
def add_one(x):<br />
return x + 1<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
def add_one(x):<br />
return x + 1<br />
print(add_one(2))<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
def print_function(x):<br />
print(x)<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
def print_function(x):<br />
print(x)<br />
return<br />
print_function("print_function")<br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
if 10*5 > 9:<br />
if 10*5 < 100:<br />
print("Yes")<br />
else:<br />
print("No")<br />
else:<br />
print("No")<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
print("Yes") <br />
else:<br />
print("No")<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
for i in range(10,100):<br />
if check(i):<br />
print(i)<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
def check(a, min, max):<br />
if a*5 > min - 1 and a*5 < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999)<br />
<br />
(Note: This is all in one program. The boxes are separate because it is a relatively long program and I like to keep it organized.)<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
print_check(100, 999, 100, 999)<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
def check(a, min, max, factor):<br />
if a*factor > min - 1 and a*factor < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max, check_factor):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check() line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
import random<br />
print(random.randint(1,6))<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
import random<br />
count = 0<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
for i in range(1, 1001):<br />
if roll() == 6:<br />
count += 1<br />
<br />
print(count)<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
print(count(10000))<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
total += count(i)<br />
<br />
print(total)<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
def count2(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count(i)<br />
return total<br />
<br />
def count3(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count2(i)<br />
return total<br />
<br />
print(count3(20))<br />
<br />
(Our program is so long!)<br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while!<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is to soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!<br />
<br />
==Very Basic Datatypes==<br />
<br />
An integer is a basic datatype in Python. Basically, all variables with the datatype of '''int''' is an integer.<br />
<br />
A string is another basic datatype, and it is a string of characters enclosed by quotes.<br />
<br />
===Why Are Datatypes So Important?===<br />
<br />
Let's say we wanted to make a program that would add 2 and 3. Some bogus code would be:<br />
<br />
x="2"<br />
y="3"<br />
print(x+y)<br />
<br />
If you ran this code, you would get 23. Why is that?<br />
<br />
Well, here, x and y are strings. When you perform the addition operator to strings in Python, it concatenates the strings, giving 23.<br />
<br />
The real code is:<br />
<br />
x=2<br />
y=3<br />
print(x+y)<br />
<br />
If you run this, you will get <math>5</math>, which is correct.<br />
<br />
Here's another reason datatypes are important. Now, we will introduce the datatype called the '''floating point number''', or '''float'''. A floating point number is a number with a decimal point.<br />
<br />
Let's go back to the IDLE. Type "0.1*10". The result is 1.0. Notice the decimal point.<br />
<br />
Let's type something different. Type <math>0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1.</math><br />
<br />
'''WHAT!?'''<br />
<br />
You would have expected the answer to be 1, but it isn't 1. What happened?<br />
<br />
'''Float approximation''' happened. Most (almost all) programming languages have a bad float approximation. That means that 1.0 can turn into 0.99999999999999 and 0.5 can turn into 0.49999999999999999993. That only happens with floats, so we should try to use floats as sparingly as possible.<br />
<br />
==Lists==<br />
<br />
A for loop iterates over a '''list'''. A list is a bunch of objects stored in one variable. (Hey! A list is a datatype!) For loops are highly related to lists.<br />
<br />
Let's say we wanted to make a program to print all the items in a list.<br />
<br />
We will first create the list, using the code:<br />
<br />
myList = [1,4,6,8]<br />
<br />
This is a list with four items: 1, 4, 6, and 8.<br />
<br />
We must now print all elements of it with a for loop:<br />
<br />
myList = [1,4,6,8]<br />
for i in myList:<br />
print(i)<br />
<br />
When we run this program, we get the numbers 1, 4, 6, and 8, as expected.<br />
<br />
===Accessing Values===<br />
<br />
Let's say we wanted to print out the second item in a list. We will use '''indexes'''.<br />
<br />
The index of the first item in a list is always 0. The index of the second is 1. The index of the <math>n</math>th is <math>n-1.</math><br />
<br />
To print out the second item, we will use an index of 1, like this:<br />
<br />
myList = [1,4,6,8]<br />
print(myList[1])<br />
<br />
Notice that the index is inside of the square brackets.<br />
<br />
===Adding Values===<br />
<br />
We can use the list.append() function to add an object to the end of a list.<br />
<br />
myList.append(10)<br />
<br />
will add 10 to the list, which makes myList = [1,4,6,8,10].<br />
<br />
===All Kinds Of Lists===<br />
<br />
Lists don't have to be only integers!<br />
<br />
myList = [1,"Hi","Hello world", 3.5, 3.14159265358979323]<br />
<br />
If fact, there can be lists inside of lists!<br />
<br />
myList = [[1,2,3], [3,4,5], [5,6,"Hello world"], "BOB", 3.1415926]<br />
<br />
Even this!<br />
<br />
myList = [[1, [1, [1,2,3],3],3], [[[3,["Hello world", 4],5],4,5],4,5], [5,6,7,[1,[1,2,3],3],"Hello world"], "BOB", 3.1415926, True]<br />
<br />
If you look at that list carefully, you will find lists inside of lists inside of lists inside of lists! And, a boolean at the end!<br />
<br />
Like variables, you can have as many lists in a program as you want (a list is a variable)!<br />
<br />
myList = [1,2,3,4]<br />
yourList = [5,6,7,8]<br />
hisList = [9,10,11,12]<br />
herList = [13,14,15,16]<br />
theirList = [17,18,19,20]<br />
ourList = [21,22,23,24]<br />
listsOfLists = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20],[21,22,23,24]]<br />
<br />
==Dictionaries==<br />
<br />
A dictionary (a type of datatype) is a bunch of keys and values. There is a major difference between dictionaries and lists. Lists are ordered; dictionaries are not.<br />
<br />
Here is the '''syntax''' of creating a dictionary:<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
<br />
This dictionary has two key/value pairs. Notice it is surrounded in curly braces. The keys are 1 and 2; the values are "one" and "two."<br />
<br />
How is this useful? Let's make a simple program to test it out.<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
print(myDictionary[1])<br />
print(myDictionary[2])<br />
<br />
===Accessing Values===<br />
<br />
To access a value in a dictionary, you put in the key.<br />
<br />
myDictionary[1]<br />
<br />
returns one, because 1 is the key to "one."<br />
<br />
===Adding New Values===<br />
<br />
To overwrite a value, we do this.<br />
<br />
myDictionary[1] = "won"<br />
<br />
The value to the key 1 is now "won."<br />
<br />
To add a value, we do the same thing!<br />
<br />
myDictionary[3] = "three"<br />
<br />
This adds a key 3 with a value of "three."<br />
<br />
==Challenge Program==</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93248
Basic Programming With Python
2018-03-14T21:53:04Z
<p>Bestaops: added a warning</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
(Note: This is a really long article. To learn the most from this article, you need to read everything in order and skip nothing, unless you are '''absolutely absolutely sure that that content is way to easy for you.''')<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
Note that this article has lots of program examples. It is recommended (but not required) to try these on your own before looking at the solutions.<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
for i in range(1,51):<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
<br />
We must not forget to print the total at the end!<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
print(total)<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
i = 3<br />
total = 0<br />
while i < 1000:<br />
total += i<br />
i += 3<br />
print(total)<br />
<br />
In this code, the while loop loops 333 times, until <math>i</math> becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
n = 1<br />
total = 0<br />
while n <= 50:<br />
total += 2**n<br />
n += 1<br />
print(total)<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2)<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
def up_down_arrow(a,b):<br />
return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
return ((a * b * up_down_arrow(a,b)) ** 2)<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
def add_one(x):<br />
return x + 1<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
def add_one(x):<br />
return x + 1<br />
print(add_one(2))<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
def print_function(x):<br />
print(x)<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
def print_function(x):<br />
print(x)<br />
return<br />
print_function("print_function")<br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
if 10*5 > 9:<br />
if 10*5 < 100:<br />
print("Yes")<br />
else:<br />
print("No")<br />
else:<br />
print("No")<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
print("Yes") <br />
else:<br />
print("No")<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
for i in range(10,100):<br />
if check(i):<br />
print(i)<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
def check(a, min, max):<br />
if a*5 > min - 1 and a*5 < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999)<br />
<br />
(Note: This is all in one program. The boxes are separate because it is a relatively long program and I like to keep it organized.)<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
print_check(100, 999, 100, 999)<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
def check(a, min, max, factor):<br />
if a*factor > min - 1 and a*factor < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max, check_factor):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check() line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
import random<br />
print(random.randint(1,6))<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
import random<br />
count = 0<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
for i in range(1, 1001):<br />
if roll() == 6:<br />
count += 1<br />
<br />
print(count)<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
print(count(10000))<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
total += count(i)<br />
<br />
print(total)<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
def count2(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count(i)<br />
return total<br />
<br />
def count3(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count2(i)<br />
return total<br />
<br />
print(count3(20))<br />
<br />
(Our program is so long!)<br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while!<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is to soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!<br />
<br />
==Very Basic Datatypes==<br />
<br />
An integer is a basic datatype in Python. Basically, all variables with the datatype of '''int''' is an integer.<br />
<br />
A string is another basic datatype, and it is a string of characters enclosed by quotes.<br />
<br />
===Why Are Datatypes So Important?===<br />
<br />
Let's say we wanted to make a program that would add 2 and 3. Some bogus code would be:<br />
<br />
x="2"<br />
y="3"<br />
print(x+y)<br />
<br />
If you ran this code, you would get 23. Why is that?<br />
<br />
Well, here, x and y are strings. When you perform the addition operator to strings in Python, it concatenates the strings, giving 23.<br />
<br />
The real code is:<br />
<br />
x=2<br />
y=3<br />
print(x+y)<br />
<br />
If you run this, you will get <math>5</math>, which is correct.<br />
<br />
Here's another reason datatypes are important. Now, we will introduce the datatype called the '''floating point number''', or '''float'''. A floating point number is a number with a decimal point.<br />
<br />
Let's go back to the IDLE. Type "0.1*10". The result is 1.0. Notice the decimal point.<br />
<br />
Let's type something different. Type <math>0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1.</math><br />
<br />
'''WHAT!?'''<br />
<br />
You would have expected the answer to be 1, but it isn't 1. What happened?<br />
<br />
'''Float approximation''' happened. Most (almost all) programming languages have a bad float approximation. That means that 1.0 can turn into 0.99999999999999 and 0.5 can turn into 0.49999999999999999993. That only happens with floats, so we should try to use floats as sparingly as possible.<br />
<br />
==Lists==<br />
<br />
A for loop iterates over a '''list'''. A list is a bunch of objects stored in one variable. (Hey! A list is a datatype!) For loops are highly related to lists.<br />
<br />
Let's say we wanted to make a program to print all the items in a list.<br />
<br />
We will first create the list, using the code:<br />
<br />
myList = [1,4,6,8]<br />
<br />
This is a list with four items: 1, 4, 6, and 8.<br />
<br />
We must now print all elements of it with a for loop:<br />
<br />
myList = [1,4,6,8]<br />
for i in myList:<br />
print(i)<br />
<br />
When we run this program, we get the numbers 1, 4, 6, and 8, as expected.<br />
<br />
===Accessing Values===<br />
<br />
Let's say we wanted to print out the second item in a list. We will use '''indexes'''.<br />
<br />
The index of the first item in a list is always 0. The index of the second is 1. The index of the <math>n</math>th is <math>n-1.</math><br />
<br />
To print out the second item, we will use an index of 1, like this:<br />
<br />
myList = [1,4,6,8]<br />
print(myList[1])<br />
<br />
Notice that the index is inside of the square brackets.<br />
<br />
===Adding Values===<br />
<br />
We can use the list.append() function to add an object to the end of a list.<br />
<br />
myList.append(10)<br />
<br />
will add 10 to the list, which makes myList = [1,4,6,8,10].<br />
<br />
===All Kinds Of Lists===<br />
<br />
Lists don't have to be only integers!<br />
<br />
myList = [1,"Hi","Hello world", 3.5, 3.14159265358979323]<br />
<br />
If fact, there can be lists inside of lists!<br />
<br />
myList = [[1,2,3], [3,4,5], [5,6,"Hello world"], "BOB", 3.1415926]<br />
<br />
Even this!<br />
<br />
myList = [[1, [1, [1,2,3],3],3], [[[3,["Hello world", 4],5],4,5],4,5], [5,6,7,[1,[1,2,3],3],"Hello world"], "BOB", 3.1415926, True]<br />
<br />
If you look at that list carefully, you will find lists inside of lists inside of lists inside of lists! And, a boolean at the end!<br />
<br />
Like variables, you can have as many lists in a program as you want (a list is a variable)!<br />
<br />
myList = [1,2,3,4]<br />
yourList = [5,6,7,8]<br />
hisList = [9,10,11,12]<br />
herList = [13,14,15,16]<br />
theirList = [17,18,19,20]<br />
ourList = [21,22,23,24]<br />
listsOfLists = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20],[21,22,23,24]]<br />
<br />
==Dictionaries==<br />
<br />
A dictionary (a type of datatype) is a bunch of keys and values. There is a major difference between dictionaries and lists. Lists are ordered; dictionaries are not.<br />
<br />
Here is the '''syntax''' of creating a dictionary:<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
<br />
This dictionary has two key/value pairs. Notice it is surrounded in curly braces. The keys are 1 and 2; the values are "one" and "two."<br />
<br />
How is this useful? Let's make a simple program to test it out.<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
print(myDictionary[1])<br />
print(myDictionary[2])<br />
<br />
===Accessing Values===<br />
<br />
To access a value in a dictionary, you put in the key.<br />
<br />
myDictionary[1]<br />
<br />
returns one, because 1 is the key to "one."<br />
<br />
===Adding New Values===<br />
<br />
To overwrite a value, we do this.<br />
<br />
myDictionary[1] = "won"<br />
<br />
The value to the key 1 is now "won."<br />
<br />
To add a value, we do the same thing!<br />
<br />
myDictionary[3] = "three"<br />
<br />
This adds a key 3 with a value of "three."</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93247
Basic Programming With Python
2018-03-14T21:51:06Z
<p>Bestaops: fixed code bugs</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
Note that this article has lots of program examples. It is recommended (but not required) to try these on your own before looking at the solutions.<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
for i in range(1,51):<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
<br />
We must not forget to print the total at the end!<br />
<br />
total = 0<br />
for i in range(1,51):<br />
total += 2**i<br />
print(total)<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
i = 3<br />
total = 0<br />
while i < 1000:<br />
total += i<br />
i += 3<br />
print(total)<br />
<br />
In this code, the while loop loops 333 times, until <math>i</math> becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
n = 1<br />
total = 0<br />
while n <= 50:<br />
total += 2**n<br />
n += 1<br />
print(total)<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
def up_down_arrow(a,b): <br />
return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2)<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
def up_down_arrow(a,b):<br />
return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
return ((a * b * up_down_arrow(a,b)) ** 2)<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
def add_one(x):<br />
return x + 1<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
def add_one(x):<br />
return x + 1<br />
print(add_one(2))<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
def print_function(x):<br />
print(x)<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
def print_function(x):<br />
print(x)<br />
return<br />
print_function("print_function")<br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
if 10*5 > 9:<br />
if 10*5 < 100:<br />
print("Yes")<br />
else:<br />
print("No")<br />
else:<br />
print("No")<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
print("Yes") <br />
else:<br />
print("No")<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
def check(a):<br />
if a*5 > 9 and a*5 < 100:<br />
return True <br />
else:<br />
return False<br />
for i in range(10,100):<br />
if check(i):<br />
print(i)<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
def check(a, min, max):<br />
if a*5 > min - 1 and a*5 < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999)<br />
<br />
(Note: This is all in one program. The boxes are separate because it is a relatively long program and I like to keep it organized.)<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
print_check(100, 999, 100, 999)<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
def check(a, min, max, factor):<br />
if a*factor > min - 1 and a*factor < max + 1:<br />
return True <br />
else:<br />
return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
for i in range(range_min, range_max + 1):<br />
if check(i, check_min, check_max, check_factor):<br />
print(i)<br />
return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check() line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
import random<br />
print(random.randint(1,6))<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
import random<br />
count = 0<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
for i in range(1, 1001):<br />
if roll() == 6:<br />
count += 1<br />
<br />
print(count)<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
print(count(10000))<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
total += count(i)<br />
<br />
print(total)<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
import random<br />
<br />
def roll():<br />
return random.randint(1,6)<br />
<br />
def count(amount):<br />
count_ = 0<br />
for i in range(1, amount+1):<br />
if roll() == 3:<br />
count_ += 1<br />
return count_<br />
<br />
def count2(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count(i)<br />
return total<br />
<br />
def count3(amount)<br />
total = 0<br />
for i in range(1, amount + 1):<br />
total += count2(i)<br />
return total<br />
<br />
print(count3(20))<br />
<br />
(Our program is so long!)<br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while!<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is to soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!<br />
<br />
==Very Basic Datatypes==<br />
<br />
An integer is a basic datatype in Python. Basically, all variables with the datatype of '''int''' is an integer.<br />
<br />
A string is another basic datatype, and it is a string of characters enclosed by quotes.<br />
<br />
===Why Are Datatypes So Important?===<br />
<br />
Let's say we wanted to make a program that would add 2 and 3. Some bogus code would be:<br />
<br />
x="2"<br />
y="3"<br />
print(x+y)<br />
<br />
If you ran this code, you would get 23. Why is that?<br />
<br />
Well, here, x and y are strings. When you perform the addition operator to strings in Python, it concatenates the strings, giving 23.<br />
<br />
The real code is:<br />
<br />
x=2<br />
y=3<br />
print(x+y)<br />
<br />
If you run this, you will get <math>5</math>, which is correct.<br />
<br />
Here's another reason datatypes are important. Now, we will introduce the datatype called the '''floating point number''', or '''float'''. A floating point number is a number with a decimal point.<br />
<br />
Let's go back to the IDLE. Type "0.1*10". The result is 1.0. Notice the decimal point.<br />
<br />
Let's type something different. Type <math>0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1.</math><br />
<br />
'''WHAT!?'''<br />
<br />
You would have expected the answer to be 1, but it isn't 1. What happened?<br />
<br />
'''Float approximation''' happened. Most (almost all) programming languages have a bad float approximation. That means that 1.0 can turn into 0.99999999999999 and 0.5 can turn into 0.49999999999999999993. That only happens with floats, so we should try to use floats as sparingly as possible.<br />
<br />
==Lists==<br />
<br />
A for loop iterates over a '''list'''. A list is a bunch of objects stored in one variable. (Hey! A list is a datatype!) For loops are highly related to lists.<br />
<br />
Let's say we wanted to make a program to print all the items in a list.<br />
<br />
We will first create the list, using the code:<br />
<br />
myList = [1,4,6,8]<br />
<br />
This is a list with four items: 1, 4, 6, and 8.<br />
<br />
We must now print all elements of it with a for loop:<br />
<br />
myList = [1,4,6,8]<br />
for i in myList:<br />
print(i)<br />
<br />
When we run this program, we get the numbers 1, 4, 6, and 8, as expected.<br />
<br />
===Accessing Values===<br />
<br />
Let's say we wanted to print out the second item in a list. We will use '''indexes'''.<br />
<br />
The index of the first item in a list is always 0. The index of the second is 1. The index of the <math>n</math>th is <math>n-1.</math><br />
<br />
To print out the second item, we will use an index of 1, like this:<br />
<br />
myList = [1,4,6,8]<br />
print(myList[1])<br />
<br />
Notice that the index is inside of the square brackets.<br />
<br />
===Adding Values===<br />
<br />
We can use the list.append() function to add an object to the end of a list.<br />
<br />
myList.append(10)<br />
<br />
will add 10 to the list, which makes myList = [1,4,6,8,10].<br />
<br />
===All Kinds Of Lists===<br />
<br />
Lists don't have to be only integers!<br />
<br />
myList = [1,"Hi","Hello world", 3.5, 3.14159265358979323]<br />
<br />
If fact, there can be lists inside of lists!<br />
<br />
myList = [[1,2,3], [3,4,5], [5,6,"Hello world"], "BOB", 3.1415926]<br />
<br />
Even this!<br />
<br />
myList = [[1, [1, [1,2,3],3],3], [[[3,["Hello world", 4],5],4,5],4,5], [5,6,7,[1,[1,2,3],3],"Hello world"], "BOB", 3.1415926, True]<br />
<br />
If you look at that list carefully, you will find lists inside of lists inside of lists inside of lists! And, a boolean at the end!<br />
<br />
Like variables, you can have as many lists in a program as you want (a list is a variable)!<br />
<br />
myList = [1,2,3,4]<br />
yourList = [5,6,7,8]<br />
hisList = [9,10,11,12]<br />
herList = [13,14,15,16]<br />
theirList = [17,18,19,20]<br />
ourList = [21,22,23,24]<br />
listsOfLists = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20],[21,22,23,24]]<br />
<br />
==Dictionaries==<br />
<br />
A dictionary (a type of datatype) is a bunch of keys and values. There is a major difference between dictionaries and lists. Lists are ordered; dictionaries are not.<br />
<br />
Here is the '''syntax''' of creating a dictionary:<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
<br />
This dictionary has two key/value pairs. Notice it is surrounded in curly braces. The keys are 1 and 2; the values are "one" and "two."<br />
<br />
How is this useful? Let's make a simple program to test it out.<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
print(myDictionary[1])<br />
print(myDictionary[2])<br />
<br />
===Accessing Values===<br />
<br />
To access a value in a dictionary, you put in the key.<br />
<br />
myDictionary[1]<br />
<br />
returns one, because 1 is the key to "one."<br />
<br />
===Adding New Values===<br />
<br />
To overwrite a value, we do this.<br />
<br />
myDictionary[1] = "won"<br />
<br />
The value to the key 1 is now "won."<br />
<br />
To add a value, we do the same thing!<br />
<br />
myDictionary[3] = "three"<br />
<br />
This adds a key 3 with a value of "three."</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93246
Basic Programming With Python
2018-03-14T21:36:15Z
<p>Bestaops: /* Lists */ and Dictionaries</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
Note that this article has lots of program examples. It is recommended (but not required) to try these on your own before looking at the solutions.<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
count = 0<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
print(count(10000))<br />
</code><br />
<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
:total += count(i)<br />
<br />
print(total)<br />
</code><br />
<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
def count2(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count(i)<br />
:return total<br />
<br />
def count3(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count2(i)<br />
:return total<br />
<br />
print(count3(20))<br />
</code><br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while!<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is to soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!<br />
<br />
==Very Basic Datatypes==<br />
<br />
An integer is a basic datatype in Python. Basically, all variables with the datatype of '''int''' is an integer.<br />
<br />
A string is another basic datatype, and it is a string of characters enclosed by quotes.<br />
<br />
===Why Are Datatypes So Important?===<br />
<br />
Let's say we wanted to make a program that would add 2 and 3. Some bogus code would be:<br />
<br />
<br />
<code><br />
<br />
x="2"<br />
<br />
y="3"<br />
<br />
print(x+y)<br />
</code><br />
<br />
<br />
If you ran this code, you would get 23. Why is that?<br />
<br />
Well, here, x and y are strings. When you perform the addition operator to strings in Python, it concatenates the strings, giving 23.<br />
<br />
The real code is:<br />
<br />
<br />
<code><br />
<br />
x=2<br />
<br />
y=3<br />
<br />
print(x+y)<br />
</code><br />
<br />
<br />
If you run this, you will get 5, which is correct.<br />
<br />
Here's another reason datatypes are important. Now, we will introduce the datatype called the '''floating point number''', or '''float'''. A floating point number is a number with a decimal point.<br />
<br />
Let's go back to the IDLE. Type "0.1*10". The result is 1.0. Notice the decimal point.<br />
<br />
Let's type something different. Type <math>0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1.</math><br />
<br />
'''WHAT!?'''<br />
<br />
You would have expected the answer to be 1, but it isn't 1. What happened?<br />
<br />
'''Float approximation''' happened. Most (almost all) programming languages have a bad float approximation. That means that 1.0 can turn into 0.99999999999999 and 0.5 can turn into 0.49999999999999999993. That only happens with floats, so we should try to use floats as sparingly as possible.<br />
<br />
==Lists==<br />
<br />
A for loop iterates over a '''list'''. A list is a bunch of objects stored in one variable. (Hey! A list is a datatype!) For loops are highly related to lists.<br />
<br />
Let's say we wanted to make a program to print all the items in a list.<br />
<br />
We will first create the list, using the code:<br />
<br />
myList = [1,4,6,8]<br />
<br />
This is a list with four items: 1, 4, 6, and 8.<br />
<br />
We must now print all elements of it with a for loop:<br />
<br />
myList = [1,4,6,8]<br />
for i in myList:<br />
print(i)<br />
<br />
When we run this program, we get the numbers 1, 4, 6, and 8, as expected.<br />
<br />
===Accessing Values===<br />
<br />
Let's say we wanted to print out the second item in a list. We will use '''indexes'''.<br />
<br />
The index of the first item in a list is always 0. The index of the second is 1. The index of the <math>n</math>th is <math>n-1.</math><br />
<br />
To print out the second item, we will use an index of 1, like this:<br />
<br />
myList = [1,4,6,8]<br />
print(myList[1])<br />
<br />
Notice that the index is inside of the square brackets.<br />
<br />
===Adding Values===<br />
<br />
We can use the list.append() function to add an object to the end of a list.<br />
<br />
myList.append(10)<br />
<br />
will add 10 to the list, which makes myList = [1,4,6,8,10].<br />
<br />
===All Kinds Of Lists===<br />
<br />
Lists don't have to be only integers!<br />
<br />
myList = [1,"Hi","Hello world", 3.5, 3.14159265358979323]<br />
<br />
If fact, there can be lists inside of lists!<br />
<br />
myList = [[1,2,3], [3,4,5], [5,6,"Hello world"], "BOB", 3.1415926]<br />
<br />
Even this!<br />
<br />
myList = [[1, [1, [1,2,3],3],3], [[[3,["Hello world", 4],5],4,5],4,5], [5,6,7,[1,[1,2,3],3],"Hello world"], "BOB", 3.1415926, True]<br />
<br />
If you look at that list carefully, you will find lists inside of lists inside of lists inside of lists! And, a boolean at the end!<br />
<br />
Like variables, you can have as many lists in a program as you want (a list is a variable)!<br />
<br />
myList = [1,2,3,4]<br />
yourList = [5,6,7,8]<br />
hisList = [9,10,11,12]<br />
herList = [13,14,15,16]<br />
theirList = [17,18,19,20]<br />
ourList = [21,22,23,24]<br />
listsOfLists = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20],[21,22,23,24]]<br />
<br />
==Dictionaries==<br />
<br />
A dictionary (a type of datatype) is a bunch of keys and values. There is a major difference between dictionaries and lists. Lists are ordered; dictionaries are not.<br />
<br />
Here is the '''syntax''' of creating a dictionary:<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
<br />
This dictionary has two key/value pairs. Notice it is surrounded in curly braces. The keys are 1 and 2; the values are "one" and "two."<br />
<br />
How is this useful? Let's make a simple program to test it out.<br />
<br />
myDictionary = {1:"one",2:"two"}<br />
print(myDictionary[1])<br />
print(myDictionary[2])<br />
<br />
===Accessing Values===<br />
<br />
To access a value in a dictionary, you put in the key.<br />
<br />
myDictionary[1]<br />
<br />
returns one, because 1 is the key to "one."<br />
<br />
===Adding New Values===<br />
<br />
To overwrite a value, we do this.<br />
<br />
myDictionary[1] = "won"<br />
<br />
The value to the key 1 is now "won."<br />
<br />
To add a value, we do the same thing!<br />
<br />
myDictionary[3] = "three"<br />
<br />
This adds a key 3 with a value of "three."</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Gmaas&diff=93245
Gmaas
2018-03-14T21:21:29Z
<p>Bestaops: /* Gmaas Jokes */</p>
<hr />
<div>=== Gmaas Jokes ===<br />
- Gmaas knows these digits of pi from memory: 3.1415926535897932384626433.<br />
<br />
- I am Gmaas<br />
<br />
-Gmaas is the only cat that has been proven transcendental.<br />
<br />
- Gmaas happened to notice http://artofproblemsolving.com/community/c402403h1598015p9983782 and is not very happy about it.<br />
<br />
- The real reason why AIME cutoffs aren't out yet is because Gmaas refused to grade them due to too much problem misplacement.<br />
<br />
-Gmaas dueled Grumpy Cat and lost<br />
<br />
-gmaas sits on the statue of pallas and says forevermore(the Raven refrence )<br />
<br />
- Gmaas does merely not use USD. He owns it.<br />
<br />
-Gmaas really knows that roblox is awful and does not play it seriously, thank god our lord is sane<br />
<br />
-In 2003, Gmaas used elliptical curves to force his reign over AoPS.<br />
<br />
-"Actually, my name is spelled GMAAS"<br />
<br />
- Gmaas is the smartest living being in the universe.<br />
<br />
-It was Gmaas who helped Monkey King on the Journey to the West.<br />
<br />
-Gmaas is the real creator of Wikipedia.<br />
<br />
-Gmaas is the basis of Greek mythology<br />
<br />
-Gmaas once sold Google to a man for around <math>12.<br />
<br />
-Gmaas uses a HP printer.<br />
<br />
-Gmass owns all AoPS staff including Richard Rusczyk<br />
<br />
- Gmass's true number of lives left is unknown; however, Gmass recently confirmed that he had at least one left. Why doesn't Gmass have so many more lives than other cats? The power of Gmass.<br />
<br />
- sseraj once spelled gmaas as gmass on accident in Introduction to Geometry (1532).<br />
<br />
-Gmaas actively plays Roblox, and is a globally ranked professional gamer: https://www.roblox.com/users/29708533/profile...but he hates Roblox.<br />
<br />
-Gmaas has beaten Chuck Norris and The Rock and John Cena all together in a fight.<br />
<br />
-Gmass is a South Korean, North Korean, Palestinian, Israeli, U.S., and Soviet citizen at the same time. EDIT: Gmaas has now been found out to be a citizen of every country in the world. Gmaas seems to enjoy the country of AOPS best, however.<br />
<br />
-"i am sand" destroyed Gmass in FTW<br />
<br />
- sseraj posted a picture of gmaas with a game controller in Introduction to Geometry (1532).<br />
<br />
-Gmaas plays roblox mobile edition and likes Minecraft, Candy Crush, and Club Penguin Rewritten<br />
<br />
-Gmaas is Roy Moore's horse in the shape of a cat<br />
<br />
-Gmaas is a known roblox/club penguin rewritten player and is a legend at it. He has over </math>289547987693<math> robux and </math>190348<math> in CPR.<br />
<br />
-This is all hypothetical EDIT: This is all factual <br />
<br />
-Gmass's real name is Princess. He has a sibling named Rusty/Fireheart/Firestar<br />
(Warrior cats reference)<br />
<br />
- He is capable of salmon powers, according to PunSpark (ask him)<br />
<br />
The Gmaas told Richard Rusczyk to make AoPS<br />
<br />
-The Gmaas is everything. Yes, you are part of the Gmaas-Dw789<br />
<br />
-The Gmaas knows every dimension up to 9999999999999999999999999999999999999999999999999th dimension<br />
<br />
-Certain theories provide evidence that he IS darth plagueis the wise<br />
<br />
-Gmaas is "TIRED OF PEOPLE ADDING TO HIS PAGE!!" (Maas 45).<br />
<br />
-Gmaas has multiple accounts; some of them are pifinity, Lord_Baltimore, Spacehead1AU, squareman, Electro3.0, and lakecomo224<br />
<br />
-Gmaas has a penguin servant named sm24136 who runs GMAASINC. The penguin may or may not be dead. <br />
<br />
-Gmass owns a TARDIS, and can sometimes be seen traveling to other times for reasons unknown.<br />
<br />
- knows how to hack into top secret ops community pages<br />
<br />
- Gmaas is king of the first men, the anduls<br />
<br />
-Gmass is a well known professor at MEOWston Academy<br />
<br />
-Gmass is a Tuna addict, along with other, more potent fish such as Salmon and Trout<br />
<br />
- Gmass won the reward of being cutest and fattest cat ever--he surpassed grumpy cat (He also out grumpied grumpy cat!!!)<br />
<br />
-Last sighting 1571-stretch-algebra-a 12/6/17<br />
<br />
- owner of sseraj, not pet<br />
<br />
- embodiment of life and universe and beyond <br />
<br />
- Watches memes<br />
<br />
-After Death became the GOD OF HYPERDEATH and obtained over 9000 souls <br />
<br />
-Gmass's real name is Pablo Diego JosÃ© Francisco de Paula Juan Nepomuceno MarÃa de los Remedios Cipriano de la SantÃsima Trinidad Ruiz y Picasso [STOP RICK ROLLING. (Source)]<br />
<br />
-Gmass is a certified Slytherin and probably the cutest cat ever.<br />
<br />
-Gmaas once slept on sseraj's private water bed, so sseraj locked him in the bathroom <br />
<br />
-Gmaas has superpowers that allow him to overcome the horrors of Mr. Toilet (while he was locked in the bathroom)<br />
<br />
- Gmaas once sat on an orange on a pile of AoPS books, causing an orange flavored equation explosion.<br />
<br />
-Gmaas once conquered the moon and imprinted his face on it until asteroids came.<br />
<br />
-Gmaas is a supreme overlord who must be given </math>10^{1000000000000000000000^{1000000000000000000000}}<math> minecraft DIAMONDS<br />
<br />
- gmaas is the Doctor Who lord; he sports Dalek-painted cars and eats human finger cheese and custard, plus black holes.<br />
<br />
- Gmaas is 5space's favorite animal. <br />
<br />
- He lives with sseraj. <br />
<br />
-Gmaas is my favorite pokemon<br />
<br />
-Gmaas dislikes number theory but enjoys geometry.<br />
<br />
- Gmaas is cool<br />
<br />
- He is often overfed (with probability </math>\frac{3972}{7891}<math>), or malnourished (with probability </math>\frac{3919}{7891}<math>) by sseraj.<br />
<br />
- He has <cmath>\sum_{k=1}^{267795} [k(k+1)]+GMAAS+GMAAAAAAAS</cmath> supercars, excluding the Purrari and the 138838383 Teslas. <br />
<br />
- He is an employee of AoPS.<br />
<br />
- He is a gmaas with yellow fur and white hypnotizing eyes.<br />
<br />
- He was born with a tail that is a completely different color from the rest of his fur.<br />
<br />
- His stare is very hypnotizing and effective at getting table scraps.<br />
<br />
- He sometimes appears several minutes before certain classes start as an admin. <br />
<br />
- He died from too many Rubik's cubes in an Introduction to Algebra A class, but got revived by the Dark Lord at 00:13:37 AM the next day.<br />
<br />
- It is uncertain whether or not he is a cat, or is merely some sort of beast that has chosen to take the form of a cat (specifically a Persian Smoke.) <br />
<br />
- Actually, he is a cat. He said so. And science also says so.<br />
<br />
- He is distant relative of Mathcat1234.<br />
<br />
- He is very famous now, and mods always talk about him before class starts.<br />
<br />
- His favorite food is AoPS textbooks because they help him digest problems.<br />
<br />
- Gmaas tends to reside in sseraj's fridge.<br />
<br />
- Gmaas once ate all sseraj's fridge food, so sseraj had to put him in the freezer.<br />
<br />
- The fur of Gmaas can protect him from the harsh conditions of a freezer.<br />
<br />
- Gmaas sightings are not very common. There have only been 8 confirmed sightings of Gmaas in the wild.<br />
<br />
- Gmaas is a sage omniscient cat.<br />
<br />
- He is looking for suitable places other than sseraj's fridge to live in.<br />
<br />
- Places where gmaas sightings have happened: <br />
~The Royal Scoop ice cream store in Bonita Beach Florida<br />
<br />
~MouseFeastForCats/CAT 8 Mouse Apartment 1083<br />
<br />
~Alligator Swamp A 1072 <br />
<br />
~Alligator Swamp B 1073<br />
<br />
~Prealgebra A (1488)<br />
<br />
~Introduction to Algebra A (1170)<br />
<br />
~Introduction to Algebra B (1529)<br />
<br />
~Welcome to Panda Town Gate 1076<br />
<br />
~Welcome to Gmaas Town Gate 1221<br />
<br />
~Welcome to Gmaas Town Gate 1125<br />
<br />
~33Â°01'17.4"N 117Â°05'40.1"W (Rancho Bernardo Road, San Diego, CA)<br />
<br />
~The other side of the ice in Antarctica<br />
<br />
~Feisty Alligator Swamp 1115<br />
<br />
~Introduction to Geometry 1221 (Taught by sseraj)<br />
<br />
~Introduction to Counting and Probability 1142 <br />
<br />
~Feisty-ish Alligator Swamp 1115 (AGAIN)<br />
<br />
~Intermediate Counting and Probability 1137<br />
<br />
~Intermediate Counting and Probability 1207<br />
<br />
~Posting student surveys<br />
<br />
~USF Castle Walls - Elven Tribe 1203<br />
<br />
~Dark Lord's Hut 1210<br />
<br />
~AMC 10 Problem Series 1200<br />
<br />
~Intermediate Number Theory 1138<br />
<br />
~Intermediate Number Theory 1476<br />
<br />
~Introduction To Number Theory 1204. Date:7/27/16.<br />
<br />
~Algebra B 1112<br />
<br />
~Intermediate Algebra 1561 7:17 PM 12/11/16<br />
<br />
~Nowhere Else, Tasmania<br />
<br />
~Earth Dimension C-137<br />
<br />
<br />
<br />
- These have all been designated as the most glorious sections of Aopsland now (especially the USF castle walls), but deforestation is so far from threatens the wild areas (i.e. Alligator Swamps A&B).<br />
<br />
- Gmaas has also been sighted in Olympiad Geometry 1148.<br />
<br />
- Gmaas has randomly been known to have sent his minions into Prealgebra 2 1163. However, the danger is passed, that class is over.<br />
<br />
- Gmaas once snuck into sseraj's email so he could give pianoman24 an extension in Introduction to Number Theory 1204. This was 1204 minutes after his sighting on 7/27/16.<br />
<br />
- Gmaas also has randomly appeared on top of the USF's Tribal Bases(he seems to prefer the Void Tribe). However, the next day there is normally a puddle in the shape of a cat's underbelly wherever he was sighted. Nobody knows what this does. <br />
<br />
EDIT: Nobody has yet seen him atop a tribal base yet.<br />
<br />
- Gmaas are often under the disguise of a penguin or cat. Look out for them.<br />
<br />
EDIT: Gmaas rarely disguises himself as a penguin.<br />
<br />
- He lives in the shadows. Is he a dream? Truth? Fiction? Condemnation? Salvation? AoPS site admin? He is all these things and none of them. He is... Gmaas.<br />
<br />
EDIT: He IS an AoPS site admin.<br />
<br />
- If you make yourself more than just a cat... if you devote yourself to an ideal... and if they can't stop you... then you become something else entirely. A LEGEND. Gmaas now belongs to the ages.<br />
<br />
- Is this the real life? Is this just fantasy? No. This is Gmaas, the legend.<br />
<br />
-Aha!! An impostor!! <br />
http://www.salford.ac.uk/environment-life-sciences/research/applied-archaeology/greater-manchester-archaeological-advisory-service<br />
(look at the acronym).<br />
<br />
-EDIT. The above fact is slightly irrelevant.<br />
<br />
- Gmaas might have been viewing (with a </math>\frac{99999.\overline{9}}{100000}<math> chance) the Ultimate Survival Forum. He (or is he a she?) is suspected to be transforming the characters into real life. Be prepared to meet your epic swordsman self someday. If you do a sci-fi version of USF, then prepare to meet your Overpowered soldier with amazing weapons one day.<br />
<br />
- EDIT: Gmaas is a he.<br />
<br />
-Gmaas is love, Gmaas is life<br />
<br />
- The name of Gmaas is so powerful, it radiates Deja Mew.<br />
<br />
- Gmaas is on the list of "Elusive Creatures." If you have questions or want the full list, contact moab33.<br />
<br />
- Gmaas can be summoned using the </math>\tan(90)<math> ritual. Draw a pentagram and write the numerical value of </math>\tan(90)<math> in the middle, and he will be summoned.<br />
<br />
- EDIT: The above fact is incorrect. math101010 has done this and commented with screenshot proof at the below link, and Gmaas was not summoned.<br />
https://artofproblemsolving.com/community/c287916h1291232<br />
<br />
- EDIT EDIT: The above 'proof' is non-conclusive. math101010 had only put an approximation.<br />
<br />
- Gmaas's left eye contains the singularity of a black hole. (Only when everyone in the world blinks at the same time within a nano-nano second.)<br />
<br />
- EDIT: That has never happened and thus it does not contain the singularity of a black hole. <br />
<br />
- Lord Grindelwald once tried to make Gmaas into a Horcrux, but Gmaas's fur is Elder Wand protected and secure, as Kendra sprinkled holly into his fur.<br />
<br />
-Despite common belief, Harry Potter did not defeat Lord Voldemort. Gmaas did.<br />
<br />
- The original owner of Gmaas is Gmaas.<br />
<br />
- Gmaas was not the fourth Peverell brother, but he ascended into a higher being and now he resides in the body of a cat, as he was before. Is it a cat? We will know. (And the answer is YES.)<br />
<br />
- It is suspected that Gmaas may be ordering his cyber hairballs to take the forums, along with microbots.<br />
<br />
- The name of Gmaas is so powerful, it radiates Deja Mu.<br />
<br />
- Gmaas rarely frequents the headquarters of the Illuminati. He was their symbol for one yoctosecond, but soon decided that the job was too low for his power to be wasted on.<br />
<br />
- It has been wondered if Gmaas is the spirit of Obi-Wan Kenobi or Anakin Skywalker in a higher form, due to his strange capabilities and powers.<br />
<br />
- Gmaas has a habit of sneaking into computers, joining The Network, and exiting out of some other computer.<br />
<br />
- It has been confirmed that gmaas uses gmewal as his email service<br />
<br />
- Gmaas enjoys wearing gmean shorts<br />
<br />
- Gmaas has a bright orange tail with hot pink spirals. Or he had for 15 minutes. <br />
<br />
- Gmaas is well known behind his stage name, Michael Stevens (also known as Vsauce XD), or his page name, Purrshanks.<br />
<br />
- Gmaas rekt sseraj at 12:54 June 4, 2016 UTC time zone. And then the Doctor chased him.<br />
<br />
- Gmaas watchers know that the codes above are NOT years. They are secret codes for the place. But if you've edited that section of the page, you know that.<br />
<br />
- Gmaas is a good friend of the TARDIS and the Millenium Falcon. <br />
<br />
- In the Dark Lord's hut, gmaas was seen watching Doctor Who. Anyone who has seem the Dark Lord's hut knows that both Gmaas and the DL (USF code name of the Dark Lord) love BBC. How Gmaas gave him a TV may be lost to history. And it has been lost.<br />
<br />
- The TV has been noticed to be invincible. Many USF weapons, even volcano rings, have tried (and failed) to destroy it. The last time it was seen was on a Kobold display case outside of a mine. The display case was crushed, and a report showed a spy running off with a non-crushed TV.<br />
<br />
-The reason why Dacammel left the USF is that gmaas entrusted his TV to him, and not wanting to be discovered by LF, Cobra, or Z9, dacammel chose to leave the USF, but is regretting it, as snakes keep spawning from the TV.<br />
<br />
- EDIT: The above fact is somewhat irrelevant.<br />
<br />
-EDIT EDIT. Dacammel gave the TV back to gmass, and he left the dark side and their cookies alone. <br />
<br />
- Gmaas is a Super Duper Uper Cat Time Lord. He has </math>57843504<math> regenerations and has used </math>3<math>. <cmath>9\cdot12\cdot2\cdot267794=57843504</cmath>. <br />
<br />
-Gmaas highly enjoys destroying squeaky toys until he finds the squeaky part, then destroys the squeaky part.<br />
<br />
- Gmaas loves to eat turnips. At </math>\frac{13}{32}<math> of the sites he was spotted at, he was seen with a turnip.<br />
<br />
-Gmaas has a secret hidden garden full of turnips under sseraj's house.<br />
<br />
- Gmaas has three tails, one for everyday life, one for special occasions, and one that's invisible.<br />
<br />
-Gmaas is a dangerous creature. If you ever meet him, immediately join his army or you will be killed.<br />
<br />
-Gmaas is in alliance with the Cult of Skaro. How did he get an alliance with ruthless creatures that want to kill everything in sight? Nobody knows. (Except him.)<br />
<br />
-Gmaas lives in Gallifrey and in Gotham City (he has sleepovers with Batman).<br />
<br />
-Gmaas is an excellent driver.<br />
<br />
-The native location of Gmaas is the twilight zone.<br />
<br />
-Donald Trump once sang "All Hail the Chief" to Gmaas, 3 days after being sworn in as US President.<br />
<br />
- Gmaas likes to talk with rrusczyk from time to time.<br />
<br />
- Gmaas can shoot fire from his paws.<br />
<br />
- Gmaas is the reason why the USF has the longest thread on AoPS.<br />
<br />
- He (or she) is an avid watcher of the popular T.V. show "Bernie Sanders and the Gauntlet of DOOM"<br />
<br />
- sseraj, in 1521 Introduction to Number Theory, posted an image of Gmaas after saying "Who wants to see 5space?" at around 5:16 PM Mountain Time, noting Gmaas was "also 5space"<br />
<br />
-EDIT: he also did it in Introduction to Algebra A once<br />
<br />
- Gmaas is now my HD background on my Mac.<br />
<br />
- In 1521 Into to Number Theory, sseraj posted an image of a 5space Gmaas fusion. (First sighting) <br />
<br />
- Also confirmed that Gmaas doesn't like ketchup because it was the only food left the photo.<br />
<br />
- In 1447 Intro to Geometry, sseraj posted a picture of Gmaas with a rubik's cube suggesting that Gmaas's has an average solve time of </math>-GMAAS<math> seconds.<br />
<br />
-Gmass beat Superman in a fight with ease<br />
<br />
-Gmass was an admin of Roblox<br />
<br />
-Gmass traveled around the world, paying so much </math>MONEY<math> just to eat :D<br />
<br />
-Gmaas is a confirmed Apex predator and should not be approached, unless in a domestic form.<br />
Summary:<br />
<br />
-When Gmaas subtracts </math>0.\overline{99}<math> from </math>1<math>, the difference is greater than </math>0$.<br />
<br />
-Gmaas was shown to have fallen on Wed Aug 23 2017: https://ibb.co/bNrtmk https://ibb.co/jzUDmk<br />
<br />
-Gmaas died on August ,24, 2017, but fortunately IceParrot revived him after about 2 mins of being dead.<br />
<br />
-The results of the revival are top secret, and nobody knows what happened.<br />
<br />
-sseraj, in 1496 Prealgebra 2, said that Gmaas is Santacat.<br />
<br />
-sseraj likes to post a picture of gmaas in every class he passes by.<br />
<br />
-sseraj posted a picture of gmaas as an Ewok, suggesting he resides on the moon of Endor. Unfortunately, the moon of Ender is also uninhabitable ever since the wreckage of the Death Star changed the climate there. It is thought gmass is now wandering space in search for a home.<br />
EDIT: What evidence is there Endor was affected? Other Ewoks still live there.<br />
<br />
-Gmaas is the lord of the pokemans<br />
<br />
-Gmass can communicate with, and sometimes control any other cats, however this is very rare, as cats normally have a very strong will<br />
<br />
-Picture of Gmass http://i.imgur.com/PP9xi.png<br />
<br />
-Known by Mike Miller<br />
<br />
-Gmaas got mad at sseraj once, so he locked him in his own freezer<br />
<br />
-Then, sseraj decided to eat all of Gmaas's hidden turnips in the freezer as punishment<br />
<br />
-Gmaas is an obviously omnipotent cat.<br />
<br />
-ehawk11 met him<br />
<br />
-sseraj is known to post pictures of Gmaas on various AoPS classrooms. It is not known if these photos have been altered with the editing program called 'Photoshop'.<br />
<br />
-sseraj has posted pictures of gmass in '"intro to algebra", before class started, with the title, "caption contest" anyone who posted a caption mysteriously vanished in the middle of the night. <br />
EDIT: This has happened many times, including in Introduction to Geometry 1533, among other active classes. The person writing this (Poeshuman) did participate, and did not disappear. (You could argue Gmass is typing this through his/her account...)<br />
<br />
- gmass has once slept in your bed and made it wet<br />
<br />
-It is rumored that rrusczyk is actually Gmaas in disguise<br />
<br />
-Gmaas is suspected to be a Mewtwo in disguise<br />
<br />
-Gmaas is a cat but has characteristics of every other animal on Earth.<br />
<br />
-Gmass is the ruler of the universe and has been known to be the creator of the species "Gmassians".<br />
<br />
-There is a rumor that Gmaas is starting a poll<br />
<br />
-Gmaas is a rumored past ThunderClan cat who ran away, founded GmaasClan, then became a kittypet.<br />
<br />
-There is a rumored sport called "Gmaas Hunting" where people try to successfully capture gmaas in the wild with video/camera/eyes. Strangely, no one has been able to do this, and those that have have mysteriously disappeared into the night. Nobody knows why. The person who is writing this(g1zq) has tried Gmaas Hunting, but has never been successful.<br />
<br />
=== Gmaas photos ===<br />
http://cdn.artofproblemsolving.com/images/f/f/8/ff8efef3a0d2eb51254634e54bec215b948a1bba.jpg<br />
<br />
=== gmaas in Popular Culture ===<br />
<br />
- [s]Currently, is being written (by themoocow) about the adventures of gmaas. It is aptly titled, "The Adventures of gmaas".[/s]Sorry, this was a rick roll troll.<br />
<br />
- BREAKING NEWS: tigershark22 has found a possible cousin to gmaas in Raymond Feist's book Silverthorn. They are mountain dwellers, gwali. Not much are known about them either, and when someone asked,"What are gwali?" the customary answer "This is gwali" is returned. Scientist 5space is now looking into it.<br />
<br />
- Sullymath and themoocow are also writing a book about Gmaas<br />
<br />
-Oryx the mad god is actually gmass wearing a suit of armor. This explains why he is never truly killed<br />
<br />
- Potential sighting of gmaas [http://www.gmac.com/frequently-asked-questions/gmass-search-service.aspx]<br />
<br />
- Gmaas has been spotted in some Doctor Who and Phineas and Ferb episodes, such as Aliens of London, Phineas and Ferb Save Summer, Dalek, Rollercoaster, Rose, Boom Town, The Day of The Doctor, Candace Gets Busted, and many more.<br />
<br />
- Gmaas can be found in many places in Plants vs. Zombies Garden Warfare 2 and Bloons TD Battles<br />
<br />
- gmaas was an un-credited actor in the Doctor Who story Knock Knock, playing a Dryad. How he shrunk, we will never know.<br />
<br />
-oadaegan is also writing a story about him. He is continuing the book that was started by JpusheenS. when he is done he will post it here<br />
<br />
-Gmaas is a time traveler from 0.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 B.C.<br />
<br />
-No one knows if Gmass is a Mr. mime in a cat skin, the other way around, or just a downright combination of both.<br />
<br />
-In it, it mentions these four links as things Gmass is having trouble (specifically technical difficulties). What could it mean? Links:<br />
https://docs.google.com/document/d/1NZ0XcFYm80sA-fAoxnm7ulMCwdNU75Va_6ZjRHfSHV0<br />
https://docs.google.com/document/d/1ELN7ORauFFv1dwpU_u-ah_dFJHeuJ3szYxoeC1LlDQg/<br />
https://docs.google.com/document/d/1oy9Q3F7fygHw-OCWNEVE8d-Uob2dxVACFcGUcLmk3fA<br />
https://docs.google.com/document/d/1jzb9Q6FmDmrRyXwnik3e0sYw5bTPMo7aBwugmUbA13o<br />
<br />
<br />
- Another possible Gmaas sighting [https://2017.spaceappschallenge.org/challenges/warning-danger-ahead/and-you-can-help-fight-fires/teams/gmaas/project]<br />
<br />
-<math>Another</math> sighting? [https://www.radarbox24.com/data/flights/GMAAS]<br />
<br />
-Gmaas has been sighted several times on the Global Announcements forum<br />
<br />
-Gmaas uses the following transportation: [img]http://cdn.artofproblemsolving.com/images/3/6/8/368da4e615ea3476355ee3388b39f30a48b8dd48.jpg[/img]<br />
<br />
- When Gmaas was mad, he started world wars 1 & 2. It is only because of Gmaas that we have not had World War 3.<br />
<br />
- Gmaas is the only cat to have been proved irrational and transcendental, though we suspect all cats fall in the first category.</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93216
Basic Programming With Python
2018-03-13T22:13:54Z
<p>Bestaops: /* Program Example 6 */ spelling error</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
Note that this article has lots of program examples. It is recommended (but not required) to try these on your own before looking at the solutions.<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
count = 0<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
print(count(10000))<br />
</code><br />
<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
:total += count(i)<br />
<br />
print(total)<br />
</code><br />
<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
def count2(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count(i)<br />
:return total<br />
<br />
def count3(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count2(i)<br />
:return total<br />
<br />
print(count3(20))<br />
</code><br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while!<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is to soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!<br />
<br />
==Very Basic Datatypes==<br />
<br />
An integer is a basic datatype in Python. Basically, all variables with the datatype of '''int''' is an integer.<br />
<br />
A string is another basic datatype, and it is a string of characters enclosed by quotes.<br />
<br />
===Why Are Datatypes So Important?===<br />
<br />
Let's say we wanted to make a program that would add 2 and 3. Some bogus code would be:<br />
<br />
<br />
<code><br />
<br />
x="2"<br />
<br />
y="3"<br />
<br />
print(x+y)<br />
</code><br />
<br />
<br />
If you ran this code, you would get 23. Why is that?<br />
<br />
Well, here, x and y are strings. When you perform the addition operator to strings in Python, it concatenates the strings, giving 23.<br />
<br />
The real code is:<br />
<br />
<br />
<code><br />
<br />
x=2<br />
<br />
y=3<br />
<br />
print(x+y)<br />
</code><br />
<br />
<br />
If you run this, you will get 5, which is correct.<br />
<br />
Here's another reason datatypes are important. Now, we will introduce the datatype called the '''floating point number''', or '''float'''. A floating point number is a number with a decimal point.<br />
<br />
Let's go back to the IDLE. Type "0.1*10". The result is 1.0. Notice the decimal point.<br />
<br />
Let's type something different. Type <math>0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1.</math><br />
<br />
'''WHAT!?'''<br />
<br />
You would have expected the answer to be 1, but it isn't 1. What happened?<br />
<br />
'''Float approximation''' happened. Most (almost all) programming languages have a bad float approximation. That means that 1.0 can turn into 0.99999999999999 and 0.5 can turn into 0.49999999999999999993. That only happens with floats, so we should try to use floats as sparingly as possible.<br />
<br />
==Lists==<br />
<br />
A for loop iterates over a '''list'''. A list is a bunch of objects stored in one variable. For loops are highly related to lists.<br />
<br />
Let's say we wanted to make a program to print all the items in a list.<br />
<br />
We will first create the list, using the code:<br />
<br />
myList = [1,4,6,8]<br />
<br />
This is a list with four items: 1, 4, 6, and 8.<br />
<br />
We must now print all elements of it with a for loop:<br />
<br />
myList = [1,4,6,8]<br />
for i in myList:<br />
print(i)<br />
<br />
When we run this program, we get the numbers 1, 4, 6, and 8, as expected.<br />
<br />
===Accessing Values===<br />
<br />
Let's say we wanted to print out the second item in a list. We will use '''indexes'''.<br />
<br />
The index of the first item in a list is always 0. The index of the second is 1. The index of the <math>n</math>th is <math>n-1.</math><br />
<br />
To print out the second item, we will use an index of 1, like this:<br />
<br />
myList = [1,4,6,8]<br />
print(myList[1])<br />
<br />
Notice that the index is inside of the square brackets.<br />
<br />
Lists don't have to be only integers!<br />
<br />
myList = [1,"Hi","Hello world", 3.5, 3.14159265358979323]<br />
<br />
If fact, there can be lists inside of lists!<br />
<br />
myList = [[1,2,3], [3,4,5], [5,6,"Hello world"], "BOB", 3.1415926]<br />
<br />
Even this!<br />
<br />
myList = [[1, [1, [1,2,3],3],3], [[[3,["Hello world", 4],5],4,5],4,5], [5,6,7,[1,[1,2,3],3],"Hello world"], "BOB", 3.1415926, True]<br />
<br />
If you look at that list carefully, you will find lists inside of lists inside of lists inside of lists! And, a boolean at the end!</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93215
Basic Programming With Python
2018-03-13T22:11:06Z
<p>Bestaops: lists content</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
Note that this article has lots of program examples. It is recommended (but not required) to try these on your own before looking at the solutions.<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
count = 0<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
print(count(10000))<br />
</code><br />
<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
:total += count(i)<br />
<br />
print(total)<br />
</code><br />
<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
def count2(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count(i)<br />
:return total<br />
<br />
def count3(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count2(i)<br />
:return total<br />
<br />
print(count3(20))<br />
</code><br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while! Our code isn't that efficient, but the program doesn't take WAY TOO LONG, and we are still learning [[Basic Programming With Python]], so we don't have to worry about it now.<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is so soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!<br />
<br />
<br />
==Very Basic Datatypes==<br />
<br />
An integer is a basic datatype in Python. Basically, all variables with the datatype of '''int''' is an integer.<br />
<br />
A string is another basic datatype, and it is a string of characters enclosed by quotes.<br />
<br />
===Why Are Datatypes So Important?===<br />
<br />
Let's say we wanted to make a program that would add 2 and 3. Some bogus code would be:<br />
<br />
<br />
<code><br />
<br />
x="2"<br />
<br />
y="3"<br />
<br />
print(x+y)<br />
</code><br />
<br />
<br />
If you ran this code, you would get 23. Why is that?<br />
<br />
Well, here, x and y are strings. When you perform the addition operator to strings in Python, it concatenates the strings, giving 23.<br />
<br />
The real code is:<br />
<br />
<br />
<code><br />
<br />
x=2<br />
<br />
y=3<br />
<br />
print(x+y)<br />
</code><br />
<br />
<br />
If you run this, you will get 5, which is correct.<br />
<br />
Here's another reason datatypes are important. Now, we will introduce the datatype called the '''floating point number''', or '''float'''. A floating point number is a number with a decimal point.<br />
<br />
Let's go back to the IDLE. Type "0.1*10". The result is 1.0. Notice the decimal point.<br />
<br />
Let's type something different. Type <math>0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1.</math><br />
<br />
'''WHAT!?'''<br />
<br />
You would have expected the answer to be 1, but it isn't 1. What happened?<br />
<br />
'''Float approximation''' happened. Most (almost all) programming languages have a bad float approximation. That means that 1.0 can turn into 0.99999999999999 and 0.5 can turn into 0.49999999999999999993. That only happens with floats, so we should try to use floats as sparingly as possible.<br />
<br />
==Lists==<br />
<br />
A for loop iterates over a '''list'''. A list is a bunch of objects stored in one variable. For loops are highly related to lists.<br />
<br />
Let's say we wanted to make a program to print all the items in a list.<br />
<br />
We will first create the list, using the code:<br />
<br />
myList = [1,4,6,8]<br />
<br />
This is a list with four items: 1, 4, 6, and 8.<br />
<br />
We must now print all elements of it with a for loop:<br />
<br />
myList = [1,4,6,8]<br />
for i in myList:<br />
print(i)<br />
<br />
When we run this program, we get the numbers 1, 4, 6, and 8, as expected.<br />
<br />
===Accessing Values===<br />
<br />
Let's say we wanted to print out the second item in a list. We will use '''indexes'''.<br />
<br />
The index of the first item in a list is always 0. The index of the second is 1. The index of the <math>n</math>th is <math>n-1.</math><br />
<br />
To print out the second item, we will use an index of 1, like this:<br />
<br />
myList = [1,4,6,8]<br />
print(myList[1])<br />
<br />
Notice that the index is inside of the square brackets.<br />
<br />
Lists don't have to be only integers!<br />
<br />
myList = [1,"Hi","Hello world", 3.5, 3.14159265358979323]<br />
<br />
If fact, there can be lists inside of lists!<br />
<br />
myList = [[1,2,3], [3,4,5], [5,6,"Hello world"], "BOB", 3.1415926]<br />
<br />
Even this!<br />
<br />
myList = [[1, [1, [1,2,3],3],3], [[[3,["Hello world", 4],5],4,5],4,5], [5,6,7,[1,[1,2,3],3],"Hello world"], "BOB", 3.1415926, True]<br />
<br />
If you look at that list carefully, you will find lists inside of lists inside of lists inside of lists! And, a boolean at the end!</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93214
Basic Programming With Python
2018-03-13T20:54:07Z
<p>Bestaops: /* Why Are Datatypes So Important? */ floats</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
Note that this article has lots of program examples. It is recommended (but not required) to try these on your own before looking at the solutions.<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
count = 0<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
print(count(10000))<br />
</code><br />
<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
:total += count(i)<br />
<br />
print(total)<br />
</code><br />
<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
def count2(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count(i)<br />
:return total<br />
<br />
def count3(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count2(i)<br />
:return total<br />
<br />
print(count3(20))<br />
</code><br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while! Our code isn't that efficient, but the program doesn't take WAY TOO LONG, and we are still learning [[Basic Programming With Python]], so we don't have to worry about it now.<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is so soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!<br />
<br />
<br />
==Very Basic Datatypes==<br />
<br />
An integer is a basic datatype in Python. Basically, all variables with the datatype of '''int''' is an integer.<br />
<br />
A string is another basic datatype, and it is a string of characters enclosed by quotes.<br />
<br />
===Why Are Datatypes So Important?===<br />
<br />
Let's say we wanted to make a program that would add 2 and 3. Some bogus code would be:<br />
<br />
<br />
<code><br />
<br />
x="2"<br />
<br />
y="3"<br />
<br />
print(x+y)<br />
</code><br />
<br />
<br />
If you ran this code, you would get 23. Why is that?<br />
<br />
Well, here, x and y are strings. When you perform the addition operator to strings in Python, it concatenates the strings, giving 23.<br />
<br />
The real code is:<br />
<br />
<br />
<code><br />
<br />
x=2<br />
<br />
y=3<br />
<br />
print(x+y)<br />
</code><br />
<br />
<br />
If you run this, you will get 5, which is correct.<br />
<br />
Here's another reason datatypes are important. Now, we will introduce the datatype called the '''floating point number''', or '''float'''. A floating point number is a number with a decimal point.<br />
<br />
Let's go back to the IDLE. Type "0.1*10". The result is 1.0. Notice the decimal point.<br />
<br />
Let's type something different. Type <math>0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1.</math><br />
<br />
'''WHAT!?'''<br />
<br />
You would have expected the answer to be 1, but it isn't 1. What happened?<br />
<br />
'''Float approximation''' happened. Most (almost all) programming languages have a bad float approximation. That means that 1.0 can turn into 0.99999999999999 and 0.5 can turn into 0.49999999999999999993. That only happens with floats, so we should try to use floats as sparingly as possible.</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93213
Basic Programming With Python
2018-03-13T20:48:27Z
<p>Bestaops: /* Why Are Datatypes So Important? */ BUG</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
Note that this article has lots of program examples. It is recommended (but not required) to try these on your own before looking at the solutions.<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
count = 0<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
print(count(10000))<br />
</code><br />
<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
:total += count(i)<br />
<br />
print(total)<br />
</code><br />
<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
def count2(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count(i)<br />
:return total<br />
<br />
def count3(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count2(i)<br />
:return total<br />
<br />
print(count3(20))<br />
</code><br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while! Our code isn't that efficient, but the program doesn't take WAY TOO LONG, and we are still learning [[Basic Programming With Python]], so we don't have to worry about it now.<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is so soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!<br />
<br />
<br />
==Very Basic Datatypes==<br />
<br />
An integer is a basic datatype in Python. Basically, all variables with the datatype of '''int''' is an integer.<br />
<br />
A string is another basic datatype, and it is a string of characters enclosed by quotes.<br />
<br />
===Why Are Datatypes So Important?===<br />
<br />
Let's say we wanted to make a program that would add 2 and 3. Some bogus code would be:<br />
<br />
<br />
<code><br />
<br />
x="2"<br />
<br />
y="3"<br />
<br />
print(x+y)<br />
</code><br />
<br />
<br />
If you ran this code, you would get 23. Why is that?<br />
<br />
Well, here, x and y are strings. When you perform the addition operator to strings in Python, it concatenates the strings, giving 23.<br />
<br />
The real code is:<br />
<br />
<br />
<code><br />
<br />
x=2<br />
<br />
y=3<br />
<br />
print(x+y)<br />
</code><br />
<br />
<br />
If you run this, you will get 5, which is correct.</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93212
Basic Programming With Python
2018-03-13T20:48:00Z
<p>Bestaops: /* Very Basic Datatypes */ added contents</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
Note that this article has lots of program examples. It is recommended (but not required) to try these on your own before looking at the solutions.<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
count = 0<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
print(count(10000))<br />
</code><br />
<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
:total += count(i)<br />
<br />
print(total)<br />
</code><br />
<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
def count2(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count(i)<br />
:return total<br />
<br />
def count3(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count2(i)<br />
:return total<br />
<br />
print(count3(20))<br />
</code><br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while! Our code isn't that efficient, but the program doesn't take WAY TOO LONG, and we are still learning [[Basic Programming With Python]], so we don't have to worry about it now.<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is so soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!<br />
<br />
<br />
==Very Basic Datatypes==<br />
<br />
An integer is a basic datatype in Python. Basically, all variables with the datatype of '''int''' is an integer.<br />
<br />
A string is another basic datatype, and it is a string of characters enclosed by quotes.<br />
<br />
===Why Are Datatypes So Important?===<br />
<br />
Let's say we wanted to make a program that would add 2 and 3. Some bogus code would be:<br />
<br />
<br />
<code><br />
<br />
x="2"<br />
y="3"<br />
print(x+y)<br />
<br />
</code><br />
<br />
<br />
If you ran this code, you would get 23. Why is that?<br />
<br />
Well, here, x and y are strings. When you perform the addition operator to strings in Python, it concatenates the strings, giving 23.<br />
<br />
The real code is:<br />
<br />
<br />
<code><br />
<br />
x=2<br />
y=3<br />
print(x+y)<br />
<br />
</code><br />
<br />
<br />
If you run this, you will get 5, which is correct.</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93211
Basic Programming With Python
2018-03-13T20:38:24Z
<p>Bestaops: new section header</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
Note that this article has lots of program examples. It is recommended (but not required) to try these on your own before looking at the solutions.<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
count = 0<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
print(count(10000))<br />
</code><br />
<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
:total += count(i)<br />
<br />
print(total)<br />
</code><br />
<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
def count2(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count(i)<br />
:return total<br />
<br />
def count3(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count2(i)<br />
:return total<br />
<br />
print(count3(20))<br />
</code><br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while! Our code isn't that efficient, but the program doesn't take WAY TOO LONG, and we are still learning [[Basic Programming With Python]], so we don't have to worry about it now.<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is so soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!<br />
<br />
<br />
==Very Basic Datatypes==</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=AoPS_Wiki:Tutorial&diff=93198
AoPS Wiki:Tutorial
2018-03-12T22:11:33Z
<p>Bestaops: /* Finding Articles To Edit */</p>
<hr />
<div>{{shortcut|[[A:T]]}}<br />
This '''AoPSWiki tutorial''' will help guide you through the process of learning to contribute to the [[AoPSWiki]]. Also see the categories [[:Category:AoPSWiki | AoPSWiki]] and [[:Category:Tutorials | Tutorials]] for more information on certain topics.<br />
<br />
In addition to the information below, there is a good [http://en.wikipedia.org/wiki/Help:Editing Wikipedia editing page] which contains most of the information below and will be incorporated into this tutorial over time.<br />
<br />
<br />
== Editing the AoPSWiki ==<br />
The AoPSWiki is meant to be edited by you, the users. If you ever find yourself saying that you could have done a better job on an article, we encourage you to edit it and improve it! Before you can edit the article, however, you should make sure you are familiar with how the AoPSWiki works.<br />
<br />
=== Learning About AoPSWiki ===<br />
All users are encouraged to read up on what a wiki is and look around AoPSWiki. Click the [[Special:Random | Random Page]] button on the navigation panel at right a few times to get a feel for the structure of content in the AoPSWiki. Try clicking through a few of the colored links on some of the pages. Some will take you to other parts of the AoPSWiki and some will take you out of the AoPSWiki to other websites.<br />
<br />
Read about [[AoPSWiki:What makes AoPSWiki different|what makes the AoPSWiki different]].<br />
<br />
=== Creating an Article ===<br />
If you search a topic or click on a link to an article that was not yet written, you yourself can begin creating that article. It is preferred to make bold the name of the article when it first appears in the article, particularly for terms that are given definitions. Bolding is explained in the Wiki Syntax section below. Read [http://artofproblemsolving.com/community/c65h98050p553863 Tips for Article Creation] to better understand the AoPSWiki philosophy of article content.<br />
<br />
If you can't think of a good topic to write about, look through the list of [[:Category:stubs|stubs]] for articles which already exist but have very little content.<br />
<br />
=== Editing an Article ===<br />
Click on the '''Edit''' button above an article while you are logged into the AoPSWiki. If the article is new, you can just start writing. If the article already exists, you will see the article text, [[MediaWiki]] syntax included. Write around or over the text to change the content of the article.<br />
<br />
If you would like to experiment with the Wiki format, please use the [http://en.wikipedia.org/wiki/Wikipedia:Sandbox Sandbox] to play around with new features.<br />
<br />
=== Wiki Syntax ===<br />
First, while in edit mode, there is a control panel in the upper left of the text box. Hover your cursor over the buttons to get an idea as to what they do. Remember that you can test syntax on your own user page. You can also hunt for examples by going into edit mode while in any article. Next, you can practice using wiki syntax in the [[sandbox]]. Here are a few common ways to format content in your article:<br />
* To create '''bullets''' link for this list, use the asterisk (*) at the beginning of each line.<br />
* Use the colon (:) to '''indent'''.<br />
* To ''italicize'' text, place two apostrophes both before and after the <nowiki>''text''</nowiki>.<br />
* To '''bold''' text, place three apostrophes both before and after the <nowiki>'''text'''</nowiki>.<br />
<br />
==== Internal Links ====<br />
Internal links are at the heart of what makes a wiki. Place two square brackets on each side of a word or phrase to link the text to the article of the same name. In order to create the link [[mathematics]], you would type <nowiki>[[mathematics]]</nowiki>. Also, for the cases when it is necessary to make the link-forming part of the phrase different from the actual title of the article it refers to, you may use the piped link format like in <nowiki>[[real number|reals]]</nowiki>, which will create a link to the article titled '''Real Number''' but show and highlight the word '''reals''' instead. If you wish to refer to a specific section of an article, say that Natural Logarithm section of the Logarithm article, you use <nowiki>[[Logarithm#Natural Logarithm|natural logarithm]]</nowiki>, which comes out like this: [[Logarithm#Natural Logarithm|natural logarithm]].<br />
<br />
==== External Links ====<br />
When linking to information outside of the AoPSWiki, use external links. Begin with one open square bracket, type or paste the URL, add a space, then type the text that should appear naming the external link. For instance, to create a link to the [[MAA]] homepage ([http://www.maa.org Mathematical Association of America]), you should type <nowiki>[http://www.maa.org Mathematical Association of America]</nowiki>.<br />
<br />
When linking to any page on AoPS/[[MathLinks]], such as http://www.artofproblemsolving.com/viewtopic.php?t=217167 or http://www.mathlinks.ro/viewtopic.php?t=217167, do it like this:<br />
<nowiki><url>viewtopic.php?=217167 Vietnam test problem</url></nowiki><br />
It will look like this: <url>viewtopic.php?=217167 Vietnam test problem</url>.<br />
This way, people in Mathlinks will stay in Mathlinks, and people in the<br />
Art of Problem Solving will stay in the Art of Problem Solving.<br />
<br />
If you plan to add book links, please read [[AoPSWiki:Linking books]].<br />
<br />
==== Redirects ====<br />
If an article has several less standard names or acronyms, you can create a page (or pages) to direct users who find each one to the article name you chose. For instance, there is an article under [[ARML]] with the following text: <br><br />
<nowiki>#REDIRECT[[American Regions Mathematics League]]</nowiki>.<br><br />
If you click on the [[ARML]] link, you will go directly to the [[American Regions Mathematics League]] page. Very convenient!<br />
<br />
==== HTML Phrases====<br />
AoPSWiki supports a limited, but highly useful amount of HTML. Try it out and see.<br />
<br />
{| border="0" cellpadding="5"<br />
| valign="top"|<br />
* &lt;b&gt;<br />
* &lt;big&gt;<br />
* &lt;blockquote&gt;<br />
* &lt;br&gt;<br />
* &lt;caption&gt;<br />
* &lt;center&gt;<br />
* &lt;cite&gt;<br />
* &lt;code&gt;<br />
* &lt;dd&gt;<br />
* &lt;div&gt;<br />
* &lt;dl&gt;<br />
* &lt;dt&gt;<br />
| valign="top"|<br />
* &lt;em&gt;<br />
* &lt;font&gt;<br />
* &lt;h1&gt;<br />
* &lt;h2&gt;<br />
* &lt;h3&gt;<br />
* &lt;h4&gt;<br />
* &lt;h5&gt;<br />
* &lt;h6&gt;<br />
* &lt;hr&gt;<br />
* &lt;i&gt;<br />
* &lt;li&gt;<br />
* &lt;ol&gt;<br />
| valign="top"|<br />
* &lt;p&gt;<br />
* &lt;pre&gt;<br />
* [http://www.w3.org/TR/1999/WD-ruby-19990322/ &lt;rb&gt;]<br />
* [http://www.w3.org/TR/1999/WD-ruby-19990322/ &lt;rp&gt;]<br />
* [http://www.w3.org/TR/1999/WD-ruby-19990322/ &lt;rt&gt;]<br />
* [http://www.w3.org/TR/1999/WD-ruby-19990322/ &lt;ruby&gt;]<br />
* &lt;s&gt;<br />
* &lt;small&gt;<br />
* &lt;strike&gt;<br />
* &lt;strong&gt;<br />
* &lt;sub&gt;<br />
* &lt;sup&gt;<br />
| valign="top"|<br />
* &lt;table&gt;<br />
* &lt;td&gt;<br />
* &lt;th&gt;<br />
* &lt;tr&gt;<br />
* &lt;tt&gt;<br />
* &lt;u&gt;<br />
* &lt;ul&gt;<br />
* &lt;var&gt;<br />
* &lt;!-- ... --&gt;<br />
|}<br />
<br />
=== Templates & Categories ===<br />
See the article [[template]]s and [[Help:Category|categories]] for a definitive guide on creating and using templates & categories, as well as a list of templates and categories currently in existence.<br />
<br />
== Finding Articles To Edit ==<br />
=== Red Links ===<br />
If, while reading through an article, you notice a red internal link, that represents an article that has not yet been written. Click on the red link to start writing that article. Remember, however, that the article on this subject may have already been written under a slightly different name, so it is always a good idea to make a little search first. If you find the relevant article under a different name, all you need to do is to create a simple REDIRECT page. You may also want to use this option if you feel that the right name for the topic should be somewhat different from the text in the red link. Also, don't forget to check the red link text for spelling and other errors before creating an article with the name from a red link.<br />
<br />
=== Recently Changed Articles ===<br />
At least while AoPSWiki is relatively young, recently changed articles are usually fairly new articles. You can find recently changed articles by clicking on the [[Special:Recentchanges]] (Recent Changes) link on the navigation tab at right. Go methodically through the articles, either contributing or adding broken links. Also see the [[AoPSWiki:Community_Portal]] (Community Portal).<br />
=== Wanted Pages ===<br />
The AoPSWiki automatically creates a list of [[Special:Wantedpages|wanted pages]]. These are pages to which there exist several links, but no actual page exists. This is a good place to look for articles which would contribute the most to the AoPSWiki's goodness.<br />
<br />
===Stubs===<br />
<br />
Some short articles have text at the bottom that says<br />
<br />
This article is a stub. Help us by expanding it.<br />
<br />
Therefore, it is extremely recommended to expand very short articles (that are stubs).<br />
<br />
== Practice Good Netiquette ==<br />
* Absolutely no [[spam]] is permitted in the AoPSWiki.<br />
* Practice good [[netiquette]].<br />
* Be aware of [[AoPSWiki:What AoPSWiki is not|what the AoPSWiki isn't]].<br />
<br />
== Where to Ask Questions ==<br />
=== AoPSWiki Forum ===<br />
The <url>Forum/index.php?f=416 AoPSWiki Forum</url> is a place to ask questions about AoPSWiki and its functionality when you cannot find the explanation in the AoPSWiki itself. Please read through the announcement and sticky threads to see if your questions are answered there. The forum also includes a search feature that might help you locate the answers to your questions.<br />
<br />
=== Article Discussion ===<br />
Click the '''Discussion''' tab at the top of an article to ask questions about the article or discuss its content.<br />
<br />
=== Math Questions ===<br />
The [http://www.artofproblemsolving.com/Forum/index.php AoPS Forums] are the appropriate place to ask questions about [[mathematics]], concepts, specific math problems, and [[problem solving]].<br />
<br />
== AoPSWiki Pages ==<br />
Please read through the pages related to the AoPSWiki, linked through the category link below, in order to best understand how to use the AoPSWiki.<br />
<br />
<br />
<br />
[[Category:AoPSWiki|Tutorial]]</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93197
Basic Programming With Python
2018-03-12T22:02:09Z
<p>Bestaops: program examples explained</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
Note that this article has lots of program examples. It is recommended (but not required) to try these on your own before looking at the solutions.<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
count = 0<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
print(count(10000))<br />
</code><br />
<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
:total += count(i)<br />
<br />
print(total)<br />
</code><br />
<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
def count2(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count(i)<br />
:return total<br />
<br />
def count3(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count2(i)<br />
:return total<br />
<br />
print(count3(20))<br />
</code><br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while! Our code isn't that efficient, but the program doesn't take WAY TOO LONG, and we are still learning [[Basic Programming With Python]], so we don't have to worry about it now.<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is so soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Getting_Started_With_Python_Programming&diff=93196
Getting Started With Python Programming
2018-03-12T22:01:02Z
<p>Bestaops: its bad to use title headers as section headers</p>
<hr />
<div>This guide takes you through the process of getting started with programming using the Python programming language. The only language that AoPS teaches (as of March 2018) in a class is Python. <br />
<br />
The sections flow from one to the next so it's recommended to read through this document in order from top to bottom. <br />
<br />
If you find that this is too easy, '''make sure you've read everything through (at least roughly)''', and check out [[Basic Programming With Python]].<br />
<br />
==Installing Python==<br />
<br />
Python is a useful and popular computer programming language. Confusingly, Python has two major versions (2 and 3) and they are not fully compatible. We recommend using the most recent release of version 3. (This is the version that our [http://www.artofproblemsolving.com/School/courseinfo.php?course_id=python1 Introduction to Programming with Python course] uses -- if you are enrolled in that class, you '''must''' have Python 3.) There is absolutely nothing wrong with Python 2, as it is what most of today's technology supports and uses, but Python 3 is well on the way of replacing Python 2, so it will be more useful in a few years.<br />
<br />
Python is open-source software and it is '''free''' to install and use. Here are installation instructions:<br />
<br />
#Go to the Python download page at http://www.python.org/downloads. Near the top of the page, there will be a list of download links for the Python 3.6.x installer. (The x will be replaced by a number -- as of March 2017 the version is 3.6.1.) If you are given multiple options, click on the link that corresponds to your computer type (Windows or Mac, 32-bit or 64-bit -- if you're not sure, use the 32-bit version.) Some browsers will save the file automatically, others may pop up a box asking you if you want to save the file, in which case you should click the "save file" option. Depending on how your browser is configured, you may be asked where to save the file. If this is the case, keep track of where you save the installer.<br />
#Find where the installer was downloaded and double click on it to run it. On most browsers, you should simply be able to double-click the installer from the browser's "Downloads" window or menu. You may also have to click "Run" or "Yes" to a security window -- do this if necessary.<br />
#The setup wizard should launch. You should just click "Next" for every option in the setup wizard (i.e. use the defaults), unless you have some specific reason not to.<br />
#Familiarize yourself with the Python shell and IDLE text editor by running through the two sections below.<br />
<br />
==Programming==<br />
<br />
Yay, it's time to program! The next few sections will talk about some very basic programming. We will program a few programs as a demonstration.<br />
<br />
===Using the Python Shell===<br />
The program that you'll use to run Python is called IDLE. It may be listed on your computer as "IDLE (Python GUI)". <br />
* On a Mac, IDLE should be in the Applications folder. <br />
* On Windows, IDLE should be accessible from the Start menu in a folder named "Python 3.6" (or something similar).<br />
The icon for IDLE looks something like this [[File:Idleicon.png]] or this [[File:Idleiconmac.png]].<br />
<br />
When you first open IDLE, you'll see the Python Shell (the numbers on your shell might be different than those shown below): <br />
<br />
[[File:Idle2-1.png]]<br />
<br />
(The screenshots in this article are taken using IDLE on a Mac with the font increased. Thus IDLE may look a little bit different for you but should still function similarly.)<br />
<br />
Note that the first line is the version of Python, which is 3.1.2 in the screenshot but should be 3.6.something if you installed it as directed above. Another thing to note is that in the lower right hand corner of the Python Shell you can see that it says "Ln: 4 Col: 4". This is just telling you where in the document your cursor is. In this case it's on line 4 and over in column 4. (The line and column number may be slightly different for your installation.)<br />
<br />
When you first start up Python on a Mac, you might get the following warning:<br />
: >>> WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable.<br />
: Visit http://www.python.org/download/mac/tcltk/ for current information.<br />
If you get this warning, you'll need to update a graphics driver on your computer. Follow the link shown above and download and install the ActiveTcl driver that's recommended for the version of OS X that your Mac is running. This most likely will be 8.5.15.0, which you can also download directly from http://www.activestate.com/activetcl/downloads (IMPORTANT: you only need to do this step if you get the warning printed above when you start IDLE for the first time. If you don't get the warning, then everything is good to go.)<br />
<br />
<br />
The Python Shell is very useful for quick one-liners and short sequences of commands:<br />
<br />
[[File:Idle2-2.2.png]]<br />
<br />
Here we see a number of familiar operations: + for addition, - for subtraction, * for multiplication, and / for division. The last operation shown in the example, denoted by **, happens to be exponentiation. One neat feature to note about Python is that it can store arbitrarily large numbers (limited by the amount of memory your computer has). Trying some hefty exponentiation, we can see that we can compute with some pretty big numbers such as <math>2^{1000}</math> as illustrated below.<br />
<br />
[[File:Idle2-3.png]]<br />
<br />
While Python can make for a pretty good calculator, it can do a whole lot more. One example is when dealing with strings as follows:<br />
<br />
[[File:Idle2-4.png]]<br />
<br />
Here we are concatenating the three strings "python", "is", and "cool" by using the + operator. Notice that previously we used + to add numbers but now with strings, Python concatenates them! You may also note that the output of the operation gives us a string with single quotes around it. In Python, you are able to use single quotes or double quotes to denote a string. You can use them interchangeably.<br />
<br />
As a final example, we can even write code in the Python Shell that extends beyond a single line as shown below. We also see our first example of a <math>\verb=for=</math> loop.<br />
<br />
[[File:Idle2-5.png]]<br />
<br />
As you type the above, the Python Shell will automatically indent the second line for you. To let the Python Shell know that you're done and are ready for it to run your code, you'll need to put in an extra blank line by hitting the Enter key again. At that point it should run your code and print your output.<br />
<br />
Take some time to play around with the Python Shell. You'll want to go through a more extensive introduction to programming to learn the full extent of what you can do with Python, but you can still do some pretty nifty stuff by just playing around. The Python Shell also has an extensive built-in help system -- just type '''help()''' at the ">>>" prompt to get started and then follow the instructions it gives you.<br />
<br />
===The IDLE Text Editor===<br />
For most programming needs, you'll want to edit your program in a separate document and then run it. Luckily, IDLE comes with its own built-in text editor.<br />
<br />
To get started, go to the File menu of the Python Shell and click on "New Window". This should give you a blank document with the title "Untitled" as shown below:<br />
<br />
[[File:Idle2-6.png]]<br />
<br />
You'll need to save your file before running it, so you might as well save it now. Make sure that you name your file with a file name with a file extension of .py (so it ends with .py), so your computer knows that it is a Python program. Here, we save ours as test.py:<br />
<br />
[[File:Idle2-7.png]]<br />
<br />
To get acquainted with the text editor, let's write our first Python program! Let's write a program that will do the following task:<br />
<br />
'''Print all the integers from 1 to 50 inclusive.'''<br />
<br />
We can achieve this by using a loop that can loop through all the integers. Luckily, Python has a function just for doing that! We use a for loop with the following code:<br />
<br />
[[File:Test_.png]]<br />
<br />
Note that as you type, the keywords like "for", "in", "range" and "print" get colored in orange or purple!<br />
Also, note that you must copy the exact same indentation. Even though the editor automatically indents for you when you type <code>for i in range(1, 51):</code>, proper indentation in Python is super important! If you don't do it correctly, the program will not compile correctly.<br />
<br />
You can indent by pressing Tab on your keyboard.<br />
<br />
This for loop means to iterate from 1 to 51 excluding the 51 and including the 1. Every iteration, Python will print out the number that it is iterating through.<br />
<br />
Now that you've written this code, you probably want to run it and test it out. You can do so by going to the Run menu and hitting "Run Module" (or by pressing F5 on your keyboard). The ===RESTART=== line means that Python is clearing all the work you've previously done before it starts running your program. The program should execute and print all the integers to the Python Shell. If it didn't, then make sure your code exactly matches the code above.<br />
<br />
[[File:Test__results.png]]<br />
<br />
If your code worked, congratulations! You have written your very first program! Now, let's try another more useful one.<br />
<br />
'''Find the sum of all the positive multiples of 3 below 1000.'''<br />
<br />
We first need to create a new file. Go into the Python Shell and click on New Window again. Remember, we must save our file first. We can save it as test2.py. Now, on to the coding!<br />
We can solve this by keeping a running total: we'll start with the smallest positive multiple of 3 and go up one multiple at a time keeping track of the sum, stopping once we hit 1000. We can do this with the following code:<br />
<br />
[[File:Idle2-8.png]]<br />
<br />
This is called a while loop. While loops keep iterating until a statement becomes false.<br />
Notice that as you type the above code, the keywords ("while" and "print") will automatically get colored -- this makes the code easier to read. Also, after typing the line "while i < 1000:", the editor will automatically start indenting for you. When you get to the line "print(total)", you'll need to use the backspace key to remove the indentation. It is important that the code look exactly like it does in the screenshot above. Again, in Python, proper indentation is very important!<br />
<br />
This program basically works by incrementing the variable <math>\verb=i=</math> by 3 every time and adding it to the variable <math>\verb=total=</math>. The <math>\verb%+=%</math> operation might be intimidating at first. However, the statement <math>\verb%i += 3%</math> is just a shorthand for <math>\verb%i = i + 3%</math>. (So <math>\verb%a += b%</math> means <math>\verb&a = a + b&</math>.)<br />
<br />
Run your program, and you should get this:<br />
<br />
[[File:Idle2-9.png]]<br />
<br />
Again, the ===RESTART=== line just means that Python is clearing all the work you've previously done before it starts running your program. Then, the program runs and we get our answer, 166833. If you instead get an error message or a different answer, check that your program exactly matches the screenshot above, and try it again.<br />
<br />
Congrats! You have written your first two Python programs!<br />
<br />
==What's Next?==<br />
<br />
Now that you've learned the very basics of getting Python going, there's a bunch of tutorials you can look at which are [http://wiki.python.org/moin/BeginnersGuide/NonProgrammers listed] on the Python website. Go check them out! Another great resource is "Stack Overflow," a forums website built for people who would like to talk about, and get help with programming. It is also recommended that you check out a wiki article discussing more advanced python, namely [[Basic Programming With Python]].<br />
<br />
Or, you can take our Introduction to Programming with Python online course!</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Computer_science&diff=93195
Computer science
2018-03-12T21:58:50Z
<p>Bestaops: /* See also */ whoops</p>
<hr />
<div>'''Computer science''' is the study of computers and computation, or more specifically, the [[algorithm]]s used to obtain results with these tools.<br />
<br />
== Topics in computer science ==<br />
===Computer programming===<br />
{{main|Computer programming}}<br />
'''Computer programming''' is the study of how algorithms can be applied through the use of various programming languages to create software utilities for the computer. Common programming languages include [[C++]], [[Java]], [[Visual Basic]], [[C#]], [[C]], and [[Pascal (language) | Pascal]]. Other languages differing slightly in usage from these are known as scripting languages. Examples are Perl, Python, Ruby and PHP.<br />
<br />
===Computability and complexity===<br />
{{main|Computability and complexity}}<br />
Computability and computational complexity are problems which concern the limits of algorithms to solve certain types of problems under certain constraints. For example, the [[P versus NP]] problem is such a problem.<br />
<br />
<br />
== See also ==<br />
* [[Computer science books]]<br />
* [[Computer science competitions]]<br />
* [[Computer science scholarships]]<br />
* [[Getting Started With Python Programming|Basic python tutorial]]</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Computer_science&diff=93194
Computer science
2018-03-12T21:58:31Z
<p>Bestaops: /* See also */</p>
<hr />
<div>'''Computer science''' is the study of computers and computation, or more specifically, the [[algorithm]]s used to obtain results with these tools.<br />
<br />
== Topics in computer science ==<br />
===Computer programming===<br />
{{main|Computer programming}}<br />
'''Computer programming''' is the study of how algorithms can be applied through the use of various programming languages to create software utilities for the computer. Common programming languages include [[C++]], [[Java]], [[Visual Basic]], [[C#]], [[C]], and [[Pascal (language) | Pascal]]. Other languages differing slightly in usage from these are known as scripting languages. Examples are Perl, Python, Ruby and PHP.<br />
<br />
===Computability and complexity===<br />
{{main|Computability and complexity}}<br />
Computability and computational complexity are problems which concern the limits of algorithms to solve certain types of problems under certain constraints. For example, the [[P versus NP]] problem is such a problem.<br />
<br />
<br />
== See also ==<br />
* [[Computer science books]]<br />
* [[Computer science competitions]]<br />
* [[Computer science scholarships]]<br />
* [[Getting Started With Python|Basic python tutorial]]</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Getting_Started_With_Python_Programming&diff=93193
Getting Started With Python Programming
2018-03-12T21:54:10Z
<p>Bestaops: /* What's Next? */ bad wording is fixed</p>
<hr />
<div>This guide takes you through the process of getting started with programming using the Python programming language. The sections flow from one to the next so it's recommended to read through this document in order from top to bottom. If you find that this is too easy, make sure you've read everything, and check out [[Basic Programming With Python]].<br />
<br />
=Installing Python=<br />
<br />
Python is a useful and popular computer programming language. Confusingly, Python has two major versions (2 and 3) and they are not fully compatible. We recommend using the most recent release of version 3. (This is the version that our [http://www.artofproblemsolving.com/School/courseinfo.php?course_id=python1 Introduction to Programming with Python course] uses -- if you are enrolled in that class, you '''must''' have Python 3.) There is absolutely nothing wrong with Python 2, as it is what most of today's technology supports and uses, but Python 3 is well on the way of replacing Python 2, so it will be more useful in a few years.<br />
<br />
Python is open-source software and it is '''free''' to install and use. Here are installation instructions:<br />
<br />
#Go to the Python download page at http://www.python.org/downloads. Near the top of the page, there will be a list of download links for the Python 3.6.x installer. (The x will be replaced by a number -- as of March 2017 the version is 3.6.1.) If you are given multiple options, click on the link that corresponds to your computer type (Windows or Mac, 32-bit or 64-bit -- if you're not sure, use the 32-bit version.) Some browsers will save the file automatically, others may pop up a box asking you if you want to save the file, in which case you should click the "save file" option. Depending on how your browser is configured, you may be asked where to save the file. If this is the case, keep track of where you save the installer.<br />
#Find where the installer was downloaded and double click on it to run it. On most browsers, you should simply be able to double-click the installer from the browser's "Downloads" window or menu. You may also have to click "Run" or "Yes" to a security window -- do this if necessary.<br />
#The setup wizard should launch. You should just click "Next" for every option in the setup wizard (i.e. use the defaults), unless you have some specific reason not to.<br />
#Familiarize yourself with the Python shell and IDLE text editor by running through the two sections below.<br />
<br />
=Programming=<br />
<br />
Yay, it's time to program! The next few sections will talk about some very basic programming. We will program a few programs as a demonstration.<br />
<br />
==Using the Python Shell==<br />
The program that you'll use to run Python is called IDLE. It may be listed on your computer as "IDLE (Python GUI)". <br />
* On a Mac, IDLE should be in the Applications folder. <br />
* On Windows, IDLE should be accessible from the Start menu in a folder named "Python 3.6" (or something similar).<br />
The icon for IDLE looks something like this [[File:Idleicon.png]] or this [[File:Idleiconmac.png]].<br />
<br />
When you first open IDLE, you'll see the Python Shell (the numbers on your shell might be different than those shown below): <br />
<br />
[[File:Idle2-1.png]]<br />
<br />
(The screenshots in this article are taken using IDLE on a Mac with the font increased. Thus IDLE may look a little bit different for you but should still function similarly.)<br />
<br />
Note that the first line is the version of Python, which is 3.1.2 in the screenshot but should be 3.6.something if you installed it as directed above. Another thing to note is that in the lower right hand corner of the Python Shell you can see that it says "Ln: 4 Col: 4". This is just telling you where in the document your cursor is. In this case it's on line 4 and over in column 4. (The line and column number may be slightly different for your installation.)<br />
<br />
When you first start up Python on a Mac, you might get the following warning:<br />
: >>> WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable.<br />
: Visit http://www.python.org/download/mac/tcltk/ for current information.<br />
If you get this warning, you'll need to update a graphics driver on your computer. Follow the link shown above and download and install the ActiveTcl driver that's recommended for the version of OS X that your Mac is running. This most likely will be 8.5.15.0, which you can also download directly from http://www.activestate.com/activetcl/downloads (IMPORTANT: you only need to do this step if you get the warning printed above when you start IDLE for the first time. If you don't get the warning, then everything is good to go.)<br />
<br />
<br />
The Python Shell is very useful for quick one-liners and short sequences of commands:<br />
<br />
[[File:Idle2-2.2.png]]<br />
<br />
Here we see a number of familiar operations: + for addition, - for subtraction, * for multiplication, and / for division. The last operation shown in the example, denoted by **, happens to be exponentiation. One neat feature to note about Python is that it can store arbitrarily large numbers (limited by the amount of memory your computer has). Trying some hefty exponentiation, we can see that we can compute with some pretty big numbers such as <math>2^{1000}</math> as illustrated below.<br />
<br />
[[File:Idle2-3.png]]<br />
<br />
While Python can make for a pretty good calculator, it can do a whole lot more. One example is when dealing with strings as follows:<br />
<br />
[[File:Idle2-4.png]]<br />
<br />
Here we are concatenating the three strings "python", "is", and "cool" by using the + operator. Notice that previously we used + to add numbers but now with strings, Python concatenates them! You may also note that the output of the operation gives us a string with single quotes around it. In Python, you are able to use single quotes or double quotes to denote a string. You can use them interchangeably.<br />
<br />
As a final example, we can even write code in the Python Shell that extends beyond a single line as shown below. We also see our first example of a <math>\verb=for=</math> loop.<br />
<br />
[[File:Idle2-5.png]]<br />
<br />
As you type the above, the Python Shell will automatically indent the second line for you. To let the Python Shell know that you're done and are ready for it to run your code, you'll need to put in an extra blank line by hitting the Enter key again. At that point it should run your code and print your output.<br />
<br />
Take some time to play around with the Python Shell. You'll want to go through a more extensive introduction to programming to learn the full extent of what you can do with Python, but you can still do some pretty nifty stuff by just playing around. The Python Shell also has an extensive built-in help system -- just type '''help()''' at the ">>>" prompt to get started and then follow the instructions it gives you.<br />
<br />
==The IDLE Text Editor==<br />
For most programming needs, you'll want to edit your program in a separate document and then run it. Luckily, IDLE comes with its own built-in text editor.<br />
<br />
To get started, go to the File menu of the Python Shell and click on "New Window". This should give you a blank document with the title "Untitled" as shown below:<br />
<br />
[[File:Idle2-6.png]]<br />
<br />
You'll need to save your file before running it, so you might as well save it now. Make sure that you name your file with a file name with a file extension of .py (so it ends with .py), so your computer knows that it is a Python program. Here, we save ours as test.py:<br />
<br />
[[File:Idle2-7.png]]<br />
<br />
To get acquainted with the text editor, let's write our first Python program! Let's write a program that will do the following task:<br />
<br />
'''Print all the integers from 1 to 50 inclusive.'''<br />
<br />
We can achieve this by using a loop that can loop through all the integers. Luckily, Python has a function just for doing that! We use a for loop with the following code:<br />
<br />
[[File:Test_.png]]<br />
<br />
Note that as you type, the keywords like "for", "in", "range" and "print" get colored in orange or purple!<br />
Also, note that you must copy the exact same indentation. Even though the editor automatically indents for you when you type <code>for i in range(1, 51):</code>, proper indentation in Python is super important! If you don't do it correctly, the program will not compile correctly.<br />
<br />
You can indent by pressing Tab on your keyboard.<br />
<br />
This for loop means to iterate from 1 to 51 excluding the 51 and including the 1. Every iteration, Python will print out the number that it is iterating through.<br />
<br />
Now that you've written this code, you probably want to run it and test it out. You can do so by going to the Run menu and hitting "Run Module" (or by pressing F5 on your keyboard). The ===RESTART=== line means that Python is clearing all the work you've previously done before it starts running your program. The program should execute and print all the integers to the Python Shell. If it didn't, then make sure your code exactly matches the code above.<br />
<br />
[[File:Test__results.png]]<br />
<br />
If your code worked, congratulations! You have written your very first program! Now, let's try another more useful one.<br />
<br />
'''Find the sum of all the positive multiples of 3 below 1000.'''<br />
<br />
We first need to create a new file. Go into the Python Shell and click on New Window again. Remember, we must save our file first. We can save it as test2.py. Now, on to the coding!<br />
We can solve this by keeping a running total: we'll start with the smallest positive multiple of 3 and go up one multiple at a time keeping track of the sum, stopping once we hit 1000. We can do this with the following code:<br />
<br />
[[File:Idle2-8.png]]<br />
<br />
This is called a while loop. While loops keep iterating until a statement becomes false.<br />
Notice that as you type the above code, the keywords ("while" and "print") will automatically get colored -- this makes the code easier to read. Also, after typing the line "while i < 1000:", the editor will automatically start indenting for you. When you get to the line "print(total)", you'll need to use the backspace key to remove the indentation. It is important that the code look exactly like it does in the screenshot above. Again, in Python, proper indentation is very important!<br />
<br />
This program basically works by incrementing the variable <math>\verb=i=</math> by 3 every time and adding it to the variable <math>\verb=total=</math>. The <math>\verb%+=%</math> operation might be intimidating at first. However, the statement <math>\verb%i += 3%</math> is just a shorthand for <math>\verb%i = i + 3%</math>. (So <math>\verb%a += b%</math> means <math>\verb&a = a + b&</math>.)<br />
<br />
Run your program, and you should get this:<br />
<br />
[[File:Idle2-9.png]]<br />
<br />
Again, the ===RESTART=== line just means that Python is clearing all the work you've previously done before it starts running your program. Then, the program runs and we get our answer, 166833. If you instead get an error message or a different answer, check that your program exactly matches the screenshot above, and try it again.<br />
<br />
Congrats! You have written your first two Python programs!<br />
<br />
=What's Next?=<br />
<br />
Now that you've learned the very basics of getting Python going, there's a bunch of tutorials you can look at which are [http://wiki.python.org/moin/BeginnersGuide/NonProgrammers listed] on the Python website. Go check them out! Another great resource is "Stack Overflow," a forums website built for people who would like to talk about, and get help with programming. It is also recommended that you check out a wiki article discussing more advanced python, namely [[Basic Programming With Python]].<br />
<br />
Or, you can take our Introduction to Programming with Python online course!</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93192
Basic Programming With Python
2018-03-12T21:52:42Z
<p>Bestaops: /* Program Example 5 */ bad wording again</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
count = 0<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
print(count(10000))<br />
</code><br />
<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
:total += count(i)<br />
<br />
print(total)<br />
</code><br />
<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
def count2(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count(i)<br />
:return total<br />
<br />
def count3(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count2(i)<br />
:return total<br />
<br />
print(count3(20))<br />
</code><br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while! Our code isn't that efficient, but the program doesn't take WAY TOO LONG, and we are still learning [[Basic Programming With Python]], so we don't have to worry about it now.<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is so soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93191
Basic Programming With Python
2018-03-12T21:52:22Z
<p>Bestaops: /* Program Example 6 */ fixed bad wording</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
count = 0<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
print(count(10000))<br />
</code><br />
<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
:total += count(i)<br />
<br />
print(total)<br />
</code><br />
<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that they roll <math>a</math> dice <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
def count2(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count(i)<br />
:return total<br />
<br />
def count3(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count2(i)<br />
:return total<br />
<br />
print(count3(20))<br />
</code><br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die each tomorrow, 2 dice each two days from now, 3 dice each three days from now, and so on so that they roll <math>a</math> dice each <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while! Our code isn't that efficient, but the program doesn't take WAY TOO LONG, and we are still learning [[Basic Programming With Python]], so we don't have to worry about it now.<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is so soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93190
Basic Programming With Python
2018-03-12T21:51:38Z
<p>Bestaops: /* Program Example 6 */ congrats added</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
count = 0<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
print(count(10000))<br />
</code><br />
<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
:total += count(i)<br />
<br />
print(total)<br />
</code><br />
<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that they roll <math>a</math> dice <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
def count2(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count(i)<br />
:return total<br />
<br />
def count3(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count2(i)<br />
:return total<br />
<br />
print(count3(20))<br />
</code><br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that they roll <math>a</math> dice <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while! Our code isn't that efficient, but the program doesn't take WAY TOO LONG, and we are still learning [[Basic Programming With Python]], so we don't have to worry about it now.<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is so soft-code programs!<br />
<br />
Congrats on writing a program that is around 25 lines long!</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93189
Basic Programming With Python
2018-03-12T21:47:30Z
<p>Bestaops: /* Program Example */ so close to finishing!!</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example 1===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
===Program Example 2===<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
count = 0<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
<br />
If we run this, we will get a number around 170.<br />
<br />
===Program Example 3===<br />
<br />
'''Simulate the rolling of 10,000 dice. Now, count the amount of times you roll 3. Print that amount out.'''<br />
<br />
We can keep our roll function and our code inside the for loop, but we need to change our for loop statement.<br />
<br />
We can actually soft-code our program more. Let's turn the whole for loop into a function!<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
print(count(10000))<br />
</code><br />
<br />
<br />
If we run this code, it works.<br />
<br />
===Program Example 4===<br />
<br />
'''One of my friends loves rolling dice. He is going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that he rolls <math>a</math> dice <math>a</math> days from now. He gets tired rolling dice after rolling dice for 365 days (so the last day he rolls 365 dice). In Python, simulate this. How many times does he roll 3 after 365 days of rolling dice?'''<br />
<br />
We can use a for loop that calls a function multiple times.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
total = 0<br />
<br />
for i in range(1, 366):<br />
:total += count(i)<br />
<br />
print(total)<br />
</code><br />
<br />
<br />
This is a really long program, but the whole program should make sense if you look at it for a while. We defined our count function in the previous example, and now we are using it with a for loop and a running total. <br />
<br />
You should get a number around 11,000 when you run it. Wow, lots of 3's!<br />
<br />
===Program Example 5===<br />
<br />
'''20 of my friends love rolling dice. They are all going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that they roll <math>a</math> dice <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 20 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
We will have to make our for loop into a function again.<br />
<br />
<br />
<code><br />
import random<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
<br />
def count(amount):<br />
:count_ = 0<br />
:for i in range(1, amount+1):<br />
::if roll() == 3:<br />
:::count_ += 1<br />
:return count_<br />
<br />
def count2(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count(i)<br />
:return total<br />
<br />
def count3(amount)<br />
:total = 0<br />
:for i in range(1, amount + 1):<br />
::total += count2(i)<br />
:return total<br />
<br />
print(count3(20))<br />
</code><br />
<br />
I also made a new function just in case we needed to turn that into a function later.<br />
<br />
'''Make sure''' you read the code carefully and you fully understand it. If you don't understand every single line of code, then you will get confused later on in this article.<br />
<br />
When you run this program, you might be surprised that the answer isn't so big.<br />
<br />
===Program Example 6===<br />
<br />
'''365 of my friends love rolling dice. They are all going to roll 1 die tomorrow, 2 dice two days from now, 3 dice three days from now, and so on so that they roll <math>a</math> dice <math>a</math> days from now. But, one of my friends gets tired very quickly and he only rolls dice for 1 day and stops. Another friend only will roll dice for 2 days, and another will roll dice for three days only, and so on up to the fact that my last friend will roll dice for 365 days. In Python, simulate this. How many times does someone roll 3 after everything?'''<br />
<br />
Because we soft-coded our program so much, all we have to do is change the last line so the parameter of count3() is 365.<br />
<br />
If we run it...we get a big answer, as expected. It also takes quite a while! Our code isn't that efficient, but the program doesn't take WAY TOO LONG, and we are still learning [[Basic Programming With Python]], so we don't have to worry about it now.<br />
<br />
You may not have realized that we soft-coded our program at all, but the whole point of functions is so soft-code programs!</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93188
Basic Programming With Python
2018-03-12T21:14:54Z
<p>Bestaops: /* Simple Program Example */</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example 1====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
====Simple Program Example 2====<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
count = 0<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
<br />
If we run this, we will get a number around 170.</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93139
Basic Programming With Python
2018-03-11T00:17:56Z
<p>Bestaops: /* Program Example */</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example===<br />
<br />
'''Generate a random number from 1 to 6.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
'''Simulate the rolling of 1000 dice. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
count = 0<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
<br />
If we run this, we will get a number around 170.</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Gmaas&diff=93138
Gmaas
2018-03-10T23:53:45Z
<p>Bestaops: /* Known Facts About Gmaas */</p>
<hr />
<div>=== Gmaas Jokes ===<br />
<br />
- Gmaas happened to notice http://artofproblemsolving.com/community/c402403h1598015p9983782 and is not very happy about it.<br />
<br />
-EDIT. Moab33 wuz here.<br />
<br />
- The real reason why AIME cutoffs aren't out yet is because Gmaas refused to grade them due to too much problem misplacement.<br />
<br />
-Gmaas dueled Grumpy Cat and won<br />
<br />
-gmaas sits on the statue of pallas and says Nevermore(the Raven refrence )<br />
<br />
- Gmaas does merely not use USD. He owns it.<br />
<br />
-Gmaas really knows that roblox is awful and does not play it seriously, thank god our lord is sane<br />
<br />
-In 2003, Gmaas used elliptical curves to force his reign over AoPS.<br />
<br />
-"Actually, my name is spelled GMAAS"<br />
<br />
- Gmass is the smartest living being in the universe.<br />
<br />
-Gmass owns all AoPS staff including Richard Rusczyk<br />
<br />
- Gmass's true number of lives left is unknown; however, Gmass recently confirmed that he had at least a million left. Why does Gmass have so many more lives than other cats? The power of Gmass.<br />
<br />
- sseraj once spelled gmaas as gmass on accident in Introduction to Geometry (1532).<br />
<br />
-Gmaas actively plays Roblox, and is a globally ranked professional gamer: https://www.roblox.com/users/29708533/profile...but he hates Roblox.<br />
<br />
-Gmaas has beaten Chuck Norris and The Rock and John Cena all together in a fight.<br />
<br />
-Gmass is a South Korean, North Korean, Palestinian, Israeli, U.S., and Soviet citizen at the same time. EDIT: Gmaas has now been found out to be a citizen of every country in the world. Gmaas seems to enjoy the country of AOPS best, however.<br />
<br />
-"i am sand" destroyed Gmass in FTW<br />
<br />
- sseraj posted a picture of gmaas with a game controller in Introduction to Geometry (1532).<br />
<br />
-Gmaas plays roblox mobile edition and likes Minecraft, Candy Crush, and Club Penguin Rewritten<br />
<br />
-Gmaas is Roy Moore's horse in the shape of a cat<br />
<br />
-Gmaas is a known roblox/club penguin rewritten player and is a legend at it. He has over <math>289547987693</math> robux and <math>190348</math> in CPR.<br />
<br />
-This is all hypothetical EDIT: This is all factual <br />
<br />
-Gmass's real name is Princess. He has a sibling named Rusty/Fireheart/Firestar<br />
(Warrior cats reference)<br />
<br />
- He is capable of salmon powers, according to PunSpark (ask him)<br />
<br />
The Gmaas told Richard Rusczyk to make AoPS<br />
<br />
-The Gmaas is everything. Yes, you are part of the Gmaas-Dw789<br />
<br />
-The Gmaas knows every dimension up to 9999999999999999999999999999999999999999999999999th dimension<br />
<br />
-Certain theories provide evidence that he IS darth plagueis the wise<br />
<br />
-Gmaas is "TIRED OF PEOPLE ADDING TO HIS PAGE!!" (Maas 45).<br />
<br />
-Gmaas has multiple accounts; some of them are pifinity, Lord_Baltimore, Spacehead1AU, squareman, Electro3.0, and lakecomo224<br />
<br />
-Gmaas has a penguin servant named sm24136 who runs GMAASINC. The penguin may or may not be dead. <br />
<br />
-Gmass owns a TARDIS, and can sometimes be seen traveling to other times for reasons unknown.<br />
<br />
- Gmaas is king of the first men, the anduls<br />
<br />
-Gmass is a well known professor at MEOWston Academy<br />
<br />
-Gmass is a Tuna addict, along with other, more potent fish such as Salmon and Trout<br />
<br />
- Gmass won the reward of being cutest and fattest cat ever--he surpassed grumpy cat (He also out grumpied grumpy cat!!!)<br />
<br />
-Last sighting 1571-stretch-algebra-a 12/6/17<br />
<br />
- owner of sseraj, not pet<br />
<br />
- embodiment of life and universe and beyond <br />
<br />
- Watches memes<br />
<br />
-After Death became the GOD OF HYPERDEATH and obtained over 9000 souls <br />
<br />
-Gmass's real name is Pablo Diego JosÃ© Francisco de Paula Juan Nepomuceno MarÃa de los Remedios Cipriano de la SantÃsima Trinidad Ruiz y Picasso [STOP RICK ROLLING. (Source)]<br />
<br />
-Gmass is a certified Slytherin and probably the cutest cat ever.<br />
<br />
-Gmaas once slept on sseraj's private water bed, so sseraj locked him in the bathroom <br />
<br />
-Gmaas has superpowers that allow him to overcome the horrors of Mr. Toilet (while he was locked in the bathroom)<br />
<br />
- Gmaas once sat on an orange on a pile of AoPS books, causing an orange flavored equation explosion.<br />
<br />
-Gmaas once conquered the moon and imprinted his face on it until asteroids came.<br />
<br />
-Gmaas is a supreme overlord who must be given <math>10^{1000000000000000000000^{1000000000000000000000}}</math> minecraft DIAMONDS<br />
<br />
- gmaas is the Doctor Who lord; he sports Dalek-painted cars and eats human finger cheese and custard, plus black holes.<br />
<br />
- Gmaas is 5space's favorite animal. <br />
<br />
- He lives with sseraj. <br />
<br />
-Gmaas is my favorite pokemon<br />
<br />
-Gmaas dislikes number theory but enjoys geometry.<br />
<br />
- Gmaas is cool<br />
<br />
- He is often overfed (with probability <math>\frac{3972}{7891}</math>), or malnourished (with probability <math>\frac{3919}{7891}</math>) by sseraj.<br />
<br />
- He has <cmath>\sum_{k=1}^{267795} [k(k+1)]+GMAAS+GMAAAAAAAS</cmath> supercars, excluding the Purrari and the 138838383 Teslas. <br />
<br />
- He is an employee of AoPS.<br />
<br />
- He is a gmaas with yellow fur and white hypnotizing eyes.<br />
<br />
- He was born with a tail that is a completely different color from the rest of his fur.<br />
<br />
- His stare is very hypnotizing and effective at getting table scraps.<br />
<br />
- He sometimes appears several minutes before certain classes start as an admin. <br />
<br />
- He died from too many Rubik's cubes in an Introduction to Algebra A class, but got revived by the Dark Lord at 00:13:37 AM the next day.<br />
<br />
- It is uncertain whether or not he is a cat, or is merely some sort of beast that has chosen to take the form of a cat (specifically a Persian Smoke.) <br />
<br />
- Actually, he is a cat. He said so. And science also says so.<br />
<br />
- He is distant relative of Mathcat1234.<br />
<br />
- He is very famous now, and mods always talk about him before class starts.<br />
<br />
- His favorite food is AoPS textbooks because they help him digest problems.<br />
<br />
- Gmaas tends to reside in sseraj's fridge.<br />
<br />
- Gmaas once ate all sseraj's fridge food, so sseraj had to put him in the freezer.<br />
<br />
- The fur of Gmaas can protect him from the harsh conditions of a freezer.<br />
<br />
- Gmaas sightings are not very common. There have only been 8 confirmed sightings of Gmaas in the wild.<br />
<br />
- Gmaas is a sage omniscient cat.<br />
<br />
- He is looking for suitable places other than sseraj's fridge to live in.<br />
<br />
- Places where gmaas sightings have happened: <br />
~The Royal Scoop ice cream store in Bonita Beach Florida<br />
<br />
~MouseFeastForCats/CAT 8 Mouse Apartment 1083<br />
<br />
~Alligator Swamp A 1072 <br />
<br />
~Alligator Swamp B 1073<br />
<br />
~Prealgebra A (1488)<br />
<br />
~Introduction to Algebra A (1170)<br />
<br />
~Introduction to Algebra B (1529)<br />
<br />
~Welcome to Panda Town Gate 1076<br />
<br />
~Welcome to Gmaas Town Gate 1221<br />
<br />
~Welcome to Gmaas Town Gate 1125<br />
<br />
~33Â°01'17.4"N 117Â°05'40.1"W (Rancho Bernardo Road, San Diego, CA)<br />
<br />
~The other side of the ice in Antarctica<br />
<br />
~Feisty Alligator Swamp 1115<br />
<br />
~Introduction to Geometry 1221 (Taught by sseraj)<br />
<br />
~Introduction to Counting and Probability 1142 <br />
<br />
~Feisty-ish Alligator Swamp 1115 (AGAIN)<br />
<br />
~Intermediate Counting and Probability 1137<br />
<br />
~Intermediate Counting and Probability 1207<br />
<br />
~Posting student surveys<br />
<br />
~USF Castle Walls - Elven Tribe 1203<br />
<br />
~Dark Lord's Hut 1210<br />
<br />
~AMC 10 Problem Series 1200<br />
<br />
~Intermediate Number Theory 1138<br />
<br />
~Intermediate Number Theory 1476<br />
<br />
~Introduction To Number Theory 1204. Date:7/27/16.<br />
<br />
~Algebra B 1112<br />
<br />
~Intermediate Algebra 1561 7:17 PM 12/11/16<br />
<br />
~Nowhere Else, Tasmania<br />
<br />
~Earth Dimension C-137<br />
<br />
<br />
<br />
- These have all been designated as the most glorious sections of Aopsland now (especially the USF castle walls), but deforestation is so far from threatens the wild areas (i.e. Alligator Swamps A&B).<br />
<br />
- Gmaas has also been sighted in Olympiad Geometry 1148.<br />
<br />
- Gmaas has randomly been known to have sent his minions into Prealgebra 2 1163. However, the danger is passed, that class is over.<br />
<br />
- Gmaas once snuck into sseraj's email so he could give pianoman24 an extension in Introduction to Number Theory 1204. This was 1204 minutes after his sighting on 7/27/16.<br />
<br />
- Gmaas also has randomly appeared on top of the USF's Tribal Bases(he seems to prefer the Void Tribe). However, the next day there is normally a puddle in the shape of a cat's underbelly wherever he was sighted. Nobody knows what this does. <br />
<br />
EDIT: Nobody has yet seen him atop a tribal base yet.<br />
<br />
- Gmaas are often under the disguise of a penguin or cat. Look out for them.<br />
<br />
EDIT: Gmaas rarely disguises himself as a penguin.<br />
<br />
- He lives in the shadows. Is he a dream? Truth? Fiction? Condemnation? Salvation? AoPS site admin? He is all these things and none of them. He is... Gmaas.<br />
<br />
EDIT: He IS an AoPS site admin.<br />
<br />
- If you make yourself more than just a cat... if you devote yourself to an ideal... and if they can't stop you... then you become something else entirely. A LEGEND. Gmaas now belongs to the ages.<br />
<br />
- Is this the real life? Is this just fantasy? No. This is Gmaas, the legend.<br />
<br />
-Aha!! An impostor!! <br />
http://www.salford.ac.uk/environment-life-sciences/research/applied-archaeology/greater-manchester-archaeological-advisory-service<br />
(look at the acronym).<br />
<br />
-EDIT. The above fact is slightly irrelevant.<br />
<br />
- Gmaas might have been viewing (with a <math>\frac{99999.\overline{9}}{100000}</math> chance) the Ultimate Survival Forum. He (or is he a she?) is suspected to be transforming the characters into real life. Be prepared to meet your epic swordsman self someday. If you do a sci-fi version of USF, then prepare to meet your Overpowered soldier with amazing weapons one day.<br />
<br />
- EDIT: Gmaas is a he.<br />
<br />
-Gmaas is love, Gmaas is life<br />
<br />
- The name of Gmaas is so powerful, it radiates Deja Mew.<br />
<br />
- Gmaas is on the list of "Elusive Creatures." If you have questions or want the full list, contact moab33.<br />
<br />
- Gmaas can be summoned using the <math>\tan(90)</math> ritual. Draw a pentagram and write the numerical value of <math>\tan(90)</math> in the middle, and he will be summoned.<br />
<br />
- EDIT: The above fact is incorrect. math101010 has done this and commented with screenshot proof at the below link, and Gmaas was not summoned.<br />
https://artofproblemsolving.com/community/c287916h1291232<br />
<br />
- EDIT EDIT: The above 'proof' is non-conclusive. math101010 had only put an approximation.<br />
<br />
- Gmaas's left eye contains the singularity of a black hole. (Only when everyone in the world blinks at the same time within a nano-nano second.)<br />
<br />
- EDIT: That has never happened and thus it does not contain the singularity of a black hole. <br />
<br />
- Lord Grindelwald once tried to make Gmaas into a Horcrux, but Gmaas's fur is Elder Wand protected and secure, as Kendra sprinkled holly into his fur.<br />
<br />
-Despite common belief, Harry Potter did not defeat Lord Voldemort. Gmaas did.<br />
<br />
- The original owner of Gmaas is Gmaas.<br />
<br />
- Gmaas was not the fourth Peverell brother, but he ascended into a higher being and now he resides in the body of a cat, as he was before. Is it a cat? We will know. (And the answer is YES.)<br />
<br />
- It is suspected that Gmaas may be ordering his cyber hairballs to take the forums, along with microbots.<br />
<br />
- The name of Gmaas is so powerful, it radiates Deja Mu.<br />
<br />
- Gmaas rarely frequents the headquarters of the Illuminati. He was their symbol for one yoctosecond, but soon decided that the job was too low for his power to be wasted on.<br />
<br />
- It has been wondered if Gmaas is the spirit of Obi-Wan Kenobi or Anakin Skywalker in a higher form, due to his strange capabilities and powers.<br />
<br />
- Gmaas has a habit of sneaking into computers, joining The Network, and exiting out of some other computer.<br />
<br />
- It has been confirmed that gmaas uses gmewal as his email service<br />
<br />
- Gmaas enjoys wearing gmean shorts<br />
<br />
- Gmaas has a bright orange tail with hot pink spirals. Or he had for 15 minutes. <br />
<br />
- Gmaas is well known behind his stage name, Michael Stevens (also known as Vsauce XD), or his page name, Purrshanks.<br />
<br />
- Gmaas rekt sseraj at 12:54 June 4, 2016 UTC time zone. And then the Doctor chased him.<br />
<br />
- Gmaas watchers know that the codes above are NOT years. They are secret codes for the place. But if you've edited that section of the page, you know that.<br />
<br />
- Gmaas is a good friend of the TARDIS and the Millenium Falcon. <br />
<br />
- In the Dark Lord's hut, gmaas was seen watching Doctor Who. Anyone who has seem the Dark Lord's hut knows that both Gmaas and the DL (USF code name of the Dark Lord) love BBC. How Gmaas gave him a TV may be lost to history. And it has been lost.<br />
<br />
- The TV has been noticed to be invincible. Many USF weapons, even volcano rings, have tried (and failed) to destroy it. The last time it was seen was on a Kobold display case outside of a mine. The display case was crushed, and a report showed a spy running off with a non-crushed TV.<br />
<br />
-The reason why Dacammel left the USF is that gmaas entrusted his TV to him, and not wanting to be discovered by LF, Cobra, or Z9, dacammel chose to leave the USF, but is regretting it, as snakes keep spawning from the TV.<br />
<br />
- EDIT: The above fact is somewhat irrelevant.<br />
<br />
-EDIT EDIT. Dacammel gave the TV back to gmass, and he left the dark side and their cookies alone. <br />
<br />
- Gmaas is a Super Duper Uper Cat Time Lord. He has <math>57843504</math> regenerations and has used <math>3</math>. <cmath>9\cdot12\cdot2\cdot267794=57843504</cmath>. <br />
<br />
-Gmaas highly enjoys destroying squeaky toys until he finds the squeaky part, then destroys the squeaky part.<br />
<br />
- Gmaas loves to eat turnips. At <math>\frac{13}{32}</math> of the sites he was spotted at, he was seen with a turnip.<br />
<br />
-Gmaas has a secret hidden garden full of turnips under sseraj's house.<br />
<br />
- Gmaas has three tails, one for everyday life, one for special occasions, and one that's invisible.<br />
<br />
-Gmaas is a dangerous creature. If you ever meet him, immediately join his army or you will be killed.<br />
<br />
-Gmaas is in alliance with the Cult of Skaro. How did he get an alliance with ruthless creatures that want to kill everything in sight? Nobody knows. (Except him.)<br />
<br />
-Gmaas lives in Gallifrey and in Gotham City (he has sleepovers with Batman).<br />
<br />
-Gmaas is an excellent driver.<br />
<br />
-The native location of Gmaas is the twilight zone.<br />
<br />
-Donald Trump once sang "All Hail the Chief" to Gmaas, 3 days after being sworn in as US President.<br />
<br />
- Gmaas likes to talk with rrusczyk from time to time.<br />
<br />
- Gmaas can shoot fire from his paws.<br />
<br />
- Gmaas is the reason why the USF has the longest thread on AoPS.<br />
<br />
- He (or she) is an avid watcher of the popular T.V. show "Bernie Sanders and the Gauntlet of DOOM"<br />
<br />
- sseraj, in 1521 Introduction to Number Theory, posted an image of Gmaas after saying "Who wants to see 5space?" at around 5:16 PM Mountain Time, noting Gmaas was "also 5space"<br />
<br />
-EDIT: he also did it in Introduction to Algebra A once<br />
<br />
- Gmaas is now my HD background on my Mac.<br />
<br />
- In 1521 Into to Number Theory, sseraj posted an image of a 5space Gmaas fusion. (First sighting) <br />
<br />
- Also confirmed that Gmaas doesn't like ketchup because it was the only food left the photo.<br />
<br />
- In 1447 Intro to Geometry, sseraj posted a picture of Gmaas with a rubik's cube suggesting that Gmaas's has an average solve time of <math>-GMAAS</math> seconds.<br />
<br />
-Gmass beat Superman in a fight with ease<br />
<br />
-Gmass was an admin of Roblox<br />
<br />
-Gmass traveled around the world, paying so much <math>MONEY</math> just to eat :D<br />
<br />
-Gmaas is a confirmed Apex predator and should not be approached, unless in a domestic form.<br />
Summary:<br />
<br />
-When Gmaas subtracts <math>0.\overline{99}</math> from <math>1</math>, the difference is greater than <math>0</math>.<br />
<br />
-Gmaas was shown to have fallen on Wed Aug 23 2017: https://ibb.co/bNrtmk https://ibb.co/jzUDmk<br />
<br />
-Gmaas died on August ,24, 2017, but fortunately IceParrot revived him after about 2 mins of being dead.<br />
<br />
-The results of the revival are top secret, and nobody knows what happened.<br />
<br />
-sseraj, in 1496 Prealgebra 2, said that Gmaas is Santacat.<br />
<br />
-sseraj likes to post a picture of gmaas in every class he passes by.<br />
<br />
-sseraj posted a picture of gmaas as an Ewok, suggesting he resides on the moon of Endor. Unfortunately, the moon of Ender is also uninhabitable ever since the wreckage of the Death Star changed the climate there. It is thought gmass is now wandering space in search for a home.<br />
EDIT: What evidence is there Endor was affected? Other Ewoks still live there.<br />
<br />
-Gmaas is the lord of the pokemans<br />
<br />
-Gmass can communicate with, and sometimes control any other cats, however this is very rare, as cats normally have a very strong will<br />
<br />
-Picture of Gmass http://i.imgur.com/PP9xi.png<br />
<br />
-Known by Mike Miller<br />
<br />
-Gmaas got mad at sseraj once, so he locked him in his own freezer<br />
<br />
-Then, sseraj decided to eat all of Gmaas's hidden turnips in the freezer as punishment<br />
<br />
-Gmaas is an obviously omnipotent cat.<br />
<br />
-ehawk11 met him<br />
<br />
-sseraj is known to post pictures of Gmaas on various AoPS classrooms. It is not known if these photos have been altered with the editing program called 'Photoshop'.<br />
<br />
-sseraj has posted pictures of gmass in '"intro to algebra", before class started, with the title, "caption contest" anyone who posted a caption mysteriously vanished in the middle of the night. <br />
EDIT: This has happened many times, including in Introduction to Geometry 1533, among other active classes. The person writing this (Poeshuman) did participate, and did not disappear. (You could argue Gmass is typing this through his/her account...)<br />
<br />
- gmass has once slept in your bed and made it wet<br />
<br />
-It is rumored that rrusczyk is actually Gmaas in disguise<br />
<br />
-Gmaas is suspected to be a Mewtwo in disguise<br />
<br />
-Gmaas is a cat but has characteristics of every other animal on Earth.<br />
<br />
-Gmass is the ruler of the universe and has been known to be the creator of the species "Gmassians".<br />
<br />
-There is a rumor that Gmaas is starting a poll<br />
<br />
-Gmaas is a rumored past ThunderClan cat who ran away, founded GmaasClan, then became a kittypet.<br />
<br />
-There is a rumored sport called "Gmaas Hunting" where people try to successfully capture gmaas in the wild with video/camera/eyes. Strangely, no one has been able to do this, and those that have have mysteriously disappeared into the night. Nobody knows why. The person who is writing this(g1zq) has tried Gmaas Hunting, but has never been successful.<br />
<br />
=== Gmaas photos ===<br />
http://cdn.artofproblemsolving.com/images/f/f/8/ff8efef3a0d2eb51254634e54bec215b948a1bba.jpg<br />
<br />
=== gmaas in Popular Culture ===<br />
<br />
- [s]Currently, is being written (by themoocow) about the adventures of gmaas. It is aptly titled, "The Adventures of gmaas".[/s]Sorry, this was a rick roll troll.<br />
<br />
- BREAKING NEWS: tigershark22 has found a possible cousin to gmaas in Raymond Feist's book Silverthorn. They are mountain dwellers, gwali. Not much are known about them either, and when someone asked,"What are gwali?" the customary answer "This is gwali" is returned. Scientist 5space is now looking into it.<br />
<br />
- Sullymath and themoocow are also writing a book about Gmaas<br />
<br />
-Oryx the mad god is actually gmass wearing a suit of armor. This explains why he is never truly killed<br />
<br />
- Potential sighting of gmaas [http://www.gmac.com/frequently-asked-questions/gmass-search-service.aspx]<br />
<br />
- Gmaas has been spotted in some Doctor Who and Phineas and Ferb episodes, such as Aliens of London, Phineas and Ferb Save Summer, Dalek, Rollercoaster, Rose, Boom Town, The Day of The Doctor, Candace Gets Busted, and many more.<br />
<br />
- Gmaas can be found in many places in Plants vs. Zombies Garden Warfare 2 and Bloons TD Battles<br />
<br />
- gmaas was an un-credited actor in the Doctor Who story Knock Knock, playing a Dryad. How he shrunk, we will never know.<br />
<br />
-oadaegan is also writing a story about him. He is continuing the book that was started by JpusheenS. when he is done he will post it here<br />
<br />
-Gmaas is a time traveler from 0.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 B.C.<br />
<br />
-No one knows if Gmass is a Mr. mime in a cat skin, the other way around, or just a downright combination of both.<br />
<br />
-In it, it mentions these four links as things Gmass is having trouble (specifically technical difficulties). What could it mean? Links:<br />
https://docs.google.com/document/d/1NZ0XcFYm80sA-fAoxnm7ulMCwdNU75Va_6ZjRHfSHV0<br />
https://docs.google.com/document/d/1ELN7ORauFFv1dwpU_u-ah_dFJHeuJ3szYxoeC1LlDQg/<br />
https://docs.google.com/document/d/1oy9Q3F7fygHw-OCWNEVE8d-Uob2dxVACFcGUcLmk3fA<br />
https://docs.google.com/document/d/1jzb9Q6FmDmrRyXwnik3e0sYw5bTPMo7aBwugmUbA13o<br />
<br />
<br />
- Another possible Gmaas sighting [https://2017.spaceappschallenge.org/challenges/warning-danger-ahead/and-you-can-help-fight-fires/teams/gmaas/project]<br />
<br />
-<math>Another</math> sighting? [https://www.radarbox24.com/data/flights/GMAAS]<br />
<br />
-Gmaas has been sighted several times on the Global Announcements forum<br />
<br />
-Gmaas uses the following transportation: [img]http://cdn.artofproblemsolving.com/images/3/6/8/368da4e615ea3476355ee3388b39f30a48b8dd48.jpg[/img]<br />
<br />
- When Gmaas was mad, he started world wars 1 & 2. It is only because of Gmaas that we have not had World War 3.<br />
<br />
- Gmaas is the only cat to have been proved irrational and transcendental, though we suspect all cats fall in the first category.</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93133
Basic Programming With Python
2018-03-10T23:28:30Z
<p>Bestaops: /* Understanding Functions */</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
====Simple Program Example====<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example===<br />
<br />
'''Simulate the rolling of a die.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
'''Simulate the rolling of 1000 dice. Do not print anything out. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
count = 0<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
<br />
If we run this, we will get a number around 170.</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93132
Basic Programming With Python
2018-03-10T23:27:42Z
<p>Bestaops: /* Program Example 2 */ minor edit</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a super super huge number that has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example===<br />
<br />
'''Simulate the rolling of a die.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
'''Simulate the rolling of 1000 dice. Do not print anything out. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
count = 0<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
<br />
If we run this, we will get a number around 170.</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93131
Basic Programming With Python
2018-03-10T23:26:02Z
<p>Bestaops: grammatical error</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install Python, look [[Getting Started With Python Programming|here]].<br />
<br />
<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a number so huge that if you have a low end PC, '''your Python might give a MemoryError. If that happens, don't worry about it.'''<br />
<br />
Here's the huge number:<br />
<br />
13587297631464779828575459193700511069135921009091375432890427471255548348541111505004724234140958867581538<br />
4544700095575139880300450300332667952300124312659454107787172869140994734083903393051401716252405338977923<br />
676705927084707669679384028974201372990703503147805423115466316373869490975200336396233735355502238744775<br />
9891969359740267436823768225701073970877427245902169001057267419452765441119054450438245054272985286180533<br />
797417127792755022040372823510595936398640365376868040870762323395254152264821642444071107668433903396506<br />
289607562793460087999004181940101666490177708306438875083164991066701839035438073287566335639223504397929<br />
4341625047852720259316143744829000868294255892155754941579915306846855602120470899115742390753069716079536<br />
554155840959042366798572487573335616432239739041473401428518140909461479933849445336033056039568470375624<br />
172123108054962032236304381550477478287376384.<br />
<br />
That number has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example===<br />
<br />
'''Simulate the rolling of a die.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
'''Simulate the rolling of 1000 dice. Do not print anything out. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
count = 0<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
<br />
If we run this, we will get a number around 170.</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93130
Basic Programming With Python
2018-03-10T23:25:29Z
<p>Bestaops: /* Random */ added section header</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install python, look [[Getting Started With Python Programming|here]].<br />
<br />
<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a number so huge that if you have a low end PC, '''your Python might give a MemoryError. If that happens, don't worry about it.'''<br />
<br />
Here's the huge number:<br />
<br />
13587297631464779828575459193700511069135921009091375432890427471255548348541111505004724234140958867581538<br />
4544700095575139880300450300332667952300124312659454107787172869140994734083903393051401716252405338977923<br />
676705927084707669679384028974201372990703503147805423115466316373869490975200336396233735355502238744775<br />
9891969359740267436823768225701073970877427245902169001057267419452765441119054450438245054272985286180533<br />
797417127792755022040372823510595936398640365376868040870762323395254152264821642444071107668433903396506<br />
289607562793460087999004181940101666490177708306438875083164991066701839035438073287566335639223504397929<br />
4341625047852720259316143744829000868294255892155754941579915306846855602120470899115742390753069716079536<br />
554155840959042366798572487573335616432239739041473401428518140909461479933849445336033056039568470375624<br />
172123108054962032236304381550477478287376384.<br />
<br />
That number has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
===Program Example===<br />
<br />
'''Simulate the rolling of a die.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
'''Simulate the rolling of 1000 dice. Do not print anything out. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
count = 0<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
<br />
If we run this, we will get a number around 170.</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93129
Basic Programming With Python
2018-03-10T23:24:23Z
<p>Bestaops: /* Random */ fixed bugs</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install python, look [[Getting Started With Python Programming|here]].<br />
<br />
<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a number so huge that if you have a low end PC, '''your Python might give a MemoryError. If that happens, don't worry about it.'''<br />
<br />
Here's the huge number:<br />
<br />
13587297631464779828575459193700511069135921009091375432890427471255548348541111505004724234140958867581538<br />
4544700095575139880300450300332667952300124312659454107787172869140994734083903393051401716252405338977923<br />
676705927084707669679384028974201372990703503147805423115466316373869490975200336396233735355502238744775<br />
9891969359740267436823768225701073970877427245902169001057267419452765441119054450438245054272985286180533<br />
797417127792755022040372823510595936398640365376868040870762323395254152264821642444071107668433903396506<br />
289607562793460087999004181940101666490177708306438875083164991066701839035438073287566335639223504397929<br />
4341625047852720259316143744829000868294255892155754941579915306846855602120470899115742390753069716079536<br />
554155840959042366798572487573335616432239739041473401428518140909461479933849445336033056039568470375624<br />
172123108054962032236304381550477478287376384.<br />
<br />
That number has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
'''Simulate the rolling of a die.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
'''Simulate the rolling of 1000 dice. Do not print anything out. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<br />
<code><br />
<br />
import random<br />
<br />
count = 0<br />
<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
<br />
If we run this, we will get a number around 170.</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93128
Basic Programming With Python
2018-03-10T23:23:42Z
<p>Bestaops: /* Random */ added section contents</p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install python, look [[Getting Started With Python Programming|here]].<br />
<br />
<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a number so huge that if you have a low end PC, '''your Python might give a MemoryError. If that happens, don't worry about it.'''<br />
<br />
Here's the huge number:<br />
<br />
13587297631464779828575459193700511069135921009091375432890427471255548348541111505004724234140958867581538<br />
4544700095575139880300450300332667952300124312659454107787172869140994734083903393051401716252405338977923<br />
676705927084707669679384028974201372990703503147805423115466316373869490975200336396233735355502238744775<br />
9891969359740267436823768225701073970877427245902169001057267419452765441119054450438245054272985286180533<br />
797417127792755022040372823510595936398640365376868040870762323395254152264821642444071107668433903396506<br />
289607562793460087999004181940101666490177708306438875083164991066701839035438073287566335639223504397929<br />
4341625047852720259316143744829000868294255892155754941579915306846855602120470899115742390753069716079536<br />
554155840959042366798572487573335616432239739041473401428518140909461479933849445336033056039568470375624<br />
172123108054962032236304381550477478287376384.<br />
<br />
That number has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
<br />
<br />
In this step, we added a parameter in both functions. We also soft-coded our program even more! Hooray!<br />
<br />
All integers from 34 to 99 work.<br />
<br />
===Program Example 4===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>12x</math> is a positive integer from 500 to 900.'''<br />
<br />
This problem may look a bit different from the other ones, but it really is the same thing, except that the factor is 12 and check_min and check_max are 500 and 900, respectively.<br />
<br />
Once we change the final print_check line to satisfy our needs, we can run our program.<br />
<br />
All numbers from 42 to 75 work!<br />
<br />
Congrats! You have written your first programs above 10 lines of code!<br />
<br />
==Random==<br />
<br />
There is a package in Python that allows the use of random numbers.<br />
<br />
'''Simulate the rolling of a die.'''<br />
<br />
Easy peasy. We will just generate a random number from 1 to 6 with the package like this:<br />
<br />
<br />
<code><br />
<br />
import random<br />
print(random.randint(1,6))<br />
</code><br />
<br />
<br />
As you can see, when you run this program, you get a random number from 1 to 6.<br />
<br />
'''Simulate the rolling of 1000 dice. Do not print anything out. Now, count the amount of times you roll 6. Print that amount out.'''<br />
<br />
We can create a function that returns a random number from 1 to 6. Then, we can make a for loop that rolls the dice 1000 times and check if it is a 6.<br />
<br />
<code><br />
<br />
import random<br />
count = 0<br />
def roll():<br />
:return random.randint(1,6)<br />
for i in range(1, 1001):<br />
:if roll() == 6:<br />
::count += 1<br />
print(count)<br />
</code><br />
<br />
If we run this, we will get a number around 170.</div>
Bestaops
https://artofproblemsolving.com/wiki/index.php?title=Basic_Programming_With_Python&diff=93126
Basic Programming With Python
2018-03-10T23:13:04Z
<p>Bestaops: </p>
<hr />
<div>'''Important: It is extremely recommended that you read [[Getting Started With Python Programming]] before reading this unless you already know some programming knowledge.'''<br />
<br />
This article will talk about some basic Python programming. If you don't even know how to install python, look [[Getting Started With Python Programming|here]].<br />
<br />
<br />
<br />
==Loops==<br />
<br />
There are two different kinds of loops in Python: the for loop and the while loop.<br />
<br />
===The For Loop===<br />
<br />
The for loop iterates over a list, or an array, of objects. You have probably seen this code before:<br />
<br />
[[File:Capture.PNG|200px]]<br />
<br />
This for loop iterates over the list of integers from 1 to 51, excluding the 51 and including the 1. That means it is a list from 1 to 50, inclusive. On every iteration, Python will print the number that the loop is iterating through. <br />
<br />
For example, in the first iteration, i = 1, so Python prints 1.<br />
<br />
In the second iteration, i = 2, so Python prints 2.<br />
<br />
This continues so on until the number, 50, is reached. Therefore, the last number Python will print out is 50.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^{n}.</math>'''<br />
<br />
To do this task, we must create a for loop and loop over the integers from 1 to 50 inclusive:<br />
<br />
<br />
<code><br />
for i in range(1,51):<br />
</code><br />
<br />
<br />
Now what? We must keep a running total and increase it by <math>2^i</math> every time:<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
</code><br />
<br />
<br />
We must not forget to print the total at the end!<br />
<br />
<br />
<code><br />
total = 0<br />
<br />
for i in range(1,51):<br />
:total += 2**i<br />
print(total)<br />
</code><br />
<br />
<br />
You must exit out of the for loop one you reach the print(total) line by pressing backspace.<br />
<br />
Once you run your program, you should get an answer of <math>\boxed{2,251,799,813,685,246.}</math><br />
<br />
===The While Loop===<br />
<br />
While loops don't loop over a list. They loop over and over and over...'''until'''...a condition becomes false.<br />
<br />
<br />
<code><br />
i = 3<br />
<br />
total = 0<br />
<br />
while i < 1000:<br />
:total += i<br />
:i += 3<br />
print(total)<br />
</code><br />
<br />
<br />
In this code, the while loop loops 333 times, until i becomes greater than or equal to 1000.<br />
<br />
====Program Example====<br />
<br />
'''Find <math>\sum_{n=1}^{50} 2^n</math> using a while loop.'''<br />
<br />
We must create a while loop that will iterate until n is greater than <math>50.</math><br />
<br />
<br />
<code><br />
n = 1<br />
<br />
total = 0<br />
<br />
while n <= 50:<br />
:total += 2**n<br />
:n += 1<br />
print(total)<br />
</code><br />
<br />
<br />
We must not forget to include the n += 1 line at the end of the while loop! <br />
<br />
If we run this, we will get the same answer as last time, <math>2,251,799,813,685,246.</math><br />
<br />
==Functions==<br />
<br />
In this section, we will define new operations and do arithmetic with them in Python.<br />
<br />
===The New Operation===<br />
Let's say that you defined a new binary operation, the <math>\uparrow \downarrow.</math> You want it to be so <math>a \uparrow \downarrow b = a^{b}b^{a}.</math> Therefore, <math>1\uparrow \downarrow 2 = 1^{2}2^{1}=1\cdot 2= 2,</math> and <math>2\uparrow \downarrow 3 = 2^33^2 = 8\cdot 9 = 72.</math> Let's call this operation an '''up down arrow.'''<br />
<br />
===Program Example 1===<br />
<br />
'''Find <math>[2 \uparrow \downarrow (1 \uparrow \downarrow 2)] \uparrow \downarrow 2.</math>'''<br />
<br />
We know this will be a big number, so we should write a program to do it! We certainly don't want to do the exponentiation and multiplication every time we use the operation in our program, and that's where functions come in! Functions can take in parameters (<math>a</math> and <math>b</math>) and return a result depending on the parameters.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
</code><br />
<br />
<br />
Above is the code to define our function. We need to print the final result at the end, so we must put a print statement at the end.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b): <br />
:return ((a**b) * (b**a))<br />
print(up_down_arrow(up_down_arrow(2,up_down_arrow(1,2)),2))<br />
</code><br />
<br />
<br />
All those nested up_down_arrow's might be confusing at first, but it really isn't that confusing.<br />
If you run your program, you should get your answer: <math>16,777,216.</math> <br />
<br />
You might be surprised that the answer is so big. If you actually start calculating the real answer without a program, you will really quickly find that the final result is <math>16 \uparrow \downarrow 2,</math> which does turn out to be 16,777,216 if you use a calculator.<br />
<br />
Let's make another operation!<br />
<br />
We will define the operation <math>\uparrow \downarrow \leftarrow \rightarrow</math> to be called '''all around.''' <math>a \uparrow \downarrow \leftarrow \rightarrow b = (ab(a \uparrow \downarrow b))^2.</math> That's an operation that will make really big numbers!<br />
<br />
===Program Example 2===<br />
<br />
'''Find 87 all around 132.'''<br />
<br />
The answer is bound to be a huge number, so we must make a program to solve it.<br />
<br />
We will keep our up_down_arrow function because in the definition of our all_around function we will use it. Then, we will define the all_around function.<br />
<br />
<br />
<code><br />
<br />
def up_down_arrow(a,b):<br />
:return ((a**b) * (b**a))<br />
def all_around(a,b):<br />
:return ((a * b * up_down_arrow(a,b)) ** 2)<br />
</code><br />
<br />
<br />
We must print all_around(87,132) at the end. Once we do that, and we run our program, we get a number so huge that if you have a low end PC, '''your Python might give a MemoryError. If that happens, don't worry about it.'''<br />
<br />
Here's the huge number:<br />
<br />
13587297631464779828575459193700511069135921009091375432890427471255548348541111505004724234140958867581538<br />
4544700095575139880300450300332667952300124312659454107787172869140994734083903393051401716252405338977923<br />
676705927084707669679384028974201372990703503147805423115466316373869490975200336396233735355502238744775<br />
9891969359740267436823768225701073970877427245902169001057267419452765441119054450438245054272985286180533<br />
797417127792755022040372823510595936398640365376868040870762323395254152264821642444071107668433903396506<br />
289607562793460087999004181940101666490177708306438875083164991066701839035438073287566335639223504397929<br />
4341625047852720259316143744829000868294255892155754941579915306846855602120470899115742390753069716079536<br />
554155840959042366798572487573335616432239739041473401428518140909461479933849445336033056039568470375624<br />
172123108054962032236304381550477478287376384.<br />
<br />
That number has over 800 digits!<br />
<br />
===Understanding Functions===<br />
<br />
Every single function has a '''return value'''. If a function does not return anything, the return value is '''null'''. Null is a term used in programming as a placeholder that stands for nothing.<br />
<br />
'''Define a function that adds 1 to an input.'''<br />
<br />
How will the function know what number to add 1 to? We will input a '''parameter''' for the function to add 1 to.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
</code><br />
<br />
<br />
In this function, <math>x</math> is the parameter.<br />
<br />
<br />
<code><br />
<br />
def add_one(x):<br />
:return x + 1<br />
print(add_one(2))<br />
</code><br />
<br />
<br />
In the print statement, we set <math>x</math> as 2, and the function returns <math>2 + 1 = 3,</math> so the program prints <math>3</math>.<br />
<br />
'''Define a function that prints out an input.'''<br />
<br />
We will use a parameter again.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
</code><br />
<br />
<br />
Uh oh! We have nothing to return! Therefore, we will return nothing (or null), by just writing return.<br />
<br />
<br />
<code><br />
<br />
def print_function(x):<br />
:print(x)<br />
:return<br />
print_function("print_function")<br />
</code><br />
<br />
This code prints out print_function. print_function() is said to be '''called''' in the final line of the code. Again, we set <math>x</math>, our parameter, as "print_function."<br />
<br />
==Flow==<br />
<br />
Flow consists of if statements, elif (else if) statements, and else statements.<br />
<br />
*An if statement checks if a comparison is true.<br />
<br />
*An else statement checks if a comparison is not true. It is used after an if statement (and all elif statements after the if statement) and it shares the same comparison as the if statement.<br />
<br />
*An elif statement checks for two things: if a comparison is true, and if a comparison is not true. It is used right after the if statement.<br />
<br />
===Program Example===<br />
<br />
'''Does the number 10 have the property that when you multiply 10 by 5, you get a two digit number?'''<br />
<br />
This problem is super easy to solve without a program, but let's write a program to solve this anyway. We will use an if statement to check if <math>10\cdot 5</math> is less than 100 and greater than 9.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9:<br />
:if 10*5 < 100:<br />
::print("Yes")<br />
:else:<br />
::print("No")<br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code means, if 10*5 > 9, then we will check if it is less than 100. If it is not greater than 9, however, we will print No. If it is greater than 9, we check if it is less than 100. If it is, we print Yes. If it isn't we print No.<br />
<br />
These nested if statements can be very confusing. Luckily, there is a faster an easier way to do this.<br />
<br />
<br />
<code><br />
<br />
if 10*5 > 9 and 10*5 < 100:<br />
:print("Yes") <br />
else:<br />
:print("No")<br />
</code><br />
<br />
<br />
This code checks for the two conditions at the same time. If we run it, we get our answer of Yes.<br />
<br />
==Booleans==<br />
<br />
===Program Example===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a two digit positive integer.'''<br />
<br />
We can create a function with our previous code.<br />
<br />
We will have to slightly modify our function so we can use it in a for loop at the end:<br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
</code><br />
<br />
<br />
True and False are what are called '''booleans'''. When an if or elif statement receives True, the code inside of the statement happens. When an if or elif statement receives False, the code inside of the statement does not happen. <br />
<br />
We must create a for loop that will iterate through all two digit positive integers. <br />
<br />
<br />
<code><br />
<br />
def check(a):<br />
:if a*5 > 9 and a*5 < 100:<br />
::return True <br />
:else:<br />
::return False<br />
for i in range(10,100):<br />
:if check(i):<br />
::print(i)<br />
</code><br />
<br />
<br />
The final for loop checks if <math>5i</math> is a two digit integer. If it is, the function returns True and the code inside the if statement gets run. If it isn't, the function returns False and the code inside the if statement gets ignored.<br />
<br />
If we run this, we will get the answer.<br />
<br />
All two digit integers from 10 to 19 inclusive work!<br />
<br />
==Soft Coding Programs==<br />
<br />
In the next few examples, you will see why hard coding programs is bad.<br />
<br />
===Program Example 1===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can keep our code and modify some parts of it.<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max):<br />
:if a*5 > min - 1 and a*5 < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999)<br />
</code><br />
<br />
<br />
Why did we add so many functions?<br />
<br />
Well, if the numbers in a problem change (and the words stay the same), and you need to change a lot of numbers in your program, your program is considered '''hard-coded'''. We want our programs to be as '''soft-coded''' as possible. In our new program, we only need to change 4 numbers (in the print_check() statement) if the numbers in the problem change. Therefore, our program is relatively soft-coded. There are still ways to soft-code this program even more, though.<br />
<br />
If we run our program, we get our answer.<br />
<br />
All numbers from 20 to 99 work!<br />
<br />
===Program Example 2===<br />
<br />
'''Print all three digit positive integers <math>x</math> such that <math>5x</math> is a three digit positive integer.'''<br />
<br />
We can just change the print_check line at the end to<br />
<br />
<br />
<code><br />
<br />
print_check(100, 999, 100, 999)<br />
</code><br />
<br />
<br />
and our program will be ready to be run.<br />
<br />
All numbers from 100 to 199 work.<br />
<br />
===Program Example 3===<br />
<br />
'''Print all two digit positive integers <math>x</math> such that <math>3x</math> is a three digit positive integer.'''<br />
<br />
Uh oh. Only changing the print_check line won't work. We will need to change our functions!<br />
<br />
<br />
<code><br />
<br />
def check(a, min, max, factor):<br />
:if a*factor > min - 1 and a*factor < max + 1:<br />
::return True <br />
:else:<br />
::return False<br />
<br />
def print_check(range_min, range_max, check_min, check_max, check_factor):<br />
:for i in range(range_min, range_max + 1):<br />
::if check(i, check_min, check_max, check_factor):<br />
:::print(i)<br />
:return<br />
<br />
print_check(10, 99, 100, 999, 3)<br />
</code><br />
&