Uploaded by Dimitris Tesias

Principles of Programming 1 - Code

advertisement
9/2/22, 4:51 PM
Programming_Priciples1
Step 1: Issuing an instruction
In the command window we give the instruction and the computer returns the result right after it! In
the following example, the instruction is about the computer displaying a specific message.
In [1]:
print("Hi there!")
Hi there!
Make the code easy-to-read: Comments
Computers need some special way to determine that the text you’re writing is a comment, not code
to execute. Python provides two methods of defining text as a comment and not as code. The first
method is the single-line comment. It uses the number sign (#), like this:
In [2]:
# This is a comment.
print("Hello from Python!") #This is also a comment.
Hello from Python!
A single-line comment can appear on a line by itself or it can appear after executable code. It
appears on only one line. You typically use a single-line comment for short descriptive text, such as
an explanation of a particular bit of code. When you need to create a longer comment, you use a
multiline comment. A multiline comment both starts and ends with three double quotes ("""), like
this:
In [3]:
"""
Application: ShowComments.py
Written by: George
Purpose: Shows how to use comments.
"""
Application: ShowComments.py\n
Out[3]: '\n
se comments.\n'
Written by: George\n
Purpose: Shows how to u
Everything between the two sets of triple double quotes is considered a comment. You typically use
multiline comments for longer explanations of who created an application, why it was created, and
what tasks it performs. Of course, there aren’t any hard rules on precisely how you use comments.
The main goal is to tell the computer precisely what is and isn’t a comment so that it doesn’t
become confused.
Even though single-line and multiline comments are both comments, the IDLE editor makes it easy
to tell the difference between the two. When you’re using the default color scheme, single-line
comments show up in red text, while multiline comments show up in green text. Python doesn’t
care about the coloration; it’s only there to help you as the developer.
We use comments to leave yourself reminders, to explain the code to others, or to "comment-out" a
part of the code when debugging it!
localhost:8889/lab/tree/Principles of Programming/Programming_Priciples1.ipynb
1/19
9/2/22, 4:51 PM
In [4]:
Programming_Priciples1
print("Hi!")
# print("I didn't mean it!")
Hi!
Storing and Modifying Information
In order to make information useful, we have to have some means of storing it permanently.
Otherwise, every time we turn the computer off, all our information will be gone and the computer
will provide limited value. In addition, Python must provide some rules for modifying information.
This section is about controlling information — defining how information is stored permanently and
manipulated by applications we create.
Storing Information
An application requires fast access to information or else it will take a long time to complete tasks.
As a result, applications store information in memory. However, memory is temporary. When you
turn off the machine, the information must be stored in some permanent form, such as on your hard
drive, a Universal Serial Bus (USB) flash drive, or a Secure Digital (SD) card. In addition, you must also
consider the form of the information, such as whether it’s a number or text. The following sections
discuss the issue of storing information as part of an application in more detail.
Seeing variables as storage boxes
When working with applications, we store information in variables. A variable is a kind of storage
box. Whenever we want to work with the information, you access it using the variable. If we have
new information we want to store, we put it in a variable. Changing information means accessing
the variable first and then storing the new value in the variable. Just as we store things in boxes in
the real world, so we store things in variables (a kind of storage box) when working with
applications. Computers are actually pretty tidy. Each variable stores just one piece of information.
Using this technique makes it easy to find the particular piece of information we need.
Using the right box to store the data
Python uses specialized variables to store information to make things easy for the programmer and
to ensure that the information remains safe. However, computers don’t actually know about
information types. All that the computer knows about are 0s and 1s, which is the absence or
presence of a voltage. At a higher level, computers do work with numbers, but that’s the extent of
what computers do. Numbers, letters, dates, times, and any other kind of information you can think
about all come down to 0s and 1s in the computer system. For example, the letter A is actually
stored as 01000001 or the number 65. The computer has no concept of the letter A or of a date
such as 8/31/2014.
Defining the Essential Python Data Types
Every programming language defines variables that hold specific kinds of information, and Python is
no exception. The specific kind of variable is called a data type. Knowing the data type of a variable
localhost:8889/lab/tree/Principles of Programming/Programming_Priciples1.ipynb
2/19
9/2/22, 4:51 PM
Programming_Priciples1
is important because it tells you what kind of information you find inside. In addition, when you
want to store information in a variable, you need a variable of the correct data type to do it. For
instance, Python doesn’t allow you to store text in a variable designed to hold numeric information.
Doing so would damage the text and cause problems with the application. You can generally classify
Python data types as numeric, string, and Boolean, although there really isn’t any limit on just how
you can view them. The following sections describe each of the standard Python data types within
these classifications.
Putting information into variables
To place a value into any variable, you make an assignment using the assignment operator (=). For
example, to place the number 5 into a variable named myVar, you type myVar = 5 and press Enter at
the Python prompt. Even though Python doesn’t provide any additional information to you, you can
always type the variable name and press Enter to see the value it contains.
In [5]:
In [6]:
myVar = 5
myVar
Out[6]: 5
We can also retrieve the value of this variable, or update it.
In [7]:
myVar = myVar + 3.0; myVar
Out[7]: 8.0
Understanding the numeric types
Humans tend to think about numbers in general terms. We view 1 and 1.0 as being the same
number — one of them simply has a decimal point. However, as far as we’re concerned, the two
numbers are equal and we could easily use them interchangeably. Python views them as being
different kinds of numbers because each form requires a different kind of processing. The following
sections describe the integer, floating-point, and complex number classes of data types that Python
supports.
Integers
Any whole number is an integer. For example, the value 1 is a whole number, so it’s an integer. On
the other hand, 1.0 isn’t a whole number; it has a decimal part to it, so it’s not an integer. Integers
are represented by the int data type. Integers can be arbitrarily large.
In [8]:
googol = 10 ** 100
googol
Out[8]: 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000
localhost:8889/lab/tree/Principles of Programming/Programming_Priciples1.ipynb
3/19
9/2/22, 4:51 PM
Programming_Priciples1
Even though that’s a really large number, it isn’t infinite. However, it can take lots of memory to
store it.
In [9]:
googol.bit_length()
Out[9]: 333
When working with the int type, you have access to a number of interesting features. One feature is
the ability to use different numeric bases: To tell Python when to use bases other than base 10, you
add a 0 and a special letter to the number. For example, 0b100 is the value one-zero-zero in base 2.
Here are the letters you normally use: ✓ b: Base 2 ✓ o: Base 8 ✓ x: Base 16 It’s also possible to
convert numeric values to other bases using the bin(), oct(), and hex() commands. So, putting
everything together, you can see how to convert between bases using the commands shown in
Figure 5-2. Try the command shown in the figure yourself so that you can see how the various bases
work. Using a different base actually makes things easier in many situations, and you’ll encounter
some of those situations later in the book. For now, all you really need to know is that integers
support different numeric bases.
In [10]:
abin = 0b100; abin
Out[10]: 4
The built-in function type provides type information for all objects with standard and built-in types
as well as for newly created ones. There is a saying that “everything in Python is an object.” This
means, for example, that even simple objects like the int object just defined have built-in methods.
For example, one can get the number of bits needed to represent the int object in memory by
calling the method bit_length():
In [11]:
type(abin)
Out[11]: int
The binary representation shows the actual memory needs!
In [12]:
abin.bit_length()
Out[12]: 3
Let's look at an integer with a base8 represenation. 100 in the base8 represenation is actually 64 in
the decimal one.
In [13]:
aoct = 0o100; aoct
Out[13]: 64
If we translate it to binary one, we do see how many bits it takes for its storage.
localhost:8889/lab/tree/Principles of Programming/Programming_Priciples1.ipynb
4/19
9/2/22, 4:51 PM
In [14]:
Programming_Priciples1
bin(aoct)
Out[14]: '0b1000000'
In [15]:
aoct.bit_length()
Out[15]: 7
In [16]:
adec = 100; adec
Out[16]: 100
In [17]:
bin(adec)
Out[17]: '0b1100100'
In [18]:
ahex = 0x100; ahex
Out[18]: 256
In [19]:
oct(ahex)
Out[19]: '0o400'
Arithmetic operations on integers are also easy to implement:
In [20]:
In [21]:
a = 1; b = 3; c = a + b
c
Out[21]: 4
In [22]:
type(c)
Out[22]: int
In [23]:
d = a/b; d
Out[23]: 0.3333333333333333
Without necessarily resulting in the same type.
In [24]:
type(d)
Out[24]: float
localhost:8889/lab/tree/Principles of Programming/Programming_Priciples1.ipynb
5/19
9/2/22, 4:51 PM
Programming_Priciples1
Floating-point values
Any number that includes a decimal portion is a floating-point value. For example, 1.0 has a decimal
part, so it’s a floating-point value. Many people get confused about whole numbers and floatingpoint numbers, but the difference is easy to remember. If you see a decimal in the number, then it’s
a floatingpoint value. Python stores floating-point values in the float data type. Floating-point
values have an advantage over integer values in that you can store immensely large or incredibly
small values in them. When working with floating-point values, you can assign the information to
the variable in a number of ways. The two most common methods are to provide the number
directly and to use scientific notation. When using scientific notation, an e separates the number
from its exponent. Notice that using a negative exponent results in a fractional value.
In [25]:
af = 255; af
Out[25]: 255
In [26]:
type(af)
Out[26]: int
In [27]:
af2 = 25.5e1; af2
Out[27]: 255.0
In [28]:
type(af)
Out[28]: int
In [29]:
af3 = 25500e-2; af3
Out[29]: 255.0
Expressions involving a float also return a float object in general
In [30]:
type (1. / 4)
Out[30]: float
A float is a bit more involved in that the computerized representation of rational or real numbers is
in general not exact and depends on the specific technical approach taken. To illustrate what this
implies, let us define another float object, b. float objects like this one are always represented
internally up to a certain degree of accuracy only. This becomes evident when adding 0.1 to b:
In [31]:
b = 0.35
type(b)
localhost:8889/lab/tree/Principles of Programming/Programming_Priciples1.ipynb
6/19
9/2/22, 4:51 PM
Programming_Priciples1
Out[31]: float
In [32]:
b + 0.1
Out[32]: 0.44999999999999996
The reason for this is that float objects are internally represented in binary format; that is, a decimal
number 0 < n < 1 is represented by a series of the form n = x/2 + y/4 + z/8 + .... For certain
floating-point numbers the binary representation might involve a large number of elements or
might even be an infinite series. However, given a fixed number of bits used to represent such a
number inaccuracies are the consequence. Other numbers can be represented perfectly and are
therefore stored exactly even with a finite number of bits available. Consider the following example:
In [33]:
c = 0.5
c.as_integer_ratio()
Out[33]: (1, 2)
One-half, i.e., 0.5, is stored exactly because it has an exact (finite) binary representation as 0.5 = 1/2 .
However, for b = 0.35 one gets something different than the expected rational number 0.35 = 7/20 :
In [34]:
b.as_integer_ratio()
Out[34]: (3152519739159347, 9007199254740992)
The precision is dependent on the number of bits used to represent the number. In general, all
platforms that Python runs on use the IEEE 754 double-precision standard — i.e., 64 bits — for
internal representation. This translates into a 15-digit relative accuracy. This kind of error can be
devastating if it involves space travel for example...
Complex numbers
Python is one of the few languages that provides a built-in data type to support complex numbers.
The imaginary part of a complex number always appears with a j after it. So, if we want to create a
complex number with 3 as the real part and 4 as the imaginary part, we make an assignment like
this:
In [35]:
myComplex = 3 + 4j
To see the real part of the variable, we simply type myComplex.real at the Python prompt and press
Enter. Likewise, to see the imaginary part of the variable, we type myComplex.imag at the Python
prompt and press Enter. These return the some of the variables properties!!
In [36]:
myComplex.real
Out[36]: 3.0
localhost:8889/lab/tree/Principles of Programming/Programming_Priciples1.ipynb
7/19
9/2/22, 4:51 PM
In [37]:
Programming_Priciples1
myComplex.imag
Out[37]: 4.0
Understanding Boolean values
A computer will never provide “maybe” as output. Every answer you get is either True or False. In
fact, there is an entire branch of mathematics called Boolean algebra that was originally defined by
George Boole that computers rely upon to make decisions. Contrary to common belief, Boolean
algebra has existed since 1854 — long before the time of computers.
When using Boolean value in Python, we rely on the bool type. A variable of this type can contain
only two values: True or False. We can assign a value by using the True or False keywords, or we can
create an expression that defines a logical idea that equates to true or false. For example, we could
say, myBool = 1 > 2, which would equate to False because 1 is most definitely not greater than 2.
In [38]:
myBool = True ; myBool
Out[38]: True
In [39]:
myBool2 = 1 < 2; myBool2
Out[39]: True
The following code shows Python’s comparison operators with the resulting bool objects:
In [40]:
# Greater than
4 > 5
Out[40]: False
In [41]:
# Greater or equal than
5 >= 5
Out[41]: True
In [42]:
# Equal to
6 == 6
Out[42]: True
In [43]:
# Different from
4 != 5
Out[43]: True
Often, logical operators are applied on bool objects, which in turn yields another bool object:
localhost:8889/lab/tree/Principles of Programming/Programming_Priciples1.ipynb
8/19
9/2/22, 4:51 PM
In [44]:
Programming_Priciples1
True and True
Out[44]: True
In [45]:
True and False
Out[45]: False
In [46]:
True or False
Out[46]: True
In [47]:
False or (5>=3)
Out[47]: True
In [48]:
# Using negation
not False and True
Out[48]: True
In [49]:
not (4 > 5)
Out[49]: True
In [50]:
# A tricky one
not (not (1 != 2) and (2 < 5))
Out[50]: True
Understanding strings
Of all the data types, strings are the most easily understood by humans and not understood at all by
computers. A string is simply any grouping of characters you place within double quotes. For
example, myString = "Python is a great language." assigns a string of characters to myString.
In [51]:
myString = "Python is a great language."; myString
Out[51]: 'Python is a great language.'
The computer doesn’t see letters at all. Every letter you use is represented by a number in memory.
For example, the letter A is actually the number 65. To see this for yourself, type ord(“A”) at the
Python prompt and press Enter. We see 65 as output. It’s possible to convert any single letter to its
numeric equivalent using the ord() command.
In [52]:
ord("A")
localhost:8889/lab/tree/Principles of Programming/Programming_Priciples1.ipynb
9/19
9/2/22, 4:51 PM
Programming_Priciples1
Out[52]: 65
Because the computer doesn’t really understand strings, but strings are so useful in writing
applications, you sometimes need to convert a string to a number. We can use the int() and float()
methods to perform this conversion. For example, if we type myInt = int(“123”) and press Enter at
the Python prompt, we create an int named myInt that contains the value 123.
In [53]:
myint = int("123"); myint
Out[53]: 123
We can convert numbers to a string as well by using the str() command. For example, if you type
myStr = str(1234.56) and press Enter, we create a string containing the value "1234.56" and assign it
to myStr.
In [54]:
myStr = str(1234.56); myStr
Out[54]: '1234.56'
Some useful editing methods:
In [55]:
In [56]:
t = 'this is a string object'
# Capitalize the first word
t.capitalize()
Out[56]: 'This is a string object'
In [57]:
# Capitalize all
t.upper()
Out[57]: 'THIS IS A STRING OBJECT'
In [58]:
# Split the string to words
t.split()
Out[58]: ['this', 'is', 'a', 'string', 'object']
In [59]:
# Find where a particular substring starts within the string
# Attention: In Python, counting starts from 0. This means that 10 refers to the 11th p
t.find('string')
Out[59]: 10
In [60]:
t.replace(' ', '|')
localhost:8889/lab/tree/Principles of Programming/Programming_Priciples1.ipynb
10/19
9/2/22, 4:51 PM
Programming_Priciples1
Out[60]: 'this|is|a|string|object'
Working with Dates and Times
Dates and times are items that most people work with quite a bit. As with everything else,
computers understand only numbers — the date and time don’t really exist. To use dates and times,
we must issue a special import datetime command. Technically, this act is called importing a
module, and we will learn more about it next week. To get the current time, you can simply type
datetime.datetime. now( ) and press Enter. We see the full date and time information as found on
our computer’s clock.
In [61]:
import datetime as datetime
datetime.datetime.now()
Out[61]: datetime.datetime(2022, 9, 2, 16, 49, 30, 207904)
To get just the current date, in a readable format just make it a string.
In [62]:
str(datetime.datetime.now().date())
Out[62]: '2022-09-02'
To get just the time?
In [63]:
str(datetime.datetime.now().time())
Out[63]: '16:49:30.239890'
Operators
An operator accepts one or more inputs in the form of variables or expressions, performs a task
(such as comparison or addition), and then provides an output consistent with that task. Operators
are classified partially by their effect and partially by the number of elements they require. For
example, a unary operator works with a single variable or expression; a binary operator requires two.
The elements provided as input to an operator are called operands. The operand on the left side of
the operator is called the left operand, while the operand on the right side of the operator is called
the right operand. The following list shows the categories of operators that you use within Python:
Arithmetic
addition '+', subtraction '-', multiplication '*', division '/'
In [64]:
5+2
Out[64]: 7
localhost:8889/lab/tree/Principles of Programming/Programming_Priciples1.ipynb
11/19
9/2/22, 4:51 PM
In [65]:
Programming_Priciples1
5-2
Out[65]: 3
In [66]:
5*2
Out[66]: 10
In [67]:
5/2
Out[67]: 2.5
power '**', integer division '//' , '%' remainder
In [68]:
5**3
Out[68]: 125
In [69]:
126//5
Out[69]: 25
In [70]:
126%5
Out[70]: 1
Relational
We saw them earlier: '==' is equal, '~=' is different from, '>', '<', '>=', '<='
In [71]:
(5 + 6) >= 7
Out[71]: True
Logical
We saw them earlier too: "and", "or" and "not"
In [72]:
True and not False
Out[72]: True
Assignment
In [73]:
MyVar = 100; MyVar
localhost:8889/lab/tree/Principles of Programming/Programming_Priciples1.ipynb
12/19
9/2/22, 4:51 PM
Programming_Priciples1
Out[73]: 100
In [74]:
MyVar += 10; MyVar
Out[74]: 110
In [75]:
MyVar -= 10; MyVar
Out[75]: 100
In [76]:
MyVar *= 3; MyVar
Out[76]: 300
In [77]:
MyVar /= 2; MyVar
Out[77]: 150.0
In [78]:
MyVar **= 2; MyVar
Out[78]: 22500.0
In [79]:
# What do we do here?
MyVar //= 7; MyVar
Out[79]: 3214.0
In [80]:
# Let's check
3214*7
Out[80]: 22498
Membership
"in" and "not in" can be very useful!
In [81]:
5 in [1, 2, 5, 8]
Out[81]: True
In [82]:
"hat" in "I hate this food"
Out[82]: True
In [83]:
t = "I hate this food"
localhost:8889/lab/tree/Principles of Programming/Programming_Priciples1.ipynb
13/19
9/2/22, 4:51 PM
Programming_Priciples1
"hat" in t.split()
Out[83]: False
In [84]:
"like" not in "I don't like him at all"
Out[84]: False
Identity
In [85]:
type(2/1) is int
Out[85]: False
In [86]:
2/1
Out[86]: 2.0
In [87]:
type(2+1) is int
Out[87]: True
Be very careful with operator precedence!!
Creating and Using Functions
Each line of code that we create performs a specific task, and we combine these lines of code to
achieve a desired result. Sometimes we need to repeat the instructions with different data, and in
some cases our code becomes so long that it’s hard to keep track of what each part does. Functions
serve as organization tools that keep our code neat and tidy. In addition, functions make it easy to
reuse the instructions you’ve created as needed with different data.
When we create a function, we define a package of code that we can use over and over to perform
the same task. All we need to do is tell the computer to perform a specific task by telling it which
function to use. The computer faithfully executes each instruction in the function absolutely every
time we ask it to do so. The code that needs services from the function is named the caller, and it
calls upon the function to perform tasks for it. The caller must supply information to the function,
and the function returns information to the caller. Code reusability is a necessary part of
applications to ✓ Reduce development time ✓ Reduce programmer error ✓ Increase application
reliability ✓ Allow entire groups to benefit from the work of one programmer ✓ Make code easier to
understand ✓ Improve application efficiency
Defining a function
In [88]:
def hello():
localhost:8889/lab/tree/Principles of Programming/Programming_Priciples1.ipynb
14/19
9/2/22, 4:51 PM
Programming_Priciples1
print("This is my very first function")
Now we can "call" it, that is run it.
In [89]:
hello()
This is my very first function
Sending information to functions
We use "arguments" to pass information into a function. This information will change the outcome
of running the function.
In [90]:
def multiply2numbers(a, b):
c = a*b
print("\n c = ", c)
let's run it
In [91]:
multiply2numbers(5, 8)
c =
40
Most of the times, printing the results is not good enough. We need the result to be stored in a
variable. We use "return" to pass information from the function to the caller environment.
In [92]:
def multiply2numbers(a, b):
c = a*b
return c
We can now run it and store the result in a variable of our own choosing.
In [93]:
outcome1 = multiply2numbers(5, 8)
Now, it is important to understand that the variable c, defined within the function does not exist
anymore once the function finished its job. That variable is called "local". The variable outcome1 is
defined in the "caller" environment and is called "global".
In [94]:
outcome1
Out[94]: 40
In [95]:
# Calling for the local variable will produce an error
c
Out[95]: 0.5
So far we are using the inputs as positional arguments. We can also use keyword arguments
ignoring the relative position of the 2 arguments.
localhost:8889/lab/tree/Principles of Programming/Programming_Priciples1.ipynb
15/19
9/2/22, 4:51 PM
In [96]:
In [97]:
Programming_Priciples1
def a_gt_b(a, b):
return a > b
a_gt_b(5, 4)
Out[97]: True
In [98]:
a_gt_b(b=4, a=5)
Out[98]: True
Giving function arguments a default value
Whether you make the call using positional arguments or keyword arguments, the functions to this
point have required that you supply a value. Sometimes a function can use default values when a
common value is available. Default values make the function easier to use and less likely to cause
errors when a developer doesn’t provide an input. To create a default value, you simply follow the
argument name with an equals sign and the default value.
In [99]:
def is_it_int(a=1):
return type(a) is int
Let's run it with an argument.
In [100…
is_it_int(15)
Out[100… True
Without the argument.
In [101…
is_it_int()
Out[101… True
Creating functions with a variable number of arguments
In most cases, we know precisely how many arguments to provide with our function. It pays to work
toward this goal whenever we can because functions with a fixed number of arguments are easier to
troubleshoot later. However, sometimes we simply can’t determine how many arguments the
function will receive at the outset. For example, when we create a Python application that works at
the command line, the user might provide no arguments, the maximum number of arguments
(assuming there is one), or any number of arguments in between.
Python provides a technique for sending a variable number of arguments to a function. We simply
create an argument that has an asterisk in front of it, such as *VarArgs. The usual technique is to
localhost:8889/lab/tree/Principles of Programming/Programming_Priciples1.ipynb
16/19
9/2/22, 4:51 PM
Programming_Priciples1
provide a second argument that contains the number of arguments passed as an input. We can also
use the function len() to count the number of arguments.
In [102…
In [103…
def print_inputs(*VarArgs):
NumOfArgs = len(VarArgs)
return NumOfArgs
print_inputs(2,3,4,5)
Out[103… 4
Let's make it a bit richer by adding a for-loop. We'll talk about repetitive execution later.
In [104…
In [105…
def print_inputs(*VarArgs):
NumOfArgs = len(VarArgs)
print("You passed ", NumOfArgs, " arguments.")
for Arg in VarArgs:
print(Arg)
print_inputs(1,2, "one", True, 2.5)
You passed
1
2
one
True
2.5
5
arguments.
Getting User Input
We can get input from the user using the input function. Remember however that this function
accepts only strings as inputs. If we are to get a number from the user, we will have to transform the
input string to a number of the appropriate type. We are going to discuss if-else and indendation
next week.
In [106…
In [107…
def count_until(n=10):
yn = input("Shall I count to 10? (y/n)")
if yn=="y":
for i in range(10):
print(i+1)
else:
n = int(input("Number of loops?"))
for i in range(n):
print(i+1)
count_until()
1
2
localhost:8889/lab/tree/Principles of Programming/Programming_Priciples1.ipynb
17/19
9/2/22, 4:51 PM
Programming_Priciples1
3
4
5
6
7
8
9
10
In [108…
count_until()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Making Decisions
The ability to make a decision, to take one path or another, is an essential element of performing
useful work. Math gives the computer the capability to obtain useful information. Decisions make it
possible to do something with the information after it’s obtained. Without the capability to make
decisions, a computer would be useless. So any language you use will include the capability to make
decisions in some manner.
Understanding the if statement
The if statement is the easiest method for making a decision in Python. It simply states that if
something is true (the logical condition), Python should perform the steps that follow. The "elif"
statement says what must happen if the previous conditions are not satisfied, but this one is. The
"else" statement says what must happen if none of the above conditions are satisfied. After the
logical condition of the is statement follows ":". The actions to be taken start with the same
indendation, characterizing the block. The previous indendation says that we go into the next
condition.
In [109…
print("1. Red")
print("2. Orange")
print("3. Yellow")
print("4. Green")
print("5. Blue")
print("6. Purple")
Choice = int(input("Select your favorite color: "))
if (Choice == 1):
print("You chose Red!")
localhost:8889/lab/tree/Principles of Programming/Programming_Priciples1.ipynb
18/19
9/2/22, 4:51 PM
Programming_Priciples1
elif (Choice == 2):
print("You chose Orange!")
elif (Choice == 3):
print("You chose Yellow!")
elif (Choice == 4):
print("You chose Green!")
elif (Choice == 5):
print("You chose Blue!")
elif (Choice == 6):
print("You chose Purple!")
else:
print("You made an invalid choice!")
1.
2.
3.
4.
5.
6.
Red
Orange
Yellow
Green
Blue
Purple
You chose Blue!
Using Nested Decision Statements
The decision-making process often happens in levels. The process of making decisions in levels, with
each level reliant on the decision made at the previous level, is called nesting. Developers often use
nesting techniques to create applications that can make complex decisions based on various inputs.
Using multiple if or if...else statements
The most commonly used multiple selection technique is a combination of if and if...else statements.
This form of selection is often called a selection tree because of its resemblance to the branches of a
tree. In this case, you follow a particular path to obtain a desired result. We'll look at "while" later on!
In [111…
print("Think of a number between 1 and 100")
min_x = 1
max_x = 100
while(min_x < max_x):
qstring = (["Is it larger than", str((max_x + min_x)//2), "? (y/n)"])
GL = input(qstring)
if (GL == "y"):
min_x = (max_x + min_x)//2 + 1
else:
max_x = (max_x + min_x)//2
print("Your secret number is ", min_x)
Think of a number between 1 and 100
Your secret number is
62
In [ ]:
localhost:8889/lab/tree/Principles of Programming/Programming_Priciples1.ipynb
19/19
Download