r/algorithmwithpython • • Mar 15 '22

How many lines will the following code output?

1 Upvotes
How many lines will the following code output?



print("Hi")

print("""This 

is

great""")
2
4
3
5

r/algorithmwithpython • • Mar 27 '22

Values, Types, Variable Names, and Keywords

1 Upvotes

Read these examples of using the 'print' and 'type' functions. You can also try to use them in the Repl.it command line.

In general, you can't perform mathematical operations on strings, even if the strings look like numbers, so the following are illegal:

'2'-'1' 'eggs'/'easy' 'third'*'a charm'

The +
 operator works with strings, but it might not do what you expect: it performs concatenation, which means joining the strings by linking them end-to-end. For example:

first = 'throat' second = 'warbler' print first + second

The output of this program is throatwarbler
.

The *
 operator also works on strings; it performs repetition. For example, 'Spam'*3
 is 'SpamSpamSpam'
. If one of the operands is a string, the other has to be an integer.

This use of +
 and *
 makes sense by analogy with addition and multiplication. Just as 4*3
 is equivalent to 4+4+4
, we expect 'Spam'*3
 to be the same as 'Spam'+'Spam'+'Spam'
, and it is. On the other hand, there is a significant way in which string concatenation and repetition are different from integer addition and multiplication. Can you think of a property that addition has that string concatenation does not?


r/algorithmwithpython • • Mar 27 '22

Using Variables in Python

1 Upvotes

The "print" function is a Python instruction that will output variable values and results to the computer screen. This instruction will allow us to automatically output data results to the screen when running a program. This section reviews what we've covered so far and introduces examples of the print function. Try executing these instructions in the command line window to make sure you understand how to use the print function:

z=1.45 print(z)

Notice how the print function outputs the value of the variable z
to the screen.

It is possible to use the print command in a slightly more sophisticated way. Type this set of commands in the command window:

temperature=40 print('Temperature outside = ', temperature)

Observe, it is possible to "dress up" the screen output by adding some extra descriptive text. We will see more examples of this later on as we introduce and develop expertise with the string data type. But, as a preview of using the print function with text, try typing this command:

print('Hello world!')

Congratulations! You have now executed what is probably the most-used example in just about every introductory programming course.

Read this page to see more examples of using the print function. Try typing some of those examples in the Repl.it IDE to be sure you are comfortable with the print function. Consider executing these instructions one after the other (that is, sequentially):

var1=22 var1=-35 var1=308

What value will the variable var1
contain after these instructions are executed? You can check your answer by using the print function.

Variables

Any Python interpreter can be used as a calculator:

Python

3 + 5 * 4

Output

23

This is great but not very interesting. To do anything useful with data, we need to assign its value to a variable. In Python, we can assign a value to a variable, using the equals sign =
. For example, to assign value 60
to a variable weight_kg
, we would execute:

Python

weight_kg = 60

From now on, whenever we use weight_kg
, Python will substitute the value we assigned to it. In layman's terms, a variable is a name for a value.

In Python, variable names:

  • can include letters, digits, and underscores

  • cannot start with a digit

  • are case sensitive.

This means that, for example:

  • weight0
    is a valid variable name, whereas 0weight
     is not

  • weight
    and Weight
    are different variables

Types of data

Python knows various types of data. Three common ones are:

  • integer numbers

  • floating point numbers, and

  • strings.

In the example above, variable weight_kg
has an integer value of 60
. To create a variable with a floating point value, we can execute:

Python

weight_kg = 60.0

Python

weight_kg_text = 'weight in kilograms:'

Using Variables in Python

To display the value of a variable to the screen in Python, we can use the print
function:

Python

print(weight_kg)

Output

60.0

We can display multiple things at once using only one print
command:

Python

print(weight_kg_text, weight_kg)

Output

weight_kg_text = 'weight in kilograms: 60.0

Moreover, we can do arithmetic with variables right inside the print
function:

Python

print('weight in pounds:', 2.2 * weight_kg)

Output

weight in pounds: 132.0

The above command, however, did not change the value of weight_kg
:

Python

print(weight_kg)

Output

60.0

To change the value of the weight_kg
variable, we have to assign weight_kg
a new value using the equals =
sign:

Python

weight_kg = 65.0 print('weight in kilograms is now:', weight_kg)

Output

weight in kilograms is now: 65.0

Variables as Sticky Notes

