0% found this document useful (0 votes)
33 views

Le1 - Language - Basics - Jupyter Notebook

1) This document introduces basic Python concepts like printing, variables, data types, arithmetic operations, strings, and user input. 2) Key concepts covered include using print() to output text, assigning values to variables, Python's dynamic typing system, numeric, string, and boolean data types, and operators for mathematical and comparison operations. 3) Strings can be defined using single quotes, double quotes, or triple quotes and support escape sequences; the input() function is used to prompt for and input user text.

Uploaded by

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

Le1 - Language - Basics - Jupyter Notebook

1) This document introduces basic Python concepts like printing, variables, data types, arithmetic operations, strings, and user input. 2) Key concepts covered include using print() to output text, assigning values to variables, Python's dynamic typing system, numeric, string, and boolean data types, and operators for mathematical and comparison operations. 3) Strings can be defined using single quotes, double quotes, or triple quotes and support escape sequences; the input() function is used to prompt for and input user text.

Uploaded by

Ezea Francisco
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Introduction to Python

Let's try some simple Python commands:

In [1]: # Display "Hello, World!" in the terminal/notebook output.


print("Hello, World!")

Hello, World!

Line 1: Referred to as a comment in software development. The Python interpreter ignores every line that starts with a # . Comments are used to explain what you're code is doing to other humans.

Line 2: The print() command is a function. Specifically referred to as a built-in function. These are functions you do not have to import to use. The print() function is used to output characters to the
console/terminal when Python programs are running. Let us consider some more examples:

In [2]: # Add two numbers together


print(1 + 1)

In [3]: # Subtract two numbers


print(5 - 2)

In [4]: # Divide a number by another number


print(6 / 3)

2.0

In [5]: # Just like in mathematics, we can make variables in Python too


x = 12
print(x)

12

Note:

The statement x = 12 should be interpreted as "assigning 12 to x" because we are instructing the computer to hold 12 in a memory location with the alias 'x', it should not be interpreted as "x is equal to 12"

Formally, variables in programming are small containers in memory that hold specific values. Values can be of many different types:

