0% found this document useful (0 votes)
11 views11 pages

Prelim - Python Introdhdhdjejejej

Uploaded by

josmar tecson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views11 pages

Prelim - Python Introdhdhdjejejej

Uploaded by

josmar tecson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

What is Python

is a very popular general-purpose interpreted, interactive, object-oriented, and high-


level programming language. Python is dynamically-typed and garbage-collected
programming language. It was created by Guido van Rossum during 1985- 1990. Like
Perl, Python source code is also available under the GNU General Public License (GPL).

It is used for:

Data Science
Machine Learning
Web Development
Computer Vision and Image processing
Embedded Systems and IoT
Job Scheduling and Automation
Desktop GUI Applications
Console-based Applications
CAD Applications
Game Development

What can Python do?


Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software
development.

Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional way.
Python Syntax compared to other programming
languages
Python was designed for readability, and has some similarities to the English language
with influence from mathematics.
Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets for
this purpose.

The First Program


In [2]: print("Hello, World!")

Hello, World!

Python Install
Many PCs and Macs will have python already installed.

To check if you have python installed on a Windows PC, search in the start bar for Python or
run the following on the Command Line (cmd.exe):

C:\Users\Your Name>python --version

If you find that you do not have Python installed on your computer, then you can download
it for free from the following website: https://www.python.org/

Python Quickstart
Python is an interpreted programming language, this means that as a developer you write
Python (.py) files in a text editor and then put those files into the python interpreter to be
executed.

The way to run a python file is like this on the command line:

C:\Users\Your Name>python helloworld.py

Let's write our first Python file, called helloworld.py, which can be done in any text editor.

In [2]: print("Hello, World!")

Hello, World!
Simple as that. Save your file. Open your command line, navigate to the directory where you
saved your file, and run:

C:\Users\Your Name>python helloworld.py

The Python Command Line


To test a short amount of code in python sometimes it is quickest and easiest not to write
the code in a file.

Type the following on the Windows, Mac or Linux command line:

C:\Users\Your Name>python
Or, if the "python" command did not work, you can try "py":

C:\Users\Your Name>py

Python Indentation
Indentation refers to the spaces at the beginning of a code line.

Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.

Python uses indentation to indicate a block of code.

In [7]: if 5 > 2:
print("Five is greater than two!")

Cell In[7], line 2


print("Five is greater than two!")
^
IndentationError: expected an indented block after 'if' statement on line 1

Python will give you an error if you skip the indentation:

In [3]: if 5 > 2:
print("Five is greater than two!")
else:
print('asdgasdg')

Five is greater than two!

The number of spaces is up to you as a programmer, the most common use is four, but it
has to be at least one.

In [ ]: if 5 > 2:
print("Five is greater than two!")
print("")
if 5 > 2:
print("Five is greater than two!")

You have to use the same number of spaces in the same block of code, otherwise Python will
give you an error:

In [1]: if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")

Cell In[1], line 3


print("Five is greater than two!")
^
IndentationError: unexpected indent

Python Variables
In Python, variables are created when you assign a value to it:

In [1]: x = 0
y = "Hello, World!"
print(x)
print(y)

0
Hello, World!

Python has no command for declaring a variable.

Comments
Python has commenting capability for the purpose of in-code documentation.

Comments start with a #, and Python will render the rest of the line as a comment:

In [2]: #This is a comment.


print("Hello, World!")

Hello, World!

Multiline Comments
Python does not really have a syntax for multiline comments.

To add a multiline comment you could insert a # for each line:


Or, not quite as intended, you can use a multiline string.

Since Python will ignore string literals that are not assigned to a variable, you can add a
multiline string (triple quotes) in your code, and place your comment inside it:

In [3]: #def addition(x,y):


# print(f"The sum of {x} and {y} is: {x+y}")

#def subtraction(x,y):
# print(f"The difference of {x} and {y} is: {x-y}")

def multiplication(x,y):
print(f"The product of {x} and {y} is: {x*y}")

def division(x,y):
print(f"The quotient of {x} and {y} is: {x/y}")

while True:
print("+-----------------------------+")
print("A-ddition")
print("S-ubtraction")
print("M-ultiplication")
print("D-ivision")
print("E-xit")
print("+-----------------------------+")
choice = input("Enter your choice: ")
choice = choice.upper()

