Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
122 views

Key Takeaways: Print

The document discusses Python syntax and functions. It provides examples of: 1) Using the print() function to output strings. 2) Strings being text enclosed in either single or double quotes. 3) Functions requiring parentheses and arguments to be called or invoked. 4) Special characters like backslash allowing escape sequences in strings. 5) Different data types in Python including integers, floating-point numbers, and Boolean values.

Uploaded by

Chester
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
122 views

Key Takeaways: Print

The document discusses Python syntax and functions. It provides examples of: 1) Using the print() function to output strings. 2) Strings being text enclosed in either single or double quotes. 3) Functions requiring parentheses and arguments to be called or invoked. 4) Special characters like backslash allowing escape sequences in strings. 5) Different data types in Python including integers, floating-point numbers, and Boolean values.

Uploaded by

Chester
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Syntax refers to the rules that define the structure of a computer language using symbols, punctuations,

and words of computer programming

Print(“Hello world”)

Print- is a function, all functions are denoted by ()

“”-is a denotation to be used in order to type a string, command which says to the computer that the
text between “” is not a code but rather take it as is or the computer will read and output it as is without
any command lines hidden, any texts written between “” will be taken literally/ output as is. Not as a
code but as a data

Hello world- is a string inside “”

Hello wold is one argument of the function print

To execute a function we need a function call or as we call it function invocation or invoke a function,, to
call it in order to be executed>>>function_name(argument)- that is what program structure should look
like in order to invoke a function or to make the computer familiarize it in its own computer
programming library to be known and to be executed
 Strings, numbers, characters, logical values, objects - any of these may be successfully passed
to print().

Python requires that there cannot be more than one instruction in a line.

A line can be empty (i.e., it may contain no instruction at all) but it must not contain two, three or
more instructions. This is strictly prohibited.

\- it is an escape character,,it does not have meaning by itself rather it suggest a new different meaning
after the backslash>>print(“ukilam lubuajen/nukilam”)>>output should be:

ukilam lubuajen

ukilam

so the backslash introduces a new different kind of meaning which is n which when introduced by
backslash makes or adds a new meaning that form a special symbol named a newline

the print() function has two keyword arguments :end,

a keyword argument consists of three elements: a keyword identifying the argument(ex: end), then the
equal sign (=), and last but not the list is the value assigned to that argument

Key takeaways
1. The  print()  function is a built-in function. It prints/outputs a specified message to the
screen/consol window.

2. Built-in functions, contrary to user-defined functions, are always available and don't have to be
imported. Python 3.8 comes with 69 built-in functions. You can find their full list provided in
alphabetical order in the Python Standard Library.
3. To call a function (this process is known as function invocation or function call), you need to
use the function name followed by parentheses. You can pass arguments into a function by placing
them inside the parentheses. You must separate arguments with a comma, e.g.,  print("Hello,",
"world!") . An "empty"  print()  function outputs an empty line to the screen.

4. Python strings are delimited with quotes, e.g.,  "I am a string"  (double quotes), or  'I am a
string, too'  (single quotes).

5. Computer programs are collections of instructions. An instruction is a command to perform a


specific task when executed, e.g., to print a certain message to the screen.

6. In Python strings the backslash ( \ ) is a special character which announces that the next
character has a different meaning, e.g.,  \n  (the newline character) starts a new output line.

7. Positional arguments are the ones whose meaning is dictated by their position, e.g., the second
argument is outputted after the first, the third is outputted after the second, etc.

8. Keyword arguments are the ones whose meaning is not dictated by their location, but by a
special word (keyword) used to identify them.