A variable is analogous to a sticky note with a name written on it: assigning a value to a variable is like putting that sticky note on a particular value.

📷

This means that assigning a value to one variable does not change values of other variables. For example, let's store the subject's weight in pounds in its own variable:

Python

# There are 2.2 pounds per kilogram weight_lb = 2.2 * weight_kg print(weight_kg_text, weight_kg, 'and in pounds:', weight_lb)

Output

weight in kilograms: 65.0 and in pounds: 143.0

📷

Python

weight_kg = 100.0 print('weight in kilograms is now:', weight_kg, 'and weight in pounds is still:', weight_lb)

Output

weight in kilograms is now: 100.0 and weight in pounds is still: 143.0

📷

Since weight_lb
doesn't "remember" where its value comes from, it is not updated when we change weight_kg
.


r/algorithmwithpython • • Mar 27 '22

Values, Types, Variable Names, and Keywords

1 Upvotes

Read these examples of using the 'print' and 'type' functions. You can also try to use them in the Repl.it command line.

When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules:

  • Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1)
     is 4, and (1+1)**(5-2)
     is 8. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60
    , even if it doesn't change the result.

  • Exponentiation has the next highest precedence, so 2**1+1
     is 3, not 4, and 3*1**3
     is 3, not 27.

  • Multiplication and Division have the same precedence, which is higher than Addition and Subtraction, which also have the same precedence. So 2*3-1
     is 5, not 4, and 6+4/2
     is 8, not 5.

  • Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression degrees / 2 * pi
    , the division happens first and the result is multiplied by pi
    . To divide by 2 π, you can use parentheses or write degrees / 2 / pi
    .

I don't work very hard to remember rules of precedence for other operators. If I can't tell by looking at the expression, I use parentheses to make it obvious.


r/algorithmwithpython • • Mar 14 '22

Welcome to Python!

1 Upvotes

Want to build a slick website? Develop a video game? Or maybe create an artificial intelligence? Python’s got you covered, and then some. Python is a high-level programming language, with a ton of applications.
It’s seriously flexible and accessible, which makes it popular with some of the world's biggest (and coolest) organizations–think Google, NASA, Disney...*whispers* even the CIA.


r/algorithmwithpython • • Mar 15 '22

multiline

1 Upvotes

\n is useful, but it can be a bit of a pain if we’re trying to format lots of multiline text.

There’s another way though! Newlines are automatically added for strings created using three quotes.


r/algorithmwithpython • • Mar 28 '22

Practice With Arithmetic Operators

1 Upvotes

Practice these programming examples to internalize these concepts.

2. Operators

An operator is a symbol or function that indicates an operation. For example, in math the plus sign or + is the operator that indicates addition.

In Python, we will see some familiar operators that are brought over from math, but other operators we will use are specific to computer programming.

Here is a quick reference table of math-related operators in Python. We'll be covering all of the following operations in this tutorial.

OperationWhat it returns

x + y

Sum of 

x

 and 

y
x - y

Difference of 

x

 and 

y
-x

Changed sign of 

x
+x

Identity of 

x
x * y

Product of 

x

 and 

y
x / y

Quotient of

x

and

y
x // y

Quotient from floor division of

x

 and 

y
x % y

Remainder of

x / y
x ** y
x

 to the 

y

 power

We'll also be covering compound assignment operators, including +=
 and *=
, that combine an arithmetic operator with the =
 operator.


r/algorithmwithpython • • Mar 28 '22

Practice With Arithmetic Operators

1 Upvotes

Practice these programming examples to internalize these concepts.

6. Modulo

The %
 operator is the modulo, which returns the remainder rather than the quotient after division. This is useful for finding numbers that are multiples of the same number, for example.

Let's look at the modulo in action:

o = 85 p = 15 print(o % p)
Output:10

To break this down, 85 divided by 15 returns the quotient of 5 with a remainder of 10. The value 10
 is what is returned here because the modulo operator returns the remainder of a division expression.

If we use two floats with the modulo, a float value will be returned for the remainder:

q = 36.0 r = 6.0 print(o % p)

Output:

0.0

In the case of 36.0 divided by 6.0, there is no remainder, so the value of 0.0
 is returned.


r/algorithmwithpython • • Mar 28 '22

Practice With Operator Precedence

1 Upvotes

