0% found this document useful (0 votes)
40 views41 pages

Python Manual

The document outlines an introduction to programming concepts like hardware, software, data storage, algorithms, and programming languages. It discusses using Python, program design, input/output, variables, arithmetic operators, data types, and type conversions. Key steps in program design are identified as understanding the problem, inputs, processing, and outputs. The print function and comments are described. Variable naming rules and reading keyboard input are also covered.

Uploaded by

nranjeet049
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
40 views41 pages

Python Manual

The document outlines an introduction to programming concepts like hardware, software, data storage, algorithms, and programming languages. It discusses using Python, program design, input/output, variables, arithmetic operators, data types, and type conversions. Key steps in program design are identified as understanding the problem, inputs, processing, and outputs. The print function and comments are described. Variable naming rules and reading keyboard input are also covered.

Uploaded by

nranjeet049
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 41

Outline:

o Introduction to computers and programming


o Hardware and software
o How computers store data
o How a program works
o Using python
o Designing a program
o Input, processing, and output
o Displaying output with the print function
o Comments
o Variables
o Reading input from the keyboard
o Performing calculations:
o Arithmetic Operator(s):
o Python Numbers and Type Conversion:
o Converting Numbers to Strings
o String concatenation
o Print function
o Decision structures and Boolean logic
o The if statement
o The if-else statement
o If — else Statement, if-elif-else Statements
o Logical operators
o Boolean variables
o Turtle graphics
o Introduction to repetition structure
o The while loop
o The for loop
o Break Keyword used in the while loop:
o Nested loop
o Infinite Loops
o Break keyword used in the for loop:
o Introductions to functions
o List
o Tuple
o Dictionaries
o Sets
o Introduction to file input and output
o Variables in Python
o Creating Variables
o Multi-line statements:
Introduction to computers and programming:
Hardware and software

➢ Hardware

o Processor
o Memory
o I/O units
➢ How does it work?

o Executes very simple instructions


o Executes them incredibly fast
o Must be programmed: it is the software, i.e., the programs that characterize what a
computer actually does.

Components of a computer:

How computers store data


How a program works:
Languages for programming a computer:

• Machine language

21 40 16 100 163 240

• Assembler language

iload intRate

bipush 100

if_icmpgt intError

• High level programming languages

if (intRate > 100)

Programs:
The programs characterize what a computer actually does.

A program (independently of the language in which it is written) is constituted by two fundamental parts:

• a representation of the information (data) relative to the domain of interest: objects

• a description of how to manipulate the representation in such a way as to realize the desired
functionality: operations

• To write a program both aspects have to be addressed.

Example: Call Center Application:

We want to realize a program for a call-center that handles requests for telephone numbers.
Specifically, a certain client requests the telephone number associated to a certain person name in a
certain city, and the operator answers to the request by selecting the telephone registry of the city
and searching there the telephone number corresponding to the person name.

Objects:
– Client

– Operator

– Telephone registry – telephone numbers, person names, cities - these are just character
sequences (strings)

Operations:
• 1. request for the telephone number of a given person name in a given city, done by a client

• 2. selection of the telephone registry of the requested city, done by the operator
• 3. Search of the telephone number corresponding to the requested person name on the telephone
registry.

The program has to represent all objects that come into play and realize all operations.

Realization of operations:
Algorithms usually, we realize an operation when we need to solve a specific problem.

Example: given a person name, find the corresponding telephone number in a telephone registry. To
delegate to a computer the solution of a problem, it is necessary to find an algorithm that solves the
problem.

Algorithm:

Procedure is through which we obtain the solution of a problem. In other words, a sequence of
statements that, when executed one after the other, allow one to calculate the solution of the
problem starting from the information provided as input.

Example of an algorithm:

Scan the person names, one after the other as they appear in the registry, until you have found the
requested one; return the associated telephone number.

Are there other algorithms to solve the same problem? Yes!

Once we have found/developed an algorithm, we have to code it in the selected programming


language.

The edit-compile-verify cycle

Using Python:
Python is commonly used for developing websites and software, task automation, data analysis, and data
visualization. Since it's relatively easy to learn, Python has been adopted by many non-programmers such as
accountants and scientists, for a variety of everyday tasks, like organizing finances.

Designing a program
Program design consists of the steps a programmer should do before they start coding the program
in a specific language.
• Design the program

• Write the code

• Correct syntax error

• Test the program

• Correct logic errors

Understanding the Program


Understanding the purpose of a program usually involves understanding its:
• Inputs

• Processing

• Outputs

This IPO approach involves what the user must enter on the keyboard and what processing or
manipulations will be done.
Input, processing, and output
❑ Input:

Data that the program receives while it is running


❑ Perform some process on the input
Example: mathematical calculation
❑ Produces output

Displaying output with the print function


• Function: piece of prewritten code that performs an operation

• Print function: displays output on the screen

• Argument: data given to function

Example: data that is printed to screen

Comment
Comment: notes of explanation within a program
o Ignored by python interpreter

o Intended for a person reading the program’s code


o Begin with a # character

End line comment: appears at the end of a line of code


o Typically explains the purpose of that line

Variables
• Variable: name that represents a value stored in the computer memory

• Used to access and manipulate data stored in memory

• A variable references the value it represents

• Assignment statement: used to create a variable and make it reference data

• General format is variable = expression

• Assignment operator: the equal sign(=)

• Example: age=18

• In assignment statement, variable receiving value must be on left side

• Variable name should not be enclosed in quote marks


• Variable can only be use if a value is assigned to it

Variable naming rules


• Variable name cannot be a python key word

• Variable name cannot contain spaces

• First character must be a letter or an underscore

• After first character may use letter, digits, or underscores

• Variable names are case sensitive

Reading input from the keyboard


• Most programs need to a read input rom the user

• Built-in input function reads input from keyboard

• Format: variable= input(prompt)

Prompt is typically a string instructing user to enter a value


• Input function always returns a string

• Built in function covert between data types

int (item) converts item to an integer


float (item) coverts item to a float
Performing calculations:

Arithmetic Operator(s):
Python uses the following symbols (operators) in calculations:

+ Addition
- Subtraction
* Multiplication
/ Division
The order of operations (also called precedence rules) defines how an expression is to be evaluated.
Multiplication is granted higher precedence than addition. Thus, the expression 2 + 3 * 4 is
interpreted to have the value 2 + (3 * 4) = 14
So the rule is that unless we use brackets the multiplication and division precedes addition and
subtraction.

Read carefully the next 2 examples that demonstrate the syntax of Python arithmetic expressions:

a = 4
b = 2
x = (a + b) “ (a — b)
print(“Value of x: “, x)

Example 5:

The program will output: Va1ue of x: 12

Example 6:

a=4
b = a/2
c = (a + b) “ (a — b)
d=a+b“a—b
x = c —d
print(“Value of x: “, x)

The program will output: Va1ue of x: 2

Modulus operator
The modulus operator (%) returns the division remainder. For instance, when we divide 10/3 the
remainder is 1. When we divide 10/5 the remainder is 0. As you can see the modulus operator is used
to find if a number is divisible by another number.

Example 7:

a = 17
b = 5
c = a % b

The program will output: Va1ue of x: 2


Python Numbers and Type Conversion:

There are two numeric types in Python (there are also complex numbers which we will not
discuss):

int
float

int - they are called just integers or ints, are positive or negative whole numbers with no decimal
point.

float - they are called floats, they represent real numbers and are written with a decimal point
dividing the integer and decimal parts.

Example:
X 11 # integer
Y 3.14 # float

we can convert from one type to another with the int(), and float() functions.
Examples:
x 1 # assign int number
y 2.8 # assign float number

#convert from int to float:


a float(x)

#convert from float to int:


b int(y)
c int(12.95) # 12.95 will be converted to 12 d
int(5/3) # 5/3 will be converted to 1

# convert from int to float


float(10) # will be converted to 10.0 m
float(1+1+1) # will be converted to 3.0

