print()
functionJupyter Notebook previously called IPython Notebook is a web application that allows you to run live code, embed visualization and explonatory text all in one place. Jupyter notebooks (with a lower case 'n') are files with .ipynb extension containing JSON data
Header: At the top of the notebook document is the header which contains the notebook title, menu bar, and toolbar, which are used to control notebook navigation and document structure.
Body: The body of a notebook is composed of cells. Each cell contains either markdown, code input, code output, or raw text.
Types of cells:
-Raw cells: These are used when text needs to be included in raw form, without execution or transformation.
Modes of a cell:
Enter
or using the mouse to click on a cell's editor area.Esc
or using the mouse to click outside a cell's editor area.Keyboard Short cuts: Keyboard shortcuts are a very popular aspect of the Jupyter environment because they facilitate a speedy cell-based workflow. Following shortcuts work in command mode:
Let's begin by using Python as a calculator. You can write and execute Python using a code cell within Jupyter.
Working with cells: To create a new cell within Jupyter, you can select "Insert > Insert Cell Below" from the menu bar or just press the "+" button on the toolbar. You can also use the keyboard shortcut
Esc+B
to create a new cell. Once a cell is created, click on it to select it. You can then change the cell type to code or markdown (text) using the "Cell > Cell Type" menu option. You can also use the keyboard shortcutsEsc+Y
andEsc+M
. Double-click a cell to edit the content within the cell. To apply your changes and run a cell, use the "Cell > Run Cells" menu option or click the "Run" button on the toolbar or just use the keyboard shortcutShift+Enter
. You can see a full list of keyboard shortcuts using the "Help > Keyboard Shortcuts" menu option.
Run the code cells below to perform calculations and view their result. Try changing the numbers and run the modified cells again to see updated results.
'hello Jupyter: JUlia PYThon R'
'hello Jupyter: JUlia PYThon R'
Python supports the following arithmetic operators:
Operator | Purpose | Example | Result |
---|---|---|---|
+ |
Addition | 2 + 3 |
5 |
- |
Subtraction | 3 - 2 |
1 |
* |
Multiplication | 8 * 12 |
96 |
/ |
Division | 100 / 7 |
14.28.. |
// |
Floor Division | 100 // 7 |
14 |
% |
Modulus/Remainder | 100 % 7 |
2 |
** |
Exponent | 5 ** 3 |
125 |
2 + 3 + 9
14
99 - 73
26
23.54 * -1432
-33709.28
100 / 7
14.285714285714286
100 // 7
14
100 % 7
2
5 ** 3
125
As you might expect, operators like /
and *
take precedence over other operators like +
and -
as per mathematical conventions. You can use parentheses, i.e. (
and )
, to specify the order in which operations are performed.
((2 + 5) * (17 - 3)) / (4 ** 3)
1.53125
Note that we're using the #
character to add comments within our code.
Comments: Comments and blank lines are ignored during execution, but they are useful for providing information to humans (including yourself) about what the code does. Comments can be inline (at the end of some code), on a separate line, or even span multiple lines.
Inline and single-line comments start with #
, whereas multi-line comments begin and end with three quotes, i.e. """
. Here are some examples of code comments:
# This is a single line comment
# Keyboard shortcut to comment/un-comment some LOC(s) is <command+/>
"""
A multi-line comment starts and ends with a tripple double quotes
A docstring is a documentation string. As a comment, this Python Syntax is used to explain code.
But unlike comments, they are more specific. Also, they are retained at runtime.
This way, the programmer can inspect them at runtime. Delimit a docstring using three double-quotes.
"""
'''
A multi-line comment can also starts and ends with a tripple single quotes
'''
x=10 # A comment ends with newline
x
10
print()
Function¶print
: The print
is a Python built-in function that is used to display information. It takes one or more inputs, which can be text (within quotes, e.g., "this is some text"
), numbers, variables, mathematical expressions, etc. We'll learn more about variables the next tutorial.
Jupyter allows you to write multiple lines of code within a single code cell. However, the result of the last line of code within a cell is displayed as the output.
print()
function receives variable number of comma separated values and all the comma separated elements/variables get printed on the output separated by spaces (by default)# Note only the last command appears in output
age = 50
name = "Arif Butt"
age
name
'Arif Butt'
# Solution is to use print()
print(age)
print(name)
50 Arif Butt
# You can use `+` operator to concatenage two or more strings
'Hello Mr. ' + name
'Hello Mr. Arif Butt'
# However, you cannot use `+` operator on numbers
"Hello Mr. " + name + ', you are ' + age + 'years old'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /var/folders/1t/g3ylw8h50cjdqmk5d6jh1qmm0000gn/T/ipykernel_9663/2630918959.py in <module> 1 # However, you cannot use `+` operator on numbers ----> 2 "Hello Mr. " + name + ', you are ' + age + 'years old' TypeError: can only concatenate str (not "int") to str
print()
Function¶%s
symbol as a place holder for the value of a variable in the format string of the print()
function.%s
inside the string where you want a value to appear. After the string, put a %
operator and mention the identifiers in parenthesis.str = "Hello Mr. %s, you are %s years old." %(name, age)
str
'Hello Mr. Arif Butt, you are 50 years old.'
# The format string can be used in `print()`
print("Hello Mr. %s, you are %s years old." %(name, age))
Hello Mr. Arif Butt, you are 50 years old.
string.format()
method: (Python Style)format()
method on the string using the dot operator and mention the identifiers in parenthesisage = 50; name = "Arif Butt"
print("Hello Mr. {}, you are {} years old." .format(name, age))
Hello Mr. Arif Butt, you are 50 years old.
# You can mention indices of variables passed to format() function, if you want a different
# sequence as in following example
age = 51; name = "Arif Butt"
print("Hello Mr. {1}, you are {0} years old." .format(age, name))
Hello Mr. Arif Butt, you are 51 years old.
# Another way of passing argument to format method
print("Hello Mr. {name}, you are {age} years old." .format(name="Kakamanna",age=23))
Hello Mr. Kakamanna, you are 23 years old.
\
#print('It's my birthday') # This will flag an error
print('It\'s my birthday')
It's my birthday
# Similarly, we can give an ordinary character 't' and 'n', special meanings by preceding them by a back slash
print('Hello\tWorld')
print('Hello\nWorld')
Hello World Hello World
sep
parameter of print()
Function¶print()
insert a space character between values.sep
parameter and assign it any character/string you want to used instead of space characterage = 50
name = "Arif Butt"
print(name, age)
Arif Butt 50
age = 50
name = "Arif Butt"
print(name, age, sep=' : ')
Arif Butt hello 50
end
parameter of print()
function¶print()
statement is done printing the output, it appends a newline character at the end. Hence, we get the output of each print statement in different line.end
parameter and assign it the character/string you want to use instead of newline characterage = 50
name = "Arif Butt"
print(name)
print(age)
Arif Butt 50
age = 50
name = "Arif Butt"
print(name, end=' ')
print(age)
Arif Butt 50
Within IPython you have various way to access help:
?
Introduction and overview of IPython's features (this screen).?object
Details about 'object'.help(object)
Access Python's own help system.help()
Interactive help utility?
?print
help(print)
Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.
# Get help about "keywords", "symbols", "topics", ...
# Type "quit" to exit this interactive command
help()
Welcome to Python 3.8's help utility! If this is your first time using Python, you should definitely check out the tutorial on the Internet at https://docs.python.org/3.8/tutorial/. Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit". To get a list of available modules, keywords, symbols, or topics, type "modules", "keywords", "symbols", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose name or summary contain a given string such as "spam", type "modules spam". help> quit You are now leaving help and returning to the Python interpreter. If you want to ask for help on a particular object directly from the interpreter, you can type "help(object)". Executing "help('string')" has the same effect as typing a particular string at the help> prompt.
!
sign!pwd
!date
!touch f1.txt
! ls
! echo "This is fun.."
! cat ../Lec-2.01-Introduction-to-Python/first.py
/Users/arif/Documents/0-DS-522/Demo-Files-Repo/Section-2-Basics-of-Python-Programming/Lec-2.02-Anaconda-and-Jupyter-Notebook Thu Dec 2 09:01:35 PKT 2021 01-hellojupyter.ipynb ddd images 02-markdown-example.ipynb f1.txt newfile This is fun.. #!/usr/bin/python ctr = 1 while ctr <= 5 : print(ctr) ctr = ctr + 1
%
character, and work much like OS command-line calls: they get as an argument the rest of the line, where arguments are passed without parentheses or quotes%%
character, and they are functions that get as an argument not only the rest of the line, but also the lines below it in a separate argument. These magics are called with two arguments: the rest of the call line and the body of the cell, consisting of the lines below the first.%lsmagic
Available line magics: %alias %alias_magic %autoawait %autocall %automagic %autosave %bookmark %cat %cd %clear %colors %conda %config %connect_info %cp %debug %dhist %dirs %doctest_mode %ed %edit %env %gui %hist %history %killbgscripts %ldir %less %lf %lk %ll %load %load_ext %loadpy %logoff %logon %logstart %logstate %logstop %ls %lsmagic %lx %macro %magic %man %matplotlib %mkdir %more %mv %notebook %page %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %pip %popd %pprint %precision %prun %psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall %rehashx %reload_ext %rep %rerun %reset %reset_selective %rm %rmdir %run %save %sc %set_env %store %sx %system %tb %time %timeit %unalias %unload_ext %who %who_ls %whos %xdel %xmode Available cell magics: %%! %%HTML %%SVG %%bash %%capture %%debug %%file %%html %%javascript %%js %%latex %%markdown %%perl %%prun %%pypy %%python %%python2 %%python3 %%ruby %%script %%sh %%svg %%sx %%system %%time %%timeit %%writefile Automagic is ON, % prefix IS NOT needed for line magics.
%pwd
'/Users/arif/Documents/0-DS-522/Demo-Files-Repo/Section-2-Basics-of-Python-Programming/Lec-2.02-Anaconda-and-Jupyter-Notebook'
%mkdir ddd
%ls
01-hellojupyter.ipynb f1.txt 02-markdown-example.ipynb images/ ddd/
%alias msg echo "Learning is fun with Arif Butt"
msg
'Learning is fun with Arif Butt'
%pycat
line magic%pycat ../Lec-2.01-Introduction-to-Python/fibo_series.py
%run
line magic%run ../Lec-2.01-Introduction-to-Python/fibo_series
Fibonacci Series: 0 1 1 2 3 5 8
%load
line magic%load ../Lec-2.01-Introduction-to-Python/fibo_series.py
# %load ../Lec-2.01-Introduction-to-Python/fibo_series.py
#Iterative Fibonacci Series
def fibo_series(n):
a=1
b=1
print("Fibonacci Series: ", end=' ')
if n<1:
print("Incorrect input")
elif n==1:
print('0', end=' ')
elif n==2:
print('0','1', end=' ')
else:
print('0',a,b,end=' ')
for i in range(n-3):
c = a + b
print(c, end=' ')
a = b
b = c
print()
fibo_series(7)
Fibonacci Series: 0 1 1 2 3 5 8
%history
# Note only the last command appears in output age = 50 msg = "Arif Butt" age msg # You can use `+` operator to concatenage things name + age # Note only the last command appears in output age = 50 name = "Arif Butt" age name # You can use `+` operator to concatenage things name + age # You can use `+` operator to concatenage things name + $age # You can use `+` operator to concatenage things 'Hello Mr. ' + name # You can use `+` operator to concatenage things "Hello Mr. " + name ', you are ' + age + 'years old' # You can use `+` operator to concatenage things "Hello Mr. " + name + ', you are ' + age + 'years old' "Hello Mr. %s, you are %s years old.' %(name, age) "Hello Mr. %s, you are %s years old."" %(name, age) "Hello Mr. %s, you are %s years old. %(name, age) "Hello Mr. %s, you are %s years old." %(name, age) # Solution is to use print() print(name, age) b=a-5 c=a+b print("a = ", a) print("b = ", b) print("c = ", c) # You can also fit in more than one statement on one line by separating them with a semicolon. d = 5 + 3; print('d = ', d) # Solution is to use print() print(age) print(name) # You can use `+` operator to concatenage two or more strings 'Hello Mr. ' + name # You can use `+` operator to concatenage strings "Hello Mr. " + name + ', you are ' + age + 'years old' # However, you cannot use `+` operator on numbers "Hello Mr. " + name + ', you are ' + age + 'years old' # Solution is to use a format string with `%s` format specifier "Hello Mr. %s, you are %s years old." %(name, age) # Solution is to use a format string with `%s` format specifier (C style) str = "Hello Mr. %s, you are %s years old." %(name, age) # The format string can be used in `print()` print(str) # The format string can be used in `print()` print("Hello Mr. %s, you are %s years old." %(name, age)) age = 50 name = "Arif Butt" print(name, age) age = 50 name = "Arif Butt" print(name, age, sep='\n') age = 50 name = "Arif Butt" print(name, age, sep=' : ') print(name, age, sep='\n') age = 50 name = "Arif Butt" print(name, age) age = 50 name = "Arif Butt" print(name, age, sep=' : ') print(name, age, sep='\n') age = 50 name = "Arif Butt" print(name) print(age) age = 50 name = "Arif Butt" print(name, end=' ') print(age) # Option 2: age = 50; name = "Arif Butt" print("Hello Mr. {}.".format(name)) print("Mr. {}, you are {} years old." .format(name, age)) # Option 2: age = 50, name = "Arif Butt" print("Hello Mr. {}.".format(name)) print("Mr. {}, you are {} years old." .format(name, age)) # Option 2: age = 50; name = "Arif Butt" print("Hello Mr. {}.".format(name)) print("Mr. {}, you are {} years old." .format(name, age)) # Option 2: age = 50; name = "Arif Butt" print("Mr. {}, you are {} years old." .format(name, age)) # Option 2: age = 50; name = "Arif Butt" print("Hello Mr. {}, you are {} years old." .format(name, age)) # Option 2: You can mention indices of variables passed to format() function, if you want a different # sequence as in following example age = 51; name = "Arif Butt" print("Mr. {1}, you are {0} years old." .format(age, name)) # Option 2: You can mention indices of variables passed to format() function, if you want a different # sequence as in following example age = 51; name = "Arif Butt" print("Hello Mr. {1}, you are {0} years old." .format(age, name)) age = 50 name = "Arif Butt" print(name, age, sep=' : ') age = 50 name = "Arif Butt" print(name, age, sep=' hello ') age = 50 name = "Arif Butt" print(name, end=' bbbb ') print(age) age = 50 name = "Arif Butt" print(name, end=' ') print(age) #print('It's my birthday') # This will flag an error print('It\'s my birthday') # Similarly, we can give an ordinary character 't' and 'n', special meanings by preceding them by a back slash print('Hello\tWorld') print('Hello\nWorld') !pwd !date !touch f1.txt ! ls ! echo "This is fun.." ! cat ../Lec-2.01-Introduction-to-Python/first.py dir(__builtins__) import math ??math import math ?math dir(math) pow() %history
- If you want to check out the time taken by a Python command to execute , use the %time line magic
- The load magic command when executed will load the file contents in the cell and automatically comment itself :)
%load ../Lec-2.01-Introduction-to-Python/fibo_series.py
%time print("hello jupyter")
hello jupyter CPU times: user 287 µs, sys: 136 µs, total: 423 µs Wall time: 357 µs
%time for i in range(10000000): pass
CPU times: user 345 ms, sys: 2.96 ms, total: 348 ms Wall time: 347 ms
%%bash
echo "My shell is:" $SHELL
touch newfile
date
pwd
for friends in 'Khurram', 'Idrees', 'Waheed', 'Nadeem'
do
echo $friends
done
My shell is: /bin/bash Wed Dec 1 22:06:28 PKT 2021 /Users/arif/Documents/0-DS-522/Demo-Files-Repo/Section-2-Basics-of-Python-Programming/Lec-2.02-Anaconda-and-Jupyter-Notebook Khurram, Idrees, Waheed, Nadeem
%%html
<h2> Students, there is no shortcut to hardwork</h2>
<p>This is text</p>
This is text
%%javascript
let msg="Learning is fun with Arif"
alert(msg)
%%HTML
<iframe width="560" height="315" src="https://www.youtube.com/embed/K1xO8weArNA" frameborder="0"></iframe>
allowfullscreen
%quickref
¶%quickref
Try answering the following questions to test your understanding of the topics covered in this notebook: