You are on page 1of 12

QUANTUM COMPUTER WORKSHOP

Intro to Python
Part One

python is a widely used, general-purpose, interpreted, high-level programming language for general purpose
programming, created by Guido van Rossum and rst released in 1991. Python les are stored with
the extension “ .py”
Two major versions of Python are currently in active use:

• Python 3.x is the current version and is under active development.

• Python 2.x is the legacy version

IDLE (Integrated Development and Learning Environment) is a simple editor for Python that comes bundled
with Python.

FEATURES OF PYTHON
Python's features include-

Easy to learn, read and maintain: Python has few keywords, simple structure and a clearly de ned
syntax. This allow students pick up the language quickly.Also, Python's source code is easy-to-maintain.

Interactive Mode: Python has support for an interactive mode, which allows interactive testing and
debugging of snippets of code.

Portable: Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.

USES OF PYTHON PROGRAMMING LANGUAGE: Python is used in virtually every industry and scienti c
eld, including: Web development, Software development, Machine Learning and Arti cial Intelligence,
Medicine and Pharmacology, Astronomy, Robotics, autonomous vehicles, etc

HOW TO CREATE A SIMPLE “HELLOWORLD” PROGRAM IN PYTHON


print("HelloWorld")

HelloWorld

COMMENTS IN PYTHON
# first comment
print ("Helloworld") #second comment
Helloworld

PYTHON VARIABLES
In computer programming, variables are used to store information to be referenced and used by programs. It is
helpful to think of variables as containers that hold information. Their sole purpose is to label and store data in
memory.This data can then be used throughout your program.Variables are also called identi ers in Python

Syntax: variable name = value

EXAMPLE:

NUM = 2023

Days = "Happy Sunday"

qubits = 'qc'

NUM =2023
#variable name = value
DATE = 16
Days= "sunday"
name= "OSSPI"

print(name)

OSSPI

VARIABLE NAMING RULES IN PYTHON


1. You must start variable names with an alphabet or underscore(_) character.

2. A variable name can only contain A-Z, a-z, 0-9, and underscore (_).
3. You cannot start the variable name with a number.
4. You cannot use special characters with the variable name such as such as $,%,#,&,@.-,^ etc.

5. Variable names are case sensitive. For example username and Username are two different variables.
6. Variable names cannot contain whitespace(s).
7. Do not use reserve keywords as a variable name for example keywords like class, for, def, del, is, else, etc.

Examples of variable names allowed


x=2

• y="Hello"

• mypython="PythonGuides"

• my_python="PythonGuides"

• _mypython="PythonGuides"

• MYPYTHON="PythonGuides"
• myPython7="PythonGuides"

mypython="PythonGuides"
MYPYTHON="PythonGuides and if"

print(mypython)

PythonGuides

######### Examples of variable names not allowed

• 7mypython"PythonGuides"

• -mypython="PythonGuides"

• myPy@thon="PythonGuides"

• my Python="PythonGuides"

• for="PythonGuides"

Data Type
A data type is a classi cation of data which tells the computer how the programmer intends to use the data.
Most programming languages support various types of data, including integer, real, character or string, and
Boolean. Python variables do not need explicit declaration, the declaration happens automatically when you
assign a value to a variable. The equal sign (=) is used to assign values to variables. The operand to the left of
the = operator is the name of the variable and the operand to the right of the = operator is the value stored in
the variable. For example –

counter = 100 #An integer assignment

miles = 1000.0 # A oating point

name = "John" # A string

Python has 6 standard data types that are used to de ne the operations possible on them:
• Numbers

• String

• Boolean

• List

• Tuple

• Dictionary

PYTHON NUMBERS
Number data types store numeric values. Python supports three different numerical types −

i. int (signed integers): positive and negative whole numbers. e.g. 10, 100, -789, 1 etc.
ii. oat ( oating point real values): positive and negative oating (decimal / fractional) numbers. e.g. 0.0,
15.20, -21.9, 1.0, 32.8+e18 etc.

iii. complex (complex numbers): positive and negative complex numbers. e.g. 3.14j, .876j, -.6545+0j,
3e+26j etc.

A complex number consists of an ordered pair of real oating-point numbers denoted by x + yj, where x and y
are real
numbers and j is the imaginary unit

x=1 #int

y=22.7 # oat

z=1j #complex

print(type(x))

x=1
print(type(x))
y=22.7
print(type(y))

<class 'int'>
<class 'float'>

You can convert from one type to another with the int(), oat(), and complex() methods.This is also know as
casting.

x=int(1)

y= oat(22/7)

z=complex(12.5)

PYTHON STRINGS
Strings (single lines) in python are surrounded by either single quotation marks, or double quotation marks. You
can assign a multiline string to a variable by using three quotes: 'hello' is the same as "hello". You can display a
string literal with the print() function: print("Hello")

QUANTUM = 'COMPUT'
print(QUANTUM)

COMPUT

osspi = "osspi love coding"


print(osspi)

osspi love coding

To modify Python strings, there are set of built-in methods that you can
use on the strings.
• The upper() method returns the string in upper case.

• The lower() method returns the string in lower case.

• The capitalize() method returns a capitalized version of the string.

• The replace() method replaces a string with another string

print(QUANTUM.upper())

print(osspi.upper())

COMPUT
OSSPI LOVE CODING