Converting Numbers to Strings

Python converts numbers to strings through using the str() function. We’ll pass either a
number or a variable into the str() function, and, then that numeric value will be converted
into a string value.

Let’s first look at converting integers. To convert the integer 12 to a string value, you just pass 12
into the str() function:

str(12) # converts to string "12"

We also can use str() function to convert float numbers or float variables into a string:

str(1/2) # converts to string "0.5"


String concatenation:
Strings

A string can be any text inside double or single quotes.


Strings enclosed by double quotes:
myname = " akshay"
mycity = "kandhkot"

The process of combining strings is called "concatenation". In Python, you combine


(“concatenate”) strings with a (+) operator like this:

a = "alpha"
b = "bet:"
c=a + b

Here is another instance of concatenation. Note the use of a single character string " " used
to create a space between the firstName and familyName

firstname = "John"
familyname="Harris"
# (see the extra space)
fullname = firstname + " " + familyname

Print function:
Function print()

The print() function prints the specified message to the screen. The message can be a string, or
any other variable, the variable will be converted into a string before written to the screen.
Simple use of print() function.
Strings are enclosed in double quotes:
Example 1:

print (“Program begins“)


a=4
print (a)
b=2
print (b)

The program will output:


Program begins 4
2
The End

Use comma to separate variables:


if we want to print a combination of several variables and text string we must separate each
element by a comma character.

print (“Program begins“)


a = 4
b = 2
print (“value of a:“, a, “value of b:“, b);
print(“The End“)
Example 2:

The program will output:


Program begins
Value of a: 4
Value of b: 2
The End
How to print without line break
In Python we can use the ’end=’ parameter in the print function. By default the end parameter uses
’\n’ which is what creates the newline, but we can set a different value for the end parameter.
This tells it to end the string with a character of our choosing rather than ending with a newline.
This example uses a default version of the print() function which automatically adds a newline
character thus breaking the output line.

a = 1000
b = 2000
c = 3000
pri nt (a)
print (b)
print (c)
Example 3:
The program will output: 10 0
0
20 00
30 0 0

In contrast, this example ends each line with a comma character (except the last print() statement):

a = 1000
b = 2000
c = 3000
print (a , end=" ,")
print (b , end=" , ")
print (c)
Example 4:

The program will output: 10 00, 2000, 3000

Decision structures and Boolean logic:


A decision structure is a construct in a computer program that allows the program to make a decision and
change its behavior based on that decision. The decision is made based on the outcome of a logical test. A
logical test is a calculation whose outcome is either true or false.
Boolean Logic is a form of algebra which is centered around three simple words known as Boolean Operators:
“Or,” “And,” and “Not”.

Logical operators:
Python logical & comparison operators
Let’s recall the comparison and logical operators that were described in Python Primer:

Python logical & comparison


Expression operator
Equals
Does not equal !=
Greater than
Less than
Greater than or equal to >=
Less than or equal to <=
And And
Or Or

Explore the following example:


Example 1

