Print Command
- Print String
- Print Numeric
- Print String + Numeric
- Print String + String
- Print Numeric + Numeric
Print String
print("Hello World")
Hello Worldprint("Information and Network Engineering")
Information and Network Engineeringprint("Hello Anirach you will be success")
Hello Anirach you will be successprint("I'm hungry")
I'm hungryprint('He ask me "Who got the book?"')
He ask me "Who got the book?"print("I'm good and \"I will do my best\"")
I'm good and "I will do my best"print('/\\')
/\print('\ta\na\ta\ta\n\ta')
a
a a a
a aprint('''\ta a\ta\ta \ta'''
a a a
a
Print Numeric
print('100.00')
100.00print('%d' %100)
100print('%d' %100.58)
100print('%f' %-100.89)
-100.890000print('%.2f' %100.89)
100.89from math import pi
print('%.2f' %pi)
3.14from math import pi
print('%.4f' %pi)
3.1416from math import pi
print('%.50f' %pi)
3.14159265358979311599796346854418516159057617187500
Print String + Numeric
print('My age is', 25,'I have', 3500.50,'Bth.')
My age is 25 I have 3500.5 Bth.print('My age is %d I have %.2f Bth.' %(25,3500.50))
My age is 25 I have 3500.50 Bth.print('My age is' + str(25)+' I have '+ str(3500.50)+' Bth.')
My age is 25 I have 3500.5 Bth.print('5+4 =',5+4)
5+4 = 9print('5+4 = %.2f' %(5+4))
5+4 = 9.00print('5+4 = ' + str(5+4))
5+4 = 9
Print String + String
print("I'm Anirach","I'll keep practicing!")
I'm Anirach I'll keep practicing!print("I'm Anirach" + "I'll keep practicing!"
I'm Anirach I'll keep practicing!
Print Numeric + Numeric
print(1, 1, 2, 3, 5, 8, 13, 21, 34, 55)
1 1 2 3 5 8 13 21 34 55print('%d %d %d %d %d %d %d %d %d %d' %(1, 1, 2, 3, 5, 8, 13, 21, 34, 55))
1 1 2 3 5 8 13 21 34 55
Print() Exercises
Computer and Programming
Before we begin exploring the concepts of programming, you need to understand a few basic things about computers and how they work.
The physical devices that a computer is made of are referred to as the computer's hardware. The programs that run on a computer are referred to as software.
Computers can do such a wide variety of things because they can be programmed. This means that computers are not designed to do just one job, but to do any job that their programs tell them to do. A program is a set of instructions that a computer follows to perform a task.
Software
System software
- Operating Systems: Windows, Mac OS, Linux
- Utility Programs: Back up, Virus scanners, Compression
- Software Development: Assemblers, Compilers, Interpreter
Application software
- Microsoft word, PowerPoint, Pages, Editor, Photoshop
How Computer Store DATA
All data that is stored in a computer is converted to sequences of 0s and 1s.
A computer's memory is divided into tiny storage locations known as bytes. One byte is only enough memory to store a letter of the alphabet or a small number. In order to do anything meaningful, a computer has to have lots of bytes. Most computers today have millions, or even billions, of bytes of memory.
How Programs Work
A computer's CPU can only understand instructions that are written in machine language. Because people find it very difficult to write entire programs in machine language, other programming languages have been invented. The CPU is an electronic device that is designed to do specific things. In particular, the CPU is designed to perform operations such as the following:
- Reading a piece of data from main memory
- Adding two numbers
- Subtracting one number from another number
- Multiplying two numbers
- Dividing one number by another number
- Moving a piece of data from one memory location to another
- Determining whether one value is equal to another value
Fetch-Decode-Execute Cycle
Assembly language
# low-level language
The first assembly language was most likely that developed in the 1940s at Cambridge University for use with a historic computer known as the EDSAC
high level language
In the 1950s, a new generation of programming languages known as high-level
languages began to appear. A high-level language allows you to create
powerful
and complex programs without knowing how the CPU works and without writing
large numbers of low-level instructions. In addition, most high-level languages use
words that are easy to understand. For example, if a programmer were using
COBOL (which was one of the early high-level languages created in the 1950s), he
or she would write the following instruction to display the message Hello world on
the computer screen:
DISPLAY "Hello world"
Python is a modern, high-level programming language that we will use in this
course. In Python you would display the message Hello world with the following
instruction:
print('Hello world')
programming language
Compiler
Interprete
Program Design
Program development cycle
Programs must be carefully designed before they are written. During the design process, programmers use tools such as pseudocode and flowcharts to create models of programs.
Designing a Programming language
The process of designing a program is arguably the most important part of the cycle. You can think of a program's design as its foundation. If you build a house on a poorly constructed foundation, eventually you will find yourself doing a lot of work to fix the house! A program's design should be viewed no differently. If your program is designed poorly, eventually you will find yourself doing a lot of work to fix the program.
The process of designing a program can be summarised in the following two steps:
- Understand the task that the program is to perform.
- Determine the steps that must be taken to perform the task.
Task and Steps Example
For example, suppose someone asks you how to boil water. You might break down that task into a series of steps as follows:
- Pour the desired amount of water into a pot.
- Put the pot on a stove burner.
- Turn the burner to high.
- Watch the water until you see large bubbles rising. When this happens, the water is boiling.
This is an example of an algorithm, which is a set of well-defined logical steps that must be taken to perform a task. Notice that the steps in this algorithm are sequentially ordered. Step 1 should be performed before step 2, and so on. If a person follows these steps exactly as they appear, and in the correct order, he or she should be able to boil water successfully.
A programmer breaks down the task that a program must perform in a similar way. An algorithm is created, which lists all of the logical steps that must be taken. For example, suppose you have been asked to write a program to calculate and display the gross pay for an hourly paid employee. Here are the steps that you would take:
- Get the number of hours worked.
- Get the hourly pay rate.
- Multiply the number of hours worked by the hourly pay rate.
- Display the result of the calculation that was performed in step 3.
Of course, this algorithm isn't ready to be executed on the computer. The steps in this list have to be translated into code. Programmers commonly use two tools to help them accomplish this: pseudocode and flowcharts. Let's look at each of these in more detail.
Pseudocode
The word “pseudo” means fake, so pseudocode is fake code. It is an informal language that has no syntax rules and is not meant to be compiled or executed. Instead, programmers use pseudocode to create models, or “mock-ups,” of programs. Because programmers don't have to worry about syntax errors while writing pseudocode, they can focus all of their attention on the program's design. Once a satisfactory design has been created with pseudocode, the pseudocode can be translated directly to actual code.
Input the hourse worked Input the hourly pay rate calculate gross pay as hours worked Multiplied by pay rate display the gross pay
Flowchart
Flowcharting is another tool that programmers use to design programs. A flowchart is a diagram that graphically depicts the steps that take place in a program.Notice that there are three types of symbols in the flowchart: ovals, parallelograms, and a rectangle. Each of these symbols represents a step in the program, as described here:
- The ovals, which appear at the top and bottom of the flowchart, are called terminal symbols. The Start terminal symbol marks the program's starting point and the End terminal symbol marks the program's ending point.
- Parallelograms are used as input symbols and output symbols. They represent steps in which the program reads input or displays output.
- Rectangles are used as processing symbols. They represent steps in which the program performs some process on data, such as a mathematical calculation.
Draw.io
Input Process Output
Computer programs typically perform the following three-step process:
- Input is received.
- Some process is performed on the input.
- Output is produced.
Input is any data that the program receives while it is running. One common form of input is data that is typed on the keyboard. Once input is received, some process, such as a mathematical calculation, is usually performed on it. The results of the process are then sent out of the program as output.
Variable
Variable are:
- Storage location that have a name
- Storage location that have a name
fruit = 'apple'
fruit = 'orange'
* Pick variable name that represent data that variable will hold
Valid Variable Names
- Case sensitive. (Case matters!)
- Fruit and fruit are different variable
- Must start with a letter.
- Can contain numbers.
- Underscores allowed in variable names
- Not allowed: + -
first3letters = 'ABC' first_three_letters = 'ABC' firstThreeLetters. = 'ABC'
* Pick variable name that represent data that variable will hold
Reserved Keywords
False
def
if
raise
None
del
import
return
True
elif
in
try
and
else
is
while
as
except
lambda
with
assert
finally
nonlocal
yield
break
for
not
class
from
or
continue
global
pass
*** Function name also not recommend
Reserved Word
*** Function name also not recommend
Data Type
Basic Data Types
- Numeric
- Integer
- Floating point
- Boolean
- String
Composite Data Types
- List
- Tuple
- Dictionary
- Set
Numbers
- Use numbers directly in your source code
- Do not use quotation marks as they are for strings.
integer = 42
float = 4.2
a = b = c = d = 0.0
* Pick variable name that represent data that variable will hold
Example
t = True type(f)
boolx = 5 y = 7 x,y = y,x print ('x = %d y = %d' %(x,y))
x = 7 y = 5
Boolean
A Boolean variable can reference one of two values: True or False. Boolean variables are commonly used as flags, which indicate whether specific conditions exist.
hungry = True
leepy = False
Example
t =True Type(f)
boolf = False type(f) print(f)
False
String
- Represent text
- Surrounded by quotes
fruit = 'apple'
fruit = “apple”
string1, string2, string3 = '', 'Knife', 'Hammer Dance'
* Strings are start with ' or " and end with 'or "
Using Quotes within Strings
sentence = 'She said, "That is a great tasting apple!" '
sentence = " That's a great tasting apple! "
double = "She said, \"That 's a great tasting apple! \" "
single = 'She said, "That\'s a great tasting apple! " '
Python Operators
What are operators in python?
Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.
Expression Operation and Operand
y = x² + 2x + 1
y,x,1 is operand
=, +,exponent is operator
y = x² + 2x + 1 is expression
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc.
Operator | Meaning | Example |
---|---|---|
+ | Add two operands or unary plus | x + y+ 2 |
- | Subtract right operand from the left or unary minus | x - y- 2 |
* | Multiply two operands | x * y |
/ | Divide left operand by the right one (always results into float) | x / y |
% | Modulus - remainder of the division of left operand by the right | x % y (remainder of x/y) |
// | Floor division - division that results into whole number adjusted to the left in the number line | x // y |
** | Exponent - left operand raised to the power of right | x**y (x to the power y) |
Example
Arithmetic operators in Python
x = 15 y = 4 # Output: x + y = 19 print('x + y =',x+y) # Output: x - y = 11 print('x - y =',x-y) # Output: x * y = 60 print('x * y =',x*y) # Output: x / y = 3.75 print('x / y =',x/y) # Output: x // y = 3 print('x // y =',x//y) # Output: x ** y = 50625 print('x ** y =',x**y)
Output
x + y = 19 x - y = 11 x * y = 60 x / y = 3.75 x // y = 3 x ** y = 50625
Operator Precedence
The operator precedence in Python is listed in the following table. It is in descending order (upper group has higher precedence than the lower ones).
Operators | Meaning |
---|---|
() |
Parentheses |
** |
Exponent |
+x ,-x ,~x
|
Unary plus, Unary minus, Bitwise NOT |
*
,/ ,// ,%
|
Multiplication, Division, Floor division, Modulus |
+ ,-
|
Addition, Subtraction |
<< ,>>
|
Bitwise shift operators |
& |
Bitwise AND |
^ |
Bitwise XOR |
| |
Bitwise OR |
== ,!= ,> ,>= ,< ,<= ,is ,is not ,in ,not in
|
Comparisons, Identity, Membership operators |
not |
Logical NOT |
and |
Logical AND |
or |
Logical OR |
Comparison Operators
Comparison operators are used to compare values. It returns either or according to the
condition.True
False
Operator | Meaning | Example |
---|---|---|
> | Greater than - True if left operand is greater than the right | x > y |
< | Less than - True if left operand is less than the right | x < y |
== | Equal to - True if both operands are equal | x == y |
!= | Not equal to - True if operands are not equal | x != y |
>= | Greater than or equal to - True if left operand is greater than or equal to the right | x >= y |
<= | Less than or equal to - True if left operand is less than or equal to the right | x <= y |
Example
Comparison Operators in Python
x = 10 y = 12 # Output: x > y is False print('x > y is',x>y) # Output: x < y is True print('x < y is',x
= y is False print('x >= y is',x>=y) # Output: x <= y is True print('x <=y is',x<=y) Output
x > y is False x < y is True x==y is False x !=y is True x>= y is False x <= y is True
Logical Operators
Logical operators are the and
,or
,not
operators.
Operator | Meaning | Example |
---|---|---|
and | True if both the operands are true | x and y |
or | True if either of the operands is true | x or y |
not | True if operand is false (complements the operand) | not x |
Example
Logical Operators in Python
x = True y = False print('x and y is',x and y) print('x or y is',x or y) print('not x is',not x)
Output
x and y is False x or y is True not x is False
Bitwise Operators
Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.
For example, 2 is 10
in binary and 7 is 111
In the table below: Let x = 10 (0000 1010
in binary) and
y = 4
(0000 0100
in binary)
Operator | Meaning | Example |
---|---|---|
& | Bitwise AND | x & y = 0 (0000 0000 ) |
| | Bitwise OR | x | y = 14 (0000 1110 ) |
~ | Bitwise NOT | ~x = -11 (1111 0101 ) |
^ | Bitwise XOR | x ^ y = 14 (0000 1110 ) |
>> | Bitwise right shift | x >> 2 = 2 (0000 0010 ) |
<< | Bitwise left shift | x << 2 = 40 (0010 1000 ) |
Assignment Operators
Assignment operators are used in Python to assign values to variables.
a = 5
is a simple assignment operator that assigns the value 5 on the right to the
variable a
on the left.
There are various compound operators in Python like a += 5
that adds to the variable and
later assigns
the same. It is equivalent to a = a + 5
.
Operator | Example | Equivalent to |
---|---|---|
= | x = 5 | x = 5 |
+= | x += 5 | x = x + 5 |
-= | x -= 5 | x = x - 5 |
*= | x *= 5 | x = x * 5 |
/= | x /= 5 | x = x / 5 |
%= | x %= 5 | x = x % 5 |
//= | x //= 5 | x = x // 5 |
**= | x **= 5 | x = x ** 5 |
&= | x &= 5 | x = x & 5 |
|= | x |= 5 | x = x | 5 |
^= | x ^= 5 | x = x ^ 5 |
>>= | x >>= 5 | x = x >> 5 |
<<= | x <<= 5 | x = x << 5 |
Special Operators
Python language offers some special types of operators like the identity operator or the membership operator. They are described below with examples.
Identity Operators
is
>and are the identity operators in Python. They are used to check if two values (or
variables) are located on the same
part of the memory. Two variables that are equal does not imply that they are
identical.is not
Operator | Meaning | Example |
---|---|---|
is | True if the operands are identical (refer to the same object) | x is True |
is not | True if the operands are not identical (do not refer to the same object) | x is not True |
Example
Identity Operators in Python
x1 = 5 y1 = 5 x2 = 'Hello' y2 = 'Hello' x3 = [1,2,3] y3 = [1,2,3] # Output: False print(x1 is not y1) # Output: True print(x2 is y2) # Output: False print(x3 is y3)
Output
False True False
Here, we see that and are integers of the same values, so they are equal as well as identical. Same is the case with and (strings).
x1
y1
x2
y2
But and are lists. They are equal but not identical. It is because the interpreter locates them separately in memory although they are equal.
x3
y3
Membership Operators
in
and are the membership operators in Python. They are used to test whether a value or
variable is found in a sequence
(string, list, tuple, set and dictionary).not in
Operator | Meaning | Example |
---|---|---|
in | True if value/variable is found in the sequence | 5 in x |
not in | True if value/variable is not found in the sequence | 5 not in x |
Example
Membership Operators in Python
x = 'Hello world' y = {1:'a',2:'b'} # Output: True print('H' in x) # Output: True print('hello' not in x) # Output: True print(1 in y) # Output: False print('a' in y)
Output
True True True False
Here, is in but is not present in (remember, Python is case sensitive). Similarly, is key and is the value in dictionary . Hence, returns .
'H'
x
'hello'
x
1
'a'
y
'a' in y
False
Input
Input Strings
Programs commonly need to read input typed by the user on the keyboard. We will use the Python functions to do this.
Python's built-in input function to read input from the keyboard. The input
function reads a piece of data that has been entered at the keyboard and
returns that data, as a string, back to the program. You normally use the
input function in an assignment statement that follows this general format:
variable = input(prompt)
Example
Input Numbers
The input function always returns the users input as a string, even if the user enters numeric data. For example, suppose you call the input function, type the number 87, and press the Enter key. The value that is returned from the input function is the string '87'. This can be a problem if you want to use the value in a math operation. Math operations can be performed only on numeric values, not strings.
Function | Description |
---|---|
int(item) | You pass an argument to the int() function and it returns the argument's value converted to an int. |
float(item) | You pass an argument to the float() function and it returns the argument's value converted to a float. |
Method 1
- string_value = input('How many hours did you work? ')
- hours = int(string_value)
Method 2
- hours = int(input('How many hours did you work? '))
Read Multiple Values
Read Multiple Values From keyboard
Comments
Comments are notes of explanation that document lines or sections of a program. Comments are part of the program, but the Python interpreter ignores them. They are intended for people who may be reading the source code.