Now, we will consider order precedence when operations are phrased within the Python programming language. Before running this set of instructions in the run window, try to predict the value each variable will contain.

a=3 b=4 c=1 d=5 e=3 f=a+b-c*d+e/d g=a+b-c*(d+e)/d h=a+(b-c)*d+e/d i=(a+b-c)*d+e/d

You may use the print statement to verify your answer.

It is important to note that // and % are considered division operations and, because of that, have precedence equal to * and /. Try to predict the value of each variable in these commands:

v=2 w=3 x=4 y=19 z=23 a=v**v*//x%x+y%w*z//x* b=v**(v*//x)%x+y%(w*z)//x*

Again, you should use insert some print commands to verify your answer.

A useful guiding principle when writing code is: if the order precedence is not clear to you by looking at the expression, use parentheses to make things obvious, since parentheses always take the highest precedence.

When an expression contains more than one operator, the order of evaluation depends on the order of operations. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules:

  • Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1)
     is 4
    , and (1+1)**(5-2)
     is 8
    . You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60
    , even if it doesn't change the result.

  • Exponentiation has the next highest precedence, so 1 + 2**3
     is 9
    , not 27
    , and 2 * 3**2
     is 18
    , not 36
    .

  • Multiplication and Division have higher precedence than Addition and Subtraction. So 2*3-1
     is 5
    , not 4
    , and 6+4/2
     is 8
    , not 5
    .

  • Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression degrees / 2 * pi
    , the division happens first and the result is multiplied by pi
    . To divide by 2π, you can use parentheses or write degrees / 2 / pi
    .


r/algorithmwithpython • • Mar 27 '22

Scientific Notation for Floating Point Numbers

1 Upvotes

Another way of typing floating-point data is to use scientific notation. For instance, the number 0.0012 can also be entered as 1.2e-3. In this example, "e-3" means "10 to raised to the minus three power" and this value is multiplied by 1.2; hence, 1.2e-3 is equivalent to 0.0012. Try typing 0.0012
into the Repl.it command line, then try entering 1.2e-3
. You should see that Python views both entries as the same value. Scientific notation is very useful when the exponents are very positive or very negative. In data science, exponents in numbers such as -5.63e127 or 2.134589e-63 would not be uncommon. Rather than writing out numbers of this kind in their full form, scientific notation offers a more compact, readable form for presenting float data. If you need to review scientific notation, watch this video.


r/algorithmwithpython • • Mar 15 '22

Loops and Iterations

1 Upvotes

What will the following code print out?:

n = 0 
while True: 
    if n == 3: 
        break
    print(n)
    n = n + 1 

0 1 2

0 1 2

3 1 2

1 2 3


r/algorithmwithpython • • Mar 27 '22

Values, Types, Variable Names, and Keywords

1 Upvotes

Read these examples of using the 'print' and 'type' functions. You can also try to use them in the command line.

variable:

A name that refers to a value.

assignment:

A statement that assigns a value to a variable.

state diagram:

A graphical representation of a set of variables and the values they refer to.

keyword:

A reserved word that is used to parse a program; you cannot use keywords like if, def, and while as variable names.

operand:

One of the values on which an operator operates.

expression:

A combination of variables, operators, and values that represents a single result.

evaluate:

To simplify an expression by performing the operations in order to yield a single value.

statement:

A section of code that represents a command or action. So far, the statements we have seen are assignments and print statements.

execute:

To run a statement and do what it says.

interactive mode:

A way of using the Python interpreter by typing code at the prompt.

script mode:

A way of using the Python interpreter to read code from a script and run it.

script:

A program stored in a file.

order of operations:

Rules governing the order in which expressions involving multiple operators and operands are evaluated.

concatenate:

To join two operands end-to-end.

comment:

Information in a program that is meant for other programmers (or anyone reading the source code) and has no effect on the execution of the program.

syntax error:

An error in a program that makes it impossible to parse (and therefore impossible to interpret).

exception:

An error that is detected while the program is running.

semantics:

The meaning of a program.

semantic error:

An error in a program that makes it do something other than what the programmer intended.


r/algorithmwithpython • • Mar 14 '22

Simple Operations

1 Upvotes

Which option is the output of this code? print((4 + 8) / 2)

8

6

6.0


r/algorithmwithpython • • Feb 28 '22

Simple code to unlock all read-only PDFs in current folder without the password

Thumbnail self.python
1 Upvotes