a =0
b =a + l
if a > 0 or b > 0:
a= a + l
b=b+ l
1 f a > 0 and b > 0 :
a= a + l
b=b+ l
x=a+b
p rint: ("value of x:”,x)

Output:
Value of x: 5
If — else Statement, if-elif-else Statements

The if-else statement executes a block of code if a specified condition is true. If the condition is
false, another block of code is executed. Let’s explore the following code:
Example 1:

a =2
b =2
if a > b:
a = a * 2
b = b *2
else:
a = a + 1
b = b + 1
x = a +b
print(“Value of x: “, x)

The program will output: Value of x: 6


Let’s expand our understating of if-else syntax. Suppose we want to check for more than one
condition. The syntax for such a case is following — note the new construct “elif” :

if conditionl:
code to be executed if this condition is true;
elif condition2:
code to be executed if the first condition is false and this condition is true;
else:
code to be executed if all conditions arefalse; Here is a simple

demonstration (note the use of mandatory colons): Example 2

number =
-1 msg =
"
if number > 0:
msg = "Number is
positive" exif number‹
0:
msg = "Number is
negative" else:
msg = "Number is 0"
print(msg)

The program will output:


Number i s negative

Boolean variables and If-Else conditions:

Boolean can have only two values, True or False (the first letter must be capitalized). Let’s
explore how to use Boolean variables to control program flow using conditional statements. In the
following example it should be obvious that the block after the ‘if’ statement will be executed as
the condition is true.

Example 1
Output:
Value of x: 1
Let’s slightly modify the previous code:

Example 2

a =0
b = a >= 0 # the result of this comparison is True
if b:
a=a+1
x=a
print("value of x: " , x)

Output:
Value of x: 1

Let’s continue with further modifications: notice in the next example the test of two Boolean
values in the ‘if’ statement.

Example 3

Output:
Value of x: 1

The while loop:


The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is
true. The syntax is very similar to the if statement - as seen below.

While condition:
# execute code as long as condition is true
The while statement is the most basic loop construct in Python.
Example 1

n=0
while n < 2 :
n=n+1
x= n
print("value of x: ", x)

The next example prints all odd numbers between <1, 10>. Note that the ‘if’ statement that determines whether
a number is odd or even (if the remainder of division by 2 is not zero then by definition the number is odd).

n = 1
while n <= 10:
if n%2 != 0:
print(n, is an odd number")
n=n+1
Example 3

Output:
1 is an odd number
3 is an odd number
5 is an odd number
7 is an odd number
9 is an odd number
Break Keyword used in the while loop:

The break keyword is used to brea k out the loop. In the next example the while loop ends when
the condition (i > 5) is true

# end the loop if i is larger than 5


i = 1
while i < 10:
print(i)
if i > 5:
break
i- i* 1

Infinite Loops:
Working with while, loops present a challenge: a coding error can cause an infinite
loop. Infinite loop, as the name suggests, is a loop that will keep running forever. If
you accidentally make an infinite loop, it could crash your Python
interpreter.

The for loop:


The for loop is more complex, but it’s also the most commonly used loop. Frequently the for loops use
“range” which is a Python function — see the example:

Example 1

n = 0
for i in range(0, 2, 1):
n = n + 10
x= n
print("value of x: ", x)

Looking at the above example you might think that (range) is part of the (for loop) syntax. It is not. Range() is
a Python function which returns a sequence of integer numbers which in turn allows the for loop to iterate
over. Since range creates a fixed length list the for loop runs for a fixed number of iteration.

Syntax of the range function is: range(start, stop, step)

start isan integer number specifying at which position to start stopisan integer number specifying at which
position toend. step is an integer number specifying the incrimination.

It is very important to note that the sequence ends before the value (stop) is reached, in other words,
range() function generate numbers up to, but not including (stop) number

examples

range (0, 5, 1) # generates numerical sequence: 0, 1, 2, 3, 4


range (2, 9, 3) # generates numerical sequence: 2, 5, 8

Furthermore, values (start) and (step) are optional. Default for (start) is 0 and the default for (step) is 1. This
means that the following range definition:

range(0,10,1)

could be written as:

range(10) # generates numerical sequence 0,1,2,3,4,5,6,7,8,9

In the context of the for loop these two statements are identical

for i in range(0, 2, 1): for i in range(2):

Here are examples that illustrate the for loops behavior:

Example 2

# Output odd numbers in interval ‹0,9s


limit = 9
for n in range
(limit+1) if n%2
!= 0:
print(n, " is an odd number")

Output:

1 is an odd number

3 is an odd number

5 is an oddnumber

7 is an odd number

9 is an odd number

Let’s modify the above code — just iterate using odd numbers sequence (it will produce an identical output):

Example 3

# Output odd numbers in interval ‹0,9s


for n in range (1,10,2)
print(n, " is an odd number")
Yet another modification shows that the range sequence can be defined separately (producing an identical
output):

# Output odd numbers in interval ‹0,9s

a = range (l , 10, 2)
for n in a:
print(n, " is an odd number")
Example4

Break keyword used in the for loop:

We’ve already learned that the while loop can be terminated by the break keyword. The same
functionality applies for the “for loop” as the next example shows:

# end the loop if i is larger than 3:


for i in range(100):
if i > 3:
break
print(i)

Introductions to functions:
A Python function is a block of code designed to perform a particular task. A function is defined
with the (def) keyword, followed by a name (’maxnum’ in our example), followed by parentheses
(). A colon is used to specify the start of the function code.

Function names follow the same convention as variable names.

Important Rule:
Make sure that your function is declared before it is needed(called). Note that the body of
a function isn’t interpreted until the function is executed. HoweVer, the functions can be
defined in any order, as long as all are defined before any executable code uses a
function. So let’s repeat:

The rule: All functions must be defined before any code that does real work

Therefore, put all the statements that do work last.


r=a
if (r < b):
r = b
return r
u = 10
x)
v = 20
Example 1

Note about the distinction between parameters and arguments:

When we talk about functions, the terms “parameters” and “arguments” are often
interchangeably used as if it were one and the same thing but there is a very subtle difference:

a)
Parameters are variables listed as a part of the function definition.

b)
Arguments are values passed to the function when it is invoked.

The scope of a variable explained

The Python code below defines function ‘maxnum’

def maxnum (a, b): r a;


if r < b:
r b;
return r

Note that the function defines variable r. This variable exists inside the function ‘maxnum’. For
other functions this variable is invisible. The technical term for this feature is called scope. It
means that the variable r has only a local scope. Local scope means: within the scope of the
function ‘maxnum’. If we define variables outside of any function then the scope of such a
variable is global. This means: anywhere in our program a global variable can be accessed and
modified.

It is very important to grasp the distinction between local and global variables. Therefore let’s
re-state this again:

We know that Python defines a variable using an assignment statement:


x=1 # this statement defines variable x

If this statement is defined inside a function body the scope (or the visibility) of this
declaration/assignment is limited to the body of the function. However, if this
statement is placed outside of any function then the scope of defined variables is gl obal.
It is not a good coding technique to use global variables as it leads to many problems.
An experienced programmer can use under certain conditions global variables; Python
certainly allows that. But for our purposes, we will avoid using global variables!

To repeat one more time: the scope refers to the visibility of variables. This means which parts of
your program can see or use it. The coding technique implemented in this course limits a
variable’s scope to a single function.

How is this done? Let’s explore the next example, which is going to be a template for all our
examples:

# a Python Program Template


def main():

some code here . .


. # end of main()

def
someFunction()
: some code
here .
# end of someFunction()

main()

What you see is a call to function main (at the very end of the program sequence) which passes
the code execution to the body of the function main. In other words, all action happens inside the
body of the function main. Other functions are called directly or indirectly from the main
function. This style ensures that all variables
have a local scope - which is our objective. This seemingly unnecessary complication of enclosing
all Python code in one or several functions guarantees the reliability of our code.

Remember we’ve established a rule for ordering the functions stated like this: the functions
can be defined in any order, as long as all are defined before any executable code
uses a function.
The presented template puts the executable code in one line of code - main() which must be
placed as the very last statement! Let’s demonstrate this using the following example:
# Python program that does NOT use global variables def main
() :
a = 10
b = 20
x = maxnum(a, b)
p ri nt(”Val ue of x: ” , x)
# end of main()
def maxnum(a, b):
r=a
if r < b:
r = b
return r
# end of maxnum()
# call to the 'main' function MUST BE THE LAST statement
main()

Example 1

List:
What is a list? A list is a special variable, which can hold more than one value at a time. Let’s say we have a list of
numbers. Storing them in single variables would look like this:
numberl 200
number2 300
number3 400

But if we wanted to use a loop to find a specific number, that would be difficult — especially for large set of
numbers. The solution is to use a list. The list can hold many values under a single name, and you can access the
values by referring to an index number:
myList [200, 300, 400]

Essential list characteristics are