9. The  end  and  sep  parameters can be used for formatting the output of the  print()  function.
The  sep  parameter specifies the separator between the outputted arguments (e.g.,  print("H",
"E", "L", "L", "O", sep="-") , whereas the  end  parameter specifies what to print at the end
of the print statement.

A literal is data whose values are determined by the literal itself.

Numbers handled by modern computers are of two types:

Integers-does not have fractional parts

Floating-point-does contain fractional parts

The characteristic of the numeric value which determines its kind, range, and application, is called
the type.

you can write this number either like this: 11111111, or like that: 11_111_111.

There are two additional conventions in Python that are unknown to the world of mathematics. The
first allows us to use numbers in an octal representation.

If an integer number is preceded by an  0O  or  0o  prefix (zero-o), it will be treated as an octal value.
This means that the number must contain digits taken from the [0..7] range only.

0o123  is an octal number with a (decimal) value equal to  83 .

The second convention allows us to use hexadecimal numbers. Such numbers should be preceded


by the prefix  0x  or  0X  (zero-x).
0x123  is a hexadecimal number with a (decimal) value equal to  291 . The print() function can
manage these values too. Try this:

4 is an integer number while 4.0 is a floating number

  300000000 .

To avoid writing out so many zeros, physics textbooks use an abbreviated form, which you have
probably already seen:  3 x 108 .

It reads: three times ten to the power of eight.

In Python, the same effect is achieved in a slightly different way - take a look:

3E8

Strings
Strings are used when you need to process text (like names of all kinds, addresses, novels, etc.), not numbers.

You already know a bit about them, e.g., that strings need quotes the way floats need points.

This is a very typical string:  "I am a string."

However, there is a catch. The catch is how to encode a quote inside a string which is already delimited by
quotes.

Let's assume that we want to print a very simple message saying:

I like "Monty Python"

How do we do it without generating an error? There are two possible solutions.

The first is based on the concept we already know of the escape character, which you should remember is
played by the backslash. The backslash can escape quotes too. A quote preceded by a backslash changes its
meaning - it's not a delimiter, but just a quote. This will work as intended:

print ("I like \"Monty Python\"")


Note: there are two escaped quotes inside the string - can you see them both?

The second solution may be a bit surprising. Python can use an apostrophe instead of a quote. Either of these
characters may delimit strings, but you must be consistent.

If you open a string with a quote, you have to close it with a quote.

If you start a string with an apostrophe, you have to end it with an apostrophe.

This example will work too:

print ('I like "Monty Python"')

Note: you don't need to do any escaping here.

Boolean values
To conclude with Python's literals, there are two additional ones.

They're not as obvious as any of the previous ones, as they're used to represent a very abstract value
- truthfulness.

Each time you ask Python if one number is greater than another, the question results in the creation of some
specific data - a Boolean value.

The name comes from George Boole (1815-1864), the author of the fundamental work, The Laws of Thought,
which contains the definition of Boolean algebra - a part of algebra which makes use of only two distinct
values:  True  and  False , denoted as  1  and  0 .

A programmer writes a program, and the program asks questions. Python executes the program, and provides
the answers. The program must be able to react according to the received answers.

Fortunately, computers know only two kinds of answers:

 Yes, this is true;


 No, this is false.

You'll never get a response like: I don't know or Probably yes, but I don't know for sure.

Python, then, is a binary reptile.


These two Boolean values have strict denotations in Python:

True

False

You cannot change anything - you have to take these symbols as they are, including case-sensitivity.

Challenge: What will be the output of the following snippet of code?

print (True > False)

print (True < False)

Run the code in the Sandbox to check. Can you explain the result?

Arithmetic operators: exponentiation


We'll begin with the operators which are associated with the most widely recognizable arithmetic
operations:

+ ,  - ,  * ,  / ,  // ,  % ,  **

A  **  (double asterisk) sign is an exponentiation (power) operator. Its left argument is the base, its
right, the exponent.

Classical mathematics prefers notation with superscripts, just like this: 23. Pure text editors don't
accept that, so Python uses  **  instead, e.g.,  2 ** 3 .

Look at the code below and try to predict the results once again:

print (-6 // 4)
print (6. // -4)

Note: some of the values are negative. This will obviously affect the result. But how?
The result is two negative twos. The real (not rounded) result is  -1.5  in both cases. However, the
results are the subjects of rounding. The rounding goes toward the lesser integer value, and the
lesser integer value is  -2 , hence:  -2  and  -2.0 .

Operators: remainder (modulo)


The next operator is quite a peculiar one, because it has no equivalent among traditional arithmetic
operators.

Its graphical representation in Python is the  %  (percent) sign, which may look a bit confusing.

print(12 % 4.5)

3.0  - not  3  but  3.0  (the rule still works:  12 // 4.5  gives  2.0 ;  2.0 * 4.5  gives  9.0 ;  12 -
9.0  gives  3.0 )

List of priorities
Since you're new to Python operators, we don't want to present the complete list of operator
priorities right now.

Instead, we'll show you its truncated form, and we'll expand it consistently as we introduce new
operators.

Look at the table below:

Priority Operator

1 + ,  - unary

2 **

3 * ,  / ,  // ,  %

4 + ,  - binary

Note to self: % can be used for limiting the maximum numbers in the output process

Note: we've enumerated the operators in order from the highest (1) to the lowest (4) priorities.

Key takeaways
1. An expression is a combination of values (or variables, operators, calls to functions - you will
learn about them soon) which evaluates to a value, e.g.,  1 + 2 .
2. Operators are special symbols or keywords which are able to operate on the values and perform
(mathematical) operations, e.g., the  *  operator multiplies two values:  x * y .

3. Arithmetic operators in Python:  +  (addition),  -  (subtraction),  *  (multiplication),  /  (classic division -


always returns a float),  %  (modulus - divides left operand by right operand and returns the remainder
of the operation, e.g.,  5 % 2 = 1 ),  **  (exponentiation - left operand raised to the power of right
operand, e.g.,  2 ** 3 = 2 * 2 * 2 = 8 ),  //  (floor/integer division - returns a number resulting
from division, but rounded down to the nearest whole number, e.g.,  3 // 2.0 = 1.0 )

4. A unary operator is an operator with only one operand, e.g.,  -1 , or  +3 .

5. A binary operator is an operator with two operands, e.g.,  4 + 5 , or  12 % 5 .

6. Some operators act before others - the hierarchy of priorities:

 unary  +  and  -  have the highest priority


 then:  ** , then:  * ,  / , and  % , and then the lowest priority: binary  +  and  - .

7. Subexpressions in parentheses are always calculated first, e.g.,  15 - 1 * (5 * (1 + 2)) =


0.

8. The exponentiation operator uses right-sided binding, e.g.,  2 ** 2 ** 3 = 256 .

What are variables?


It seems fairly obvious that Python should allow you to encode literals carrying number and text values.

You already know that you can do some arithmetic operations with these numbers: add, subtract, etc. You'll be
doing that many times.

But it's quite a normal question to ask how to store the results of these operations, in order to use them in
other operations, and so on.

How do you save the intermediate results, and use them again to produce subsequent ones?

Python will help you with that. It offers special "boxes" (containers) for that purpose, and these boxes are
called variables - the name itself suggests that the content of these containers can be varied in (almost) any
way.

What does every Python variable have?

 a name;
 a value (the content of the container)

Let's start with the issues related to a variable's name.

Variables do not appear in a program automatically. As developer, you must decide how many and which
variables to use in your programs.
You must also name them.

If you want to give a name to a variable, you must follow some strict rules:

 the name of the variable must be composed of upper-case or lower-case letters, digits, and the
character  _  (underscore)
 the name of the variable must begin with a letter;
 the underscore character is a letter;
 upper- and lower-case letters are treated as different (a little differently than in the real world
- Alice and ALICE are the same first names, but in Python they are two different variable names, and
consequently, two different variables);
 the name of the variable must not be any of Python's reserved words (the keywords - we'll explain
more about this soon).

Keywords
Take a look at the list of words that play a very special role in every Python program.

['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class',


'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for',
'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not',
'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

They are called keywords or (more precisely) reserved keywords. They are reserved because you
mustn't use them as names: neither for your variables, nor functions, nor any other named entities
you want to create.

The meaning of the reserved word is predefined, and mustn't be changed in any way.

Fortunately, due to the fact that Python is case-sensitive, you can modify any of these words by
changing the case of any letter, thus creating a new word, which is not reserved anymore.

For example - you can't name your variable like this:

import

You mustn't have a variable named in such a way - it is prohibited. But you can do this instead:

Import

These words might be a mystery to you now, but you'll soon learn the meaning of them.

Using variables
You're allowed to use as many variable declarations as you need to achieve your goal, like this:
var = 1

account_balance = 1000.0

client_name = 'John Doe'

print (var, account_balance, client_name)

print (var)

You're not allowed to use a variable which doesn't exist (in other words, a variable that was not assigned a
value).

This example will cause an error:

var = 1

print(Var)

We've tried to use a variable named  Var , which doesn't have any value (note:  var  and  Var  are different
entities, and have nothing in common as far as Python's concerned).

REMEMBER

You can use the  print()  function and combine text and variables using the  +  operator to output strings and
variables, e.g.:

var = "3.8.5"

print("Python version: " + var)

The input() function
We're now going to introduce you to a completely new function, which seems to be a mirror reflection of the
good old  print()  function.

Why? Well,  print()  sends data to the console.

The new function gets data from it.


print()  has no usable result. The meaning of the new function is to return a very usable result.

The function is named  input() . The name of the function says everything.

The  input()  function is able to read data entered by the user and to return the same data to the running
program.

The program can manipulate the data, making the code truly interactive.

Virtually all programs read and process data. A program which doesn't get a user's input is a deaf program.

Take a look at our example:

print ("Tell me anything...")


anything = input()
print ("Hmm...", anything, "... Really?")

It shows a very simple case of using the  input()  function.

Note:

 The program prompts the user to input some data from the console (most likely using a keyboard,
although it is also possible to input data using voice or image);
 the  input()  function is invoked without arguments (this is the simplest way of using the function);
the function will switch the console to input mode; you'll see a blinking cursor, and you'll be able to
input some keystrokes, finishing off by hitting the Enter key; all the inputted data will be sent to your
program through the function's result;
 note: you need to assign the result to a variable; this is crucial - missing out this step will cause the
entered data to be lost;
 then we use the  print()  function to output the data we get, with some additional remarks.

Try to run the code and let the function show you what 

We've said it already, but it must be unambiguously stated once again: the result of
the  input()  function is a string.

A string containing all the characters the user enters from the keyboard. It is not an integer or a float.

This means that you mustn't use it as an argument of any arithmetic operation, e.g., you can't
use this data to square it, divide it by anything, or divide anything by it.

anything = input("Enter a number: ")


something = anything ** 2.0
print(anything, "to the power of 2 is", something)
Python offers two simple functions to specify a type of data and solve this problem - here they
are: int() and float().

anything = float(input("Enter a number: "))

something = anything ** 2.0

print(anything, "to the power of 2 is", something)

Having a team consisting of the trio input()-int()-float() opens up lots of new possibilities.

The  *  (asterisk) sign, when applied to a string and number (or a number and string, as it remains
commutative in this position) becomes a replication operator:

string * number
number * string

It replicates the string the same number of times specified by the number.

For example:

 "James" * 3  gives  "JamesJamesJames"


 3 * "an"  gives  "ananan"
 5 * "2"  (or  "2" * 5 ) gives  "22222"  (not  10 !)

Type conversion: str()
You already know how to use the  int()  and  float()  functions to convert a string into a number.

This type of conversion is not a one-way street. You can also convert a number into a string,
which is way easier and safer - this operation is always possible.

A function capable of doing that is called  str() :

str (number)

To be honest, it can do much more than just transform numbers into strings, but that can wait for
later.
The "right-angle triangle" again
Here is our "right-angle triangle" program again:

leg_a = float(input("Input first leg length: "))

leg_b = float(input("Input second leg length: "))

print("Hypotenuse length is " + str((leg_a**2 + leg_b**2) ** .5))

We've modified it a bit to show you how the  str()  function works. Thanks to this, we can pass the
whole result to the  print()  function as one string, forgetting about the commas.

hour = int(input("Starting time (hours): "))

mins = int(input("Starting time (minutes): "))

dura = int(input("Event duration (minutes): "))

mins = mins + dura # find a total of all minutes

hour = hour + mins // 60 # find a number of hours hidden in minutes and update the hour

mins = mins % 60 # correct minutes to fall in the (0..59) range

hour = hour % 24 # correct hours to fall in the (0..23) range

print(hour, ":", mins, sep='')

Key takeaways

1. The  print()  function sends data to the console, while the  input()  function gets data from the
console.

2. The  input()  function comes with an optional parameter: the prompt string. It allows you to write a
message before the user input, e.g.:
name = input("Enter your name: ")

print("Hello, " + name + ". Nice to meet you!")

3. When the  input()  function is called, the program's flow is stopped, the prompt symbol keeps blinking (it
prompts the user to take action when the console is switched to input mode) until the user has entered an input
and/or pressed the Enter key.

NOTE

You can test the functionality of the  input()  function in its full scope locally on your machine. For resource
optimization reasons, we have limited the maximum program execution time in Edube to a few seconds. Go to
Sandbox, copy-paste the above snippet, run the program, and do nothing - just wait a few seconds to see what
happens. Your program should be stopped automatically after a short moment. Now open IDLE, and run the
same program there - can you see the difference?

Tip: the above-mentioned feature of the  input()  function can be used to prompt the user to end a program.
Look at the code below:

name = input("Enter your name: ")

print ("Hello, " + name + ". Nice to meet you!")

print ("\nPress Enter to end the program.")

input ()

print ("THE END.")

3. The result of the  input()  function is a string. You can add strings to each other using the concatenation
( + ) operator. Check out this code:

num_1 = input("Enter the first number: ") # Enter 12

num_2 = input("Enter the second number: ") # Enter 21

print (num_1 + num_2) # the program returns 1221


4. You can also multiply ( *  - replication) strings, e.g.:

my_input = input("Enter something: ") # Example input: hello

print (my_input * 3) # Expected output: hellohellohello

Boolean Values, Conditional Execution, Loops, Lists and List Processing, Logical and
Bitwise Operations

In this module, you will cover the following topics:

 the Boolean data type;


 relational operators;
 making decisions in Python (if, if-else, if-elif,else)
 how to repeat code execution using loops (while, for)
 how to perform logic and bitwise operations in Python;
 lists in Python (constructing, indexing, and slicing; content manipulation)
 how to sort a list using bubble-sort algorithms;
 multidimensional lists and their applications.

You might also like