PYTHON BOOLEANS
Booleans represent one of two values: True or False. In programming you often need to know if an expression is
True or False. You can evaluate any expression in Python, and get one of two answers, True or False. When you
compare two values, the expression is evaluated and Python returns the Boolean answer.

print(10 > 9)
print(20 < 1)
print(10 == 12)
print(10 == 10)

True
False
False
True

PYTHON INPUT FUNCTION


Python allows for user input. That means we are able to ask the user for input. Python 3x uses the input() method.
The following example asks for the username, and when you entered the username, it gets printed on the screen:

username = input("Enter Username: ")

print("Username is: " + username)

STATE = input("Enter your state: ")

print(STATE)

#for casting
Num =int(input("Enter Username: "))

print(Num)
age = int(input("Enter your age: "))

print(age)

QUANTUM COMPUTER WORKSHOP


Intro to Python
Part Two

PYTHON ARITHMETIC OPERATORS


Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Example

+ Addition x+y

- Subtraction x-y

/ Division x/y

* Multiplication x*y

** Exponentiation x ** y

// Floor division x // y

% Modulus x%y

PYTHON ASSIGNMENT OPERATORS


Assignment operators are used to assign values to variables:

Operator Example Same As

= x= 5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

PYTHON COMPARISON OPERATORS


Comparison operators are used to compare two values:

Operator Name Example


Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

a=20
b=20
cc = a > b
print(cc)

False

PYTHON LOGICAL OPERATORS


Logical operators are used to combine conditional statements:

Operator Description Example

and ReturnsTrue if both statements are true x < 5 and x < 10

or ReturnsTrue if one of the statements is true x < 5 or x < 4

not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

PYTHON MEMBERSHIP OPERATORS


Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with the speci ed value is present in the object x in y

not in Returns True if a sequence with the speci ed value is not present in the object x not in y

a< and b<23

True

Decision Making & Conditional Statements


Decision-making is the anticipation of conditions occurring during the execution
of a program and speci ed actions taken according to the conditions. Conditional
expressions, involving keywords such as if, elif, and else, provide Python
programs with the ability to perform different actions depending on a boolean
condition.

For IF STATEMENT
a = 23
b = 200
if b > a:
print("b is greater than a")

For ELIF STATEMENT


The elif keyword is Python’s way of saying "if the previous conditions were not true, then try this condition".

if b > a :
print("b is greater than a")
elif b == a:
print("b is not equal to a")

For ELSE STATEMENT


The else keyword catches anything which isn't caught by the preceding conditions.

aa = 200
bb = 22

if bb > aa:
print("bb is greater than aa")
elif aa == bb:
print("aa is not equal to bb")
else:
print("aa is greater than bb")

aa is greater than bb

In this example a is greater than b, so the rst condition is not true, also the elif condition is not true, so we go to
the
else condition and print to screen that "aa is greater than bb"

“AND” & “OR”


The and & or keywords are logical operators and are used to combine conditional statements.

aa = 200
bb = 22
cc = 500
if aa > bb and cc > aa:
print("Both conditions are True")

Both conditions are True

if aa > bb or cc > aa:


print(" One must be True")

One must be True


NESTED IF
You can have if statements inside if statements, this is called nested if statements.

QC = 40
if QC > 10:
print("Above ten,")
if QC > 20:
print("And also above 20 !")
else:
print("but not above 20.")

Above ten,
And also above 20 !

a = 20
b = 200
v = 320
if a < v:
print("One")
if a == v:
print("Move to next page")
if a != v:
print("Love coding")

One
Love coding

Python Loops
Python has two primitive loop commands:

1. while loops

2. for loops

A.THE WHILE LOOP

With the while loop we can execute a set of statements as long as a condition is true.

#EXAMPLE: Print i as long as i is less than 6 -


QC1 = 1
while QC1 < 6:
print(QC1)
QC1 +=1

#Remember to increment i, or else, the loop will continue forever.

1
2
3
4
5

THE BREAK STATEMENT


With the break statement we can stop the loop even if the while condition is true:

#EXAMPLE: Exit the loop when i is 3 -


QC1 = 1
while QC1 < 6:
print(QC1)
if QC1 == 3:
break
QC1 +=1

1
2
3

THE CONTINUE STATEMENT


With the continue statement we can stop the current iteration, and continue with the next.

#EXAMPLE: Continue to the next iteration if i is 3 -


QC1 = 0
while QC1 < 6:
QC1 +=1
if QC1 == 3:
continue
print(QC1)

1
2
4
5
6

B.THE FOR LOOP


A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. The for
loop does not require an indexing variable to set beforehand.

#EXAMPLE: Print each fruit in a fruit list: -

fruits = ['apple', 'banana', 'cherry']


for x in fruits:
print(x)
apple
banana
cherry

THE BREAK STATEMENT


With the break statement we can stop the loop before it has looped through all the items:

#EXAMPLE: Exit the loop when x is "banana" -


fruits = ['apple', 'banana', 'cherry']
for x in fruits:
print(x)
if x == "banana":
break

apple
banana

THE RANGE FUNCTION


To loop through a set of code a speci ed number of times, we can use the range() function. The range()
function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and
ends at a speci ed number.

#EXAMPLE: Using the range() function -


for x in range(6):
print(x)

#Note that range(6) is not the values of 0 to 6, but the values 0 to 5

0
1
2
3
4
5

The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by
adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6).

for x in range(2, 6):


print(x)

2
3
4
5
TASK II Write a simple Python program to print even numbers between 1 - 20

You might also like