A list can hold many values under a single name
List elements are accessed using their index number
The indexing operator [ ] selects a single element from a sequence. The expression inside square brackets is
called the index, and must be an integer value.
List indexes start with 0. [0] is the first list element, [1] is the second, [2] is the third, etc.

Python (as most modern languages) uses so-called zero-based indexing. This is extremely important! Let’s
remember and repeat:
[0] the index of the first element
[1] the index of the second element
if the list length is defined as len then [Ien-1] is the index of the last element
informally lists and arrays are treated as identical concepts. However, Python does make a distinction between lists
and arrays (although they are very similar).
However, we will not discuss the concept of Python arrays in this manual.
Creating a list
Syntax:
listName [iteml, item2, .]

Example :
numbers = [200, 300, 400] # this list has 3 elements
Access the Elements of a list

You access a list element by referring to the index number. This statement accesses the value of the first
element in ‘numbers’:
someVariable = numbers[0] # the first element

The List length function len()


The length property of a list returns the number of its elements.
Example:
primes = [2, 3, 5, 7]
x = len(primes) # the length of primes is 4

Empty List Definition


An empty list is defined as the following
myList = [] # define an empty list x = len(myList) # the length is zero

Example defines and initiates a list. Consequently, list elements are assigned random values:

String Elements in List


A list can contain string elements
Example:
colors = ["red", print(colors[0]) "green", "orange", "blue"] # outputs ’red’
print(colors[3])
# outputs ’blue’

Boolean Elements in List


Here is an example of a list that has 3 elements, all of them set to False (capitalized):
boolVector = [False, False, False]

List Functions
Add a new item to a list — append():
Function append adds an element to the end of the list

fruits = [] # let begin with an empty list fruits.append("Apple") # sets fruits[0] to "Apple"
fruits.append("Mango") # sets fruits[1] to "Mango"

It should be self-evident that after ‘append’ is executed the list length is incremented by 1.
Delete last element from list — pop()
Function pop removes the last element of a list; the list length drops by 1
fruits ["Orange", "Lemon", "Avocado"]
fruits.pop() # Removes the last element ("Avocado") from list
Delete an element from a list by index using del operator

The del operator removes an element at the specified index location from the list. Example:

values [100, 200, 300, 400, 500, 600]


# Use del to remove by an index del values[2]
print(values)

Insert an element at the specified position using insert function


The insert() function inserts an element at the specified index. Syntax:
listName.insert(index, element)

Example:

values [100, 200, 300, 400, 500, 600]

values.insert(2,999) # insert 999 into positionvalues[2] print(values)


values.insert(0,777) # insert 777 into positionvalues[0] print(values)

It is obvious that each insert increments the list length by 1.

Remove all elements from a list — clear() function The clear() function removes all the elements from a
list.
Syntax
listName.clear()

Example:

metals = ["iron", "copper", "silver", "zinc"]


metals.clear() # removes all elements — len(metals) returns 0
The following example shows all list functions in action:

Looping List Elements, Cop y List, Print List


Looping List Elements

Suppose you need to construct a loop that will iterate over all list elements. We know how to do it using the
function range():

numbers = [100, 200, 300a


length = ten(numbers)
for i in range(length)
xx = numbers[i]
pint(xx)

Output:
10 0
20 0
300

However, Python allows to loop through all the elements of a list. The previous example could be rewritten
(and simplified) as the following (producing identical output):

numbers = [100, 200, 300a


for xx in numbers:
pint(xx)

How to make a copy of the list


You cannot create a copy by the following assignment
a [100, 200, 300]
b a # this assignment does not make a copy of a

Make a copy of a list with the list() method:

numberSet1 = [101, 102, 103, 104a


numberSet2 = list(numberSet1)
print(numberSet2)

example 3

Print lists in different ways

Let’s explore the ways to print a list:

a)
we’ve already seen the simplest possible way:
a [1, 2, 3, 4, 5]
print(a)

b)
print a list using a loop
a [1, 2, 3, 4, 5]
for y in a:
print(y)

c)
print a list using a loop and make the output a single line (no line breaks):
a [1, 2, 3, 4, 5]
for y in a:
print(y, end=" ")