• numbers: integers, real numbers (which include numbers with decimal parts, known as floating-point numbers). There are 3 major numeric types in Python: int , float , and complex
• strings: combination of characters such as alphabets, numbers, and other characters. Strings in Python can be denoted by enclosing the content of the strings with single quotes: '' , double quotes "" , triple single
quotes ''' or triple double quotes """ .
• bool: The boolean data type has two possible values: True and False .
• other types such as list , dict , tuple , set , NamedTuple , etc.
• user-defined types: you can also create your own type for specific needs that do not align perfectly with the types that exist in the language. For example, other Python users have created types such as
pandas.DataFrame , numpy.array , that are very beneficial to Python's scientific computing community.

Eventhough a variable can hold values of any of the above-mentioned types. However, Python is flexible in that you do not have to explicitly declare the type of values a variable is going to hold when you create it.
In [6]: my_variable = 'assigned the value of a string'

You can also change the type of value a variable holds after it has been created:

In [7]: # create a variable to hold an integer


my_var = 34
print(my_var)
# you can check the type of value a variable holds with the `type()`
# builtin function
print(type(my_var))
# change the value it holds to a string
my_var = 'now a string'
print(my_var)
print(type(my_var))

34
<class 'int'>
now a string
<class 'str'>

Programming languages where the type of variables can be changed after they've been created are referred to as dynamically typed language. This behavior is possible because the variables are assigned a type as the
code is being executed. Python is a dynamically typed language. While the ability to alter the type of a variable offers much more flexibility, it also makes the code less optimized (the interpreter has to always check the
type of a variable at any point in the code it's assigned a new value. This contributes to slower program speeds of dynamically typed languages).

There is another group of programming languages where the programmer is required to state the data type of each variable when the variable is being declared. The data types are checked as programs written in these
languages are compiled before the programs can be used. Such languages are referred to as statically typed languages. For these languages, a variable's data type is static and cannot be altered, or a compilation error
will be raised.

More Arithmetic Operations in Python


Here are some other arithmetic operations available in Python:

In [8]: # To obtain the remainder of a division operation


x = 19
y = 5
remainder = x % y
print(remainder)

In [9]: # To obtain the floored quotient (might also be referred to as integer division)
x = 19
y = 5
floored_quotient = x // 5
print(f"Floored quotient: {floored_quotient}")

print(f"x divided by y is equal to {floored_quotient} remainder {remainder}")

Floored quotient: 3
x divided by y is equal to 3 remainder 4
In [10]: # Calculating power

# 2 raised to power 3
print(2**3)

# 2 raised to power 10
print(2**10)

# 7 raised to power 2
print(7**2)

8
1024
49

Python also supports complex numbers

In [11]: comp_1 = 4 + 3j
print(comp_1)

(4+3j)

In [12]: comp_1 = 4 + 3j
comp_2 = 6 - 2j

print(f"comp_1 - comp_2 = {comp_1 - comp_2}")

# To get the real part of a complex number


real_comp_1 = comp_1.real

# To get the imaginary part of a complex number


imag_comp_1 = comp_1.imag

print(f"Real(comp_1) = {real_comp_1}\nImag(comp_1) = {imag_comp_1}")

comp_1 - comp_2 = (-2+5j)


Real(comp_1) = 4.0
Imag(comp_1) = 3.0

Strings
We have used strings to print out user-friendly versions some mathematical expressions above. Let us take a closer look at how they work in Python.

As stated above, strings can be expressed in several ways. They can be enclosed in single quotes ('...'), double quotes ("...") with the same result. `' can be used to escape quotes.

In [13]: print('he was welcomed back')

he was welcomed back


In [14]: # if we wanted to use a single quote again within the expression above,
# we might get an unexpected result by just using it directly:
print('he wasn't welcomed back') # invalid syntax

File "/tmp/ipykernel_46044/4052526396.py", line 3


print('he wasn't welcomed back') # invalid syntax
^
SyntaxError: invalid syntax

In [ ]: # we will have to "escape" the single quote for it to work


print('he wasn\'t welcomed back') # valid syntax

In [ ]: # We could also avoid all this by just re-writing the expression as so:
print("he wasn't welcomed back") # surround the entire string with double quotes

Escape sequences

There are actually very important escape sequences we need to note:

Sequence Meaning

\' single quote

\" double quote

\\ backslash

\n Newline

\t tab

In [ ]: print("The path to the folder is: C:\home\\new_folder")

In [ ]: # Two strings can be added to each other. This is known as concatenation
name = input("Please enter your name: ")
greeting = "Hello " + name + " and welcome to Python"
print(greeting)

In [ ]: # Strings placed next to each other will also be automatically concatenated
another_greeting = 'Hello, ' 'I am new here.'
print(another_greeting)

In [ ]: # It is best practice to enclose such strings in parentheses


note = (
'Better to use '
'parentheses when placing strings next to each other '
'like this'
)
print(note)

In [ ]: # this feature will not work when joining strings literals and variables
note '. more notes'
Strings will be discussed in details later in the course when we look at data structures like lists and dictionaries.

The input() function


The input function is used to accept input from a user on the console. The programmer can prompt the user for the expected input by passing a string into the input function. The user input is always of the type str even
when the user inputs a number.

In [ ]: collected_number = input("Please enter a number between 1 and 10: ")


print(collected_number)
print(type(collected_number))

A variable can be explicitly converted to another type. For example, we can convert collected_number above to a number:

In [ ]: converted_number = int(collected_number) # You can also use float(collected_number) if the user is expected to enter floating-point numbers
print(converted_number)
print(type(converted_number))

Comparison Operators
These are operators that are used to compare two values. Comparison statements are typically evaluated to True or False . In Python True and False are both of the data Boolean type.

Operator Meaning

== equal to

< less than

> greater than

<= less than or equal to

>= greater than or equal to

!= not equal to

In [ ]:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy