0% found this document useful (0 votes)
44 views23 pages

Untitled

The print() function in Python prints objects to the screen. It takes object(s) as parameters and converts them to strings before printing. Optional parameters like sep, end, and file allow customizing the output. The print() function is used to display text, variables, and the results of expressions. Import statements enable importing modules and their contents like classes, functions, and variables for use in a Python program. The input() function allows user input in Python programs.

Uploaded by

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

Untitled

The print() function in Python prints objects to the screen. It takes object(s) as parameters and converts them to strings before printing. Optional parameters like sep, end, and file allow customizing the output. The print() function is used to display text, variables, and the results of expressions. Import statements enable importing modules and their contents like classes, functions, and variables for use in a Python program. The input() function allows user input in Python programs.

Uploaded by

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

print ():

- The print() function in Python is used to print a specified message on the screen. The
print command in Python prints strings or objects which are converted to a string while
printing on a screen.

- The python print() function as the name suggests is used to print a python object(s) in
Python as standard output.

Parameters:

Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all
objects get converted into strings.

sep: It is an optional parameter used to define the separation among different objects to be
printed. By default an empty string(“”) is used as a separator.

end: It is an optional parameter used to set the string that is to be printed at the end. The
default value for this is set as line feed(“\n”).

file: It is an optional parameter used when writing on or over a file. By default,, it is set to
produce standard output as part of sys.stdout.

flush: It is an optional boolean parameter to set either a flushed or buffered output. If set
True, it takes flushed else it takes buffered. By default, it is set to False.

Example 0: Printing the classic Hello world!

Import time

Print (“Hello World!”)


Time.sleep(3)

Output:

Output at the Screen

1
Output ay the Python IDLE

Invoking the Python IDLE:

Right Click on the Python file, select Edit with IDLE 3.10
(64-bit) and then click “run”

Invoking the Python Output Console:

2
Right Click on the Python file, click open or Double Click on the Python file.

import:

- Python import statement enables the user to import particular modules in the
corresponding program.
- It resembles the #include header_file in C/C++.

As soon as the interpreter encounters the import statement in a particular code, it searches for
the same in the local scope and imports the module, if present in the search path.

It searches for a particular module in its built-in modules section at first. If it’s not found, it
searches those modules in its current directory.

A module is loaded only once in a particular program, without being affected by the
number of times the module is imported.

The true power of modules is that they can be imported and reused in other code. Consider the
following example:

>>> import math

>>>math.pi

3.141592653589793

3
In the first line, import math, you import the code in the math module and make it available to
use. In the second line, you access the pi variable within the math module. math is part of
Python’s standard library, which means that it’s always available to import when you’re running
Python.

Note that you write math.pi and not just simply pi. In addition to being a module, math
acts as a namespace that keeps all the attributes of the module together. Namespaces are
useful for keeping your code readable and organized.

You can list the contents of a namespace with dir():

>>> import math

>>>dir()

['__annotations__', '__builtins__', ..., 'math']

>>>dir(math)

['__doc__', ..., 'nan', 'pi', 'pow', ...]

Using dir() without any argument shows what’s in the global namespace. To see the contents of
the math namespace, you use dir(math).

The following code imports only the pi variable from the math module:

>>> from math import pi

>>> pi

3.141592653589793

>>>math.pi

NameError: name 'math' is not defined

Note that this places pi in the global namespace and not within a math namespace.

4
You can also rename modules and attributes as they’re imported:

>>> import math as m

>>>m.pi

3.141592653589793

>>> from math import pi as PI

>>> PI

3.141592653589793

Importing class/functions from a module


We can import classes/functions from a module using the syntax:

from {module} import {class/function}

ex:

from collections import OrderedDict


from os import path
from math import pi

print(pi)

Output:

3.141592653589793

The import * Statement


All the methods and constants of a particular module can be imported using import * operator.

from math import *


print(pi)
print(floor(3.15))

Output:

3.141592653589793

5
from math import *
print(pi)
print(factorial(6))

Output:

3.141592653589793

720

Python’s import as Statement


The import as statement helps the user provide an alias name to the original module name.

# python import as
import math as M

print(M.pi)
print(M.floor(3.18))

Output:

3.141592653589793

Print() continuation….
Example 1: Printing python objects
# sample python objects

Import time

list = [1,2,3]
tuple = ("A","B")
string = "Geeksforgeeks"

# printing the objects


print(list,tuple,string)
time.sleep(3)

Output:

[1, 2, 3] ('A', 'B') Geeksforgeeks

6
Example 2: Printing objects with a separator
# sample python objects

Import time

list = [1,2,3]
tuple = ("A","B")
string = "Geeksforgeeks"

# printing the objects


print(list,tuple,string, sep="<<..>>")
time.sleep(3)

Output:

[1, 2, 3]<<..>>('A', 'B')<<..>>Geeksforgeeks

Let us print 8 blank lines. You can type:

print (8 * "\n")

or:

print ("\n\n\n\n\n\n\n\n\n")

Example 3: Specifying the string to be printed at the end

# sample python objects

import time

list = [1,2,3]
tuple = ("A","B")
string = "Geeksforgeeks"

# printing the objects


print(list,tuple,string, end="<<..>>")
time.sleep(3)

Output:

[1, 2, 3] ('A', 'B') Geeksforgeeks<<..>>

7
Example 4: Printing and Reading contents of an external file.

For this, we will also be using the Python open() function and then print its contents. We
already have the following text file saved in our system with the name geeksforgeeks.txt.

To read and print this content we will use the below code:

import time

# open and read the file


my_file = open("geeksforgeeks.txt","r")

# print the contents of the file


print(my_file.read())
time.sleep(3)

Output:

8
input():

To input data into a program, we use input().


This function reads a single line of text, as a String.

Here's a program that reads the user's name and greets them:
This is the template for capturing string input…

import time

print("What is your name?")


name = input() # read a single line and store it in the variable "name"
print("Hi " + name + "!")

time.sleep(5)

Example take integer input in Python 3:

Simple example code taking integer input we have to typecast those


inputs into integers by using Python built-in int() function.
This is the template for capturing numeric input…

import time

age = int(input("Enter age: "))

print(age)
print(type(age))

time.sleep(3)

Output:

9
Another Example:
import time

# string input
print ("Enter the value of a; ")
input_a = input()

# print type
print(type(input_a))

print ("Enter the value of b; ")


# integer input
input_b = int(input())

# print type
print(type(input_b))

time.sleep(3)

Output:

10
Python Round to The Nearest Whole Number:
To round to the nearest whole number in Python, you can use the round() method. You should
not specify a number of decimal places to which your number should be rounded.

Here’s an example of using round() without the second parameter to round a number to its
nearest whole value:
number = 24.28959
print(round(number))

Our Python code returns: 24.

The round() function is usually used with floating-point numbers, which include decimal
places. You can also pass integers into round() without returning an error. With that said, our
program will return the same values because integers are already round numbers.

Optionally, you can specify 0 as a second argument instead of omitting it entirely. This will also
round a value to the nearest whole number. But since the 0 is the default value, we did not
specify it in this example.
The round() function can also be used to round a negative number.

Example:
import time
import math

x=(math.pi)
y=(round(x))

print(x)
time.sleep(3)

print(y)
time.sleep(3)

11
With Python’s round() function we can round decimal places up and down. The function needs
two arguments for that. The first is the value to round. The second is the number of digits after
the decimal point.

ex:
a=round(12.54673, 2)
print(a)

# Returns: 12.55

Another example:
z=round(3.141592, 3)
print(z)
time.sleep(3)

# Returns: 3.142

Python Color:
We can use the built-in colorama module of Python to print colorful text. It is a cross-platform
printing module. In this, colored text can be done using Colorama’s constant shorthand for
ANSI escape sequences. Just import from coloroma module and get your desired output.

import colorama
import time
from colorama import Fore

print(Fore.YELLOW + 'This text is YELLOW in color')


print(Fore.RED + 'This text is RED in color')
print(Fore.BLUE + 'This text is BLUE in color')
print(Fore.GREEN + 'This text is GREEN in color')
time.sleep(3)

12
Output:

Another example:
from colorama import Fore
from colorama import Style
import time

print(f"This is {Fore.GREEN}color{Style.RESET_ALL}!")
time.sleep(3)

Output:

13
Coloring in the Python IDLE!

Put this at the "start" of your code:

import time
import sys

try:
color = sys.stdout.shell
except AttributeError:
raise RuntimeError("Use IDLE")

And then use color.write(YourText,Color) for "printing":

color.write("Hi, are you called Miharu461? \n","KEYWORD")


color.write("Yes","STRING")
color.write(" or ","KEYWORD")
color.write("No\n","COMMENT")

Type these:

#This will manifest only in the PYTHON IDLE!

import time
import sys

try:
color = sys.stdout.shell
except AttributeError:
raise RuntimeError("Use IDLE")

color.write("Hi, are you called Miharu461? \n","KEYWORD")


color.write("Yes","STRING")
color.write(" or ","KEYWORD")
color.write("No\n","COMMENT")

time.sleep(3)

14
Output:

15
Another example:
import time
import sys

try: color = sys.stdout.shell


except AttributeError: raise RuntimeError("Use IDLE")

color.write("COLOR PRODUCED BY:SYNC \n","SYNC")


color.write("COLOR PRODUCED BY:stdin \n","stdin")
color.write("COLOR PRODUCED BY:BUILTIN \n","BUILTIN")
color.write("COLOR PRODUCED BY:STRING \n","STRING")
color.write("COLOR PRODUCED BY:console \n","console")
color.write("COLOR PRODUCED BY:COMMENT \n","COMMENT")
color.write("COLOR PRODUCED BY:stdout \n","stdout")
color.write("COLOR PRODUCED BY:TODO \n","TODO")
color.write("COLOR PRODUCED BY:stderr \n","stderr")
color.write("COLOR PRODUCED BY:hit \n","hit")
color.write("COLOR PRODUCED BY:DEFINITION \n","DEFINITION")
color.write("COLOR PRODUCED BY:KEYWORD \n","KEYWORD")
color.write("COLOR PRODUCED BY:ERROR \n","ERROR")
color.write("COLOR PRODUCED BY:sel \n","sel")

#The "Colors" you can put are: SYNC, stdin, BUILTIN, STRING, console, COMMENT, stdout,
TODO, stderr, hit, DEFINITION, KEYWORD, ERROR, and #sel.

time.sleep(3)

Output:

Only in IDLE!!!

16
Printing ASCII characters:

Python code using ord function :


ord() : It converts the given string of length one, returns an integer representing the Unicode
code point of the character. For example, ord(‘a’) returns the integer 97.

Ex1:

import time

c = 'A'
# print the ASCII value of assigned character in c
print("The ASCII value of '" + c + "' is", ord(c))

time.sleep(3)

Output:

Another example:

Here is a method to print the ASCII value of the characters in a string using python.

Ex2:

import time

print("Enter a String: ", end="")


text = input()

textlength = len(text)

for char in text:


ascii = ord(char)
print(char, "\t", ascii)

time.sleep(10)

17
Output:

Python Program - Shutdown Computer

import os

check = input("Want to shutdown your computer ? (y/n): ")


if check == 'n':
exit()
else:
os.system("shutdown /s /t 1")

Output:

18
Python Program - Restart Computer

# Python Program - Restart Computer

import os

check = input("Want to restart your computer ? (y/n): ")


if check == 'n':
exit()
else:
os.system("shutdown /r /t 1")

Output:

# Python Program - Shutdown and Restart Computer

import os

print("1. Shutdown Computer")


print("2. Restart Computer")
print("3. Exit")

choice = int(input("\nEnter your choice: "));


if(choice>=1 and choice<=2):
if choice == 1:
os.system("shutdown /s /t 1")
else:
os.system("shutdown /r /t 1")
else:
exit()

19
Output:

Alignment of text:

import time

text = input("Enter text: ")


# left aligned
print('{:<30}'.format(text))
# Right aligned
print('{:>50}'.format(text))
# centered
print('{:^30}'.format(text))

time.sleep(3)

Output:

20
Generating Random Letter:

To generate random letter, we need to import random and string modules.

#Generating Random String:

import string
import random
import time

# Randomly choose a letter from all the ascii_letters


randomLetter = random.choice(string.ascii_letters)
print(randomLetter)
time.sleep(1)

randomLetter = random.choice(string.ascii_letters)
print(randomLetter)
time.sleep(1)

randomLetter = random.choice(string.ascii_letters)
print(randomLetter)
time.sleep(1)

time.sleep(3)

Output:

21
Generating Random Number:

To generate random number in Python, randint() function is used. This function is defined in
random module.

# Program to generate a random number between 0 and 9


# importing the random module

import random

print(random.randint(0,9))

Note that we may get different output because this program generates random number in
range 0 and 9.

The syntax of this function is:

random.randint(a,b)

This returns a number N in the inclusive range [a,b], meaning a <= N <= b,

where the endpoints are included in the range.

Ex:

import time
import random

print(random.randint(0,9))
time.sleep(1)

print(random.randint(50,100))
time.sleep(1)

print(random.randint(1,20))
time.sleep(1)

time.sleep(3)

22
23

You might also like