Comparing floating numbers, passing variable & list

Comparison of floating-point numbers


Due to rounding errors, most floating-point numbers end up being slightly imprecise.
This means that numbers expected to be equal often differ slightly, and a simple equality
test fails. The next example illustrates the problem:

a = 0.15 + 0.15
b = 0.1 + 0.2
i f a == b:
print(”Values a and b are equal ”) e1se:
print(”Val ues a and b are NOT equal ”)

Example 1

Output:
Values a and b are NOT equal

Merge Lists:

Merge algorithm takes two sorted lists as input and produce a single list as output, containing
all the elements of both input lists in sorted order.

Let’s show the process using real data:

Input Lists:
listl = [1, 3, 4, 5]
list2 = [2, 4, 6, 8]

Output list (merged):


List3 = [1, 2, 3, 4, 4, 5, 6, 8]

Multi-line statements:
You cannot split a statement into multiple lines in Python by pressing Enter . Instead, use the
backslash ( \ ) to indicate that a statement is continued on the next line. For example this
statement:

a 5 6 7

could be re-written as the following: (note the backslash characters at the end of lines):
a 5 \
6 \
7

Input-Output in Python
Python provides some built-in functions to perform both input and output operations.

In order to print the output, python provides us with a built-in function called print().

Example:

Print(“Hello Python”)
Output:

Hello Python

Files in Python
A file is a named location on the disk which is used to store the data permanently.

Here are some of the operations which you can perform on files:

• open a file
• read file

Variables in Python:

Variables: A Python variable name can be a single letter or a descriptive name

Python rules for naming variables:


• Variable names cannot contain spaces.
• A variable starts with a letter A to Z or a to z or an underscore (_) followed by zero or
more letters, underscores and digits (0 to 9)
• Python does not allow punctuation characters such as @, $, and % within variables
• Variable names are case-sensitive.
Creating Variables:

Unlike other programming languages, Python has no command for declaring a variable. A
variable is created the moment you first assign a value to it:
a = 100

This means: variable (a) has been created and assigned value 100.

Python tuple :

Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-
in data types in Python used to store collections of data, the other 3 are List, Set,
and Dictionary, all with different qualities and usage. A tuple is a collection which is
ordered and unchangeable. Tuples are written with round brackets

• Unchangeable
• Ordered
• Allow duplicates
Tuple Length

To determine how many items a tuple has, use the len() function:
Dictionaries:

Dictionaries are used to store data values in key: value pairs. A dictionary is a
collection which is ordered*, changeable and do not allow duplicates. Dictionaries
are written with curly brackets, and have keys and values:

Dictionary Items

Dictionary items are ordered, changeable, and does not allow duplicates.Dictionary
items are presented in key: value pairs, and can be referred to by using the key
name.

• Ordered

• Changeable

• Duplicate not allowed


Output :

Ford
Python sets
Sets are used to store multiple items in a single variable. Set is one of 4 built-in
data types in Python used to store collections of data, the other 3 are List, Tuple,
and Dictionary, all with different qualities and usage. A set is a collection which
is unordered, unchangeable*, and unindexed. Sets are written with curly brackets.

Output

{Cherry,banana,apple}
Python turtle graphics
turtle is a pre-installed Python library that enables users to create pictures and
shapes by providing them with a virtual canvas. The onscreen pen that you use for
drawing is called the turtle and this is what gives the library its name. In short, the
Python turtle library helps new programmers get a feel for what programming with
Python is like in a fun and interactive way.
With the Python turtle library, you can draw and create various types of shapes and
images. Here’s a sample of the kinds of drawings you can make with turtle:

Moving the Turtle


There are four directions that a turtle can move in:

• Forward
• Backward
• Left
• Right

The turtle moves .forward() or .backward() in the direction that it’s facing. You can
change this direction by turning it .left() or .right() by a certain degree. You can
try each of these commands like so:
Output

You might also like