if choice == 'E':
break
else:
"""val1 = int(input("Enter 1st number: "))
val2 = int(input("Enter 1st number: "))
if choice =='A':
addition(val1,val2)
elif choice =='S':
subtraction(val1,val2)
elif choice =='M':
multiplication(val1,val2)
elif choice =='D':
division(val1,val2)
else:
print("Invalid Input!")"""
print("Thank You! Good Bye!")
A-ddition
S-ubtraction
M-ultiplication
D-ivision
E-xit
The sum of 12 and 12 is: 24
A-ddition
S-ubtraction
M-ultiplication
D-ivision
E-xit
Thank You! Good Bye!

As long as the string is not assigned to a variable, Python will read the code, but then ignore
it, and you have made a multiline comment.

Creating Variables
Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

In [3]: x = 5
y = "John"
print(x)
print(y)

5
John

Variables do not need to be declared with any particular type, and can even change type
after they have been set.

In [4]: a = int(input("Enter a num:")) # x is of type int


x = '4'
a = 'a'
x = x+a
print(x)

4a

Casting
If you want to specify the data type of a variable, this can be done with casting.

In [5]: x = str(3) # x will be '3'


y = int(x) # y will be 3
z = float(3) # z will be 3.0
print(x,y,z)
print(x+str(y),z)
3 3 3.0
33 3.0

Get the Type


You can get the data type of a variable with the type() function.

In [4]: x = 5
y = "John"
print(type(x))
print(type(y))

<class 'int'>
<class 'str'>

Single or Double Quotes?


String variables can be declared either by using single or double quotes:

In [5]: x = "John"
# is the same as
x = 'John'

Case-Sensitive
Variable names are case-sensitive.

In [6]: a = 4
A = "Sally"
print(A)
print(a)
#A will not overwrite a

Sally
4

Python - Variable Names


A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume). Rules for Python variables:

A variable name must start with a letter or the underscore character


A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
A variable name cannot be any of the Python keywords.
In [7]: myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

print(myvar, my_var, _my_var, myVar, MYVAR, myvar2)

John John John John John John

In [8]: 2myvar = "John"


my-var = "John"
my var = "John"

print(2myvar, my-var, my var)

Cell In[8], line 1


2myvar = "John"
^
SyntaxError: invalid decimal literal

Multi Words Variable Names


There are several techniques you can use to make them more readable:

Camel Case
Pascal Case
Snake Case

In [9]: myVariableName = "John" #Camel Case


MyVariableName = "John" #Pascal Case
my_variable_name = "John" #Snake Case

print(myVariableName,MyVariableName,my_variable_name)

John John John

Many Values to Multiple Variables


In [10]: x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

Orange
Banana
Cherry

One Value to Multiple Variables


In [11]: x = y = z = "Orange"
print(x)
print(y)
print(z)

Orange
Orange
Orange

Unpack a Collection
In [12]: fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)

apple
banana
cherry

Output Variables
The Python print() function is often used to output variables.

In the print() function, you output multiple variables, separated by a comma:

In [13]: x = "Python"
y = "is"
z = "awesome"
print(x, y, z)

Python is awesome

You can also use the + operator to output multiple variables:

In [14]: x = "Python "


y = "is "
z = "awesome"
print(x + y + z)

Python is awesome

Global Variables
Variables that are created outside of a function (as in all of the examples in the previous
pages) are known as global variables.

Global variables can be used by everyone, both inside of functions and outside.
In [15]: x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()

Python is awesome

If you create a variable with the same name inside a function, this variable will be local, and
can only be used inside the function. The global variable with the same name will remain as
it was, global and with the original value.

In [16]: x = "awesome"

def myfunc():
x = "fantastic"
print("Python is " + x)

myfunc()

print("Python is " + x)

Python is fantastic
Python is awesome

The global Keyword


To create a global variable inside a function, you can use the global keyword.

In [17]: def myfunc():


global x
x = "fantastic"

myfunc()

print("Python is " + x)

Python is fantastic

Also, use the global keyword if you want to change a global variable inside a function.

In [18]: x = "awesome"

def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)

Python is fantastic
In [19]: val = bytearray("Hello", 'utf-8')
print(val)
b1 = bytes([65, 66, 67, 68, 69])
print(b1)

bytearray(b'Hello')
b'ABCDE'

You might also like