0% found this document useful (0 votes)
8 views

Unit I

Uploaded by

Abhishek Kumar
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)
8 views

Unit I

Uploaded by

Abhishek Kumar
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/ 74

CSE90D: COMPUTER PROGRAMMING

USING PYTHON
Unit 1: History and basic
Python syntax

▶ Python History and Versions


▶ Python laid its foundation in the late 1980s.
▶ The implementation of Python was started in December 1989
by Guido Van Rossum at CWI in Netherland.
▶ In February 1991, Guido Van Rossum published the code
(labeled version 0.9.0) to alt.sources.
▶ In 1994, Python 1.0 was released with new features like
lambda, map, filter, and reduce.
Cont..

▶ Python 2.0 added new features such as list comprehensions,


garbage collection systems.
▶ On December 3, 2008, Python 3.0 (also called "Py3K") was
released. It was designed to rectify the fundamental flaw of
the language.
▶ ABC programming language is said to be the predecessor of
Python language, which was capable of Exception Handling and
interfacing with the Amoeba Operating System.
▶ The following programming languages influence Python:
▶ ABC language.
▶ Modula-3
Versions in Python

▶ Version 1: Python 1.0


▶ In January 1994, the first version of Python 1.0 was
released. This version 1 includes the major new
features like the functional programming
tools filter, reduce, map, and lambda etc.
▶ Version 2: Python 2.0
▶ After Six and a half years later, Python 2.0 was
introduced in October 2000. In this release, a full
garbage collector, list comprehensions were included,
and it also supports Unicode.
Cont..

▶ Version 3: Python 3.0


▶ Python then after 8 years, the next major release was made.
This release was Python 3.0 also known as Py3K or ―Python
3000.
▶ ▶ The major changes in Python 3.0 are:
▶ In this version, Print is a Python function
▶ Instead of lists, in this version, we have Views and iterators
Python Latest version:

▶ The Python latest version is 3.10.1. This stable version


was released on 6 DEC.
New syntax features:
• Structural Pattern Matching: Specification
• Structural Pattern Matching: Motivation and Rationale
• Structural Pattern Matching: Tutorial
• Parenthesized context managers are now officially allowed.

Interpreter improvements:
• Precise line numbers for debugging and other tools.

New typing features:


• Allow writing union types as X | Y
• Explicit Type Aliases
• Parameter Specification Variables
Check Python Version:

▶ Most of the operating system will have python already


installed. To check which Python version you have in
your system you can:
▶ Open Command prompt,
▶ Run the following command.

Installing python
▶ The Python download requires about 25 Mb of disk space; keep
it on your machine, in case you need to re-install Python.
When installed, Python requires about an additional 90 Mb of
disk space.
▶ Downloading
▶ Click Python Download. The following page will appear in your
browser.
Cont..

▶ Click the Windows link (two lines below the Download


Python 3.10.1 button). The following page will appear
in your browser
Cont..

▶ Click on the Download Windows x86-64 executable


installer link under the top-left Stable Releases.The
following pop-up window titled Opening python-3.10-
amd64.exe will appear.

Cont..

▶ Click the Save File button.


▶ The file named python-3.10.1-amd64.exe should start downloading
into your standard download folder. This file is about 30 Mb so it might
take a while to download fully if you are on a slow internet connection
(it took me about 10 seconds over a cable modem).
▶ The file should appear as
▶ Move this file to a more permanent location, so that you can install
Python (and reinstall it easily later, if necessary).
▶ Feel free to explore this webpage further; if you want to just continue
the installation, you can terminate the tab browsing this webpage.
▶ Start the Installing instructions directly below.
Cont..

▶ Installing
▶ Double-click the icon labeling the file python-
3.10.1- amd64.exe.A Python 3.3.10.1 (64-bit)
Setup pop-up window will appear.
Cont..

▶ Ensure that the Install launcher for all users (recommended) and
the Add Python 3.10 to PATH checkboxes at the bottom are checked.
▶ If the Python Installer finds an earlier version of Python installed on
your computer, the Install Now message may instead appear as Upgrade
Now (and the checkboxes will not appear).
▶ Highlight the Install Now (or Upgrade Now) message, and then click it.
When run, a User Account Control pop-up window may appear on your
screen. I could not capture its image, but it asks, Do you want to allow
this app to make changes to your device.
▶ Click the Yes button. A new Python 3.10.1 (64-bit) Setup pop-up window
will appear with a Setup Progress message and a progress bar.

Cont..
Cont..

▶ During installation, it will show the various components


it is installing and move the progress bar towards
completion. Soon, a new Python 3.10.1 (64-bit)
Setup pop-up window will appear with a Setup was
successfully message.
▶ Click the Close button.
Environment
▶ The venv module provides support for creating lightweight
―virtual environments with their own site directories,
optionally isolated from system site directories.

▶ Each virtual environment has its own Python binary (which


matches the version of the binary that was used to create this
environment) and can have its own independent set of
installed Python packages in its site directories.

▶ A virtual environment is a directory tree which contains


Python executable files and other files which indicate that it
is a virtual environment.

▶ Common installation tools such as setuptools and pip work as


expected with virtual environments. In other words, when a
virtual environment is active, they install Python packages into
the virtual environment without needing to be told to do so
explicitly.
Variables
▶ Variables are nothing but reserved memory locations to
store values. This means that when you create a
variable you reserve some space in memory.
▶ Based on the data type of a variable, the interpreter
allocates memory and decides what can be stored in the
reserved memory.
▶ Therefore, by assigning different data types to
variables, you can store integers, decimals or characters
in these variables.
Assigning Values to Variables

▶ Python variables do not need explicit declaration to


reserve memory space. 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 −

▶ #!/usr/bin/python
▶ counter = 100 # An integer assignment
▶ miles = 1000.0 # A floating point
▶ name = "John" # A string
▶ print counter
▶ print miles
▶ print name
Cont..

▶ Here, 100, 1000.0 and "John" are the values assigned


to counter, miles, and name variables, respectively.
This produces the following result −
▶ 100
▶ 1000.0
▶ John
Multiple Assignment

▶ Python allows you to assign a single value to several


variables simultaneously. For example −
▶ a=b=c=1
▶ Here, an integer object is created with the value 1, and
all three variables are assigned to the same memory
location. You can also assign multiple objects to
multiple variables.
▶ For example −
▶ a,b,c = 1,2,"john"
Python Variable Types: Local &
Global
▶ There are two types of variables in Python, Global
variable and Local variable.
▶ Example:
▶ Let us define variable in Python where the variable "f"
is global in scope and is assigned value 101 which is printed in
output
▶ Variable f is again declared in function and
assumes local scope. It is assigned value "I am learning
Python." which is printed out as an output. This Python declare
variable is different from the global variable "f" defined earlier
▶ Once the function call is over, the local variable f is destroyed.
At line 12, when we again, print the value of "f" is it displays
the value of global variable f=101
Executing python from the command
line
▶ A Python interactive session will allow you to write a lot
of lines of code, but once you close the session, you
lose everything you‘ve written.
▶ That‘s why the usual way of writing Python programs is
by using plain text files. By convention, those files will
use the .py extension. (On Windows systems the
extension can also be .pyw.)
▶ Python code files can be created with any plain text
editor. If you are new to Python programming, you can
try Sublime Text, which is a powerful and easy-to-use
editor, but you can use any editor you like.
Cont..

▶ To keep moving forward in this tutorial, you‘ll need to


create a test script. Open your favorite text editor and
write the following code:
▶ #!/usr/bin/env python3
▶ print('Hello World!')
▶ Save the file in your working directory with the
name hello.py. With the test script ready, you can
continue reading.
Using the python Command

▶o run Python scripts with the python command, you


need to open a command-line and type in the
word python, or python3 if you have both versions,
followed by the path to your script, just like this:
▶ $ python3 hello.py
▶ Hello World!
▶ If everything works okay, after you press Enter, you‘ll
see the phrase Hello World! on your screen. That‘s it!
You‘ve just run your first Python script!
Redirecting the Output

▶ Sometimes it‘s useful to save the output of a script for


later analysis. Here‘s how you can do that:
▶ $ python3 hello.py > output.txt
▶ This operation redirects the output of your script
to output.txt, rather than to the standard system
output (stdout).
▶ The process is commonly known as stream redirection
and is available on both Windows and Unix-like systems.
Python - IDLE

▶ IDLE (Integrated Development and Learning


Environment) is an integrated development
environment (IDE) for Python.

The Python installer for Windows contains the IDLE


module by default.
▶ IDLE is not available by default in Python distributions
for Linux. It needs to be installed using the respective
package managers
Cont..

▶ IDLE can be used to execute a single statement just like


Python Shell and also to create, modify, and execute
Python scripts.
▶ IDLE provides a fully-featured text editor to create
Python script that includes features like syntax
highlighting, auto completion, and smart indent.
▶ It also has a debugger with stepping and breakpoints
features.
Editing python files

▶ Filesin python can be appended to, deleted and overwritten.


When writing to a file in Python, text cannot be inserted into
the middle of a file, and will require rewriting it.
▶ When opening a file to edit with open(file, mode="r"), set
mode to "w" to write to a file or "a" to append to the end of a
file.
▶ Setting mode to w will create the file specified if it does not
exist, and overwrite the file if it does exist.
▶ Use file.write(s) to write the string s into the file and
returns the number of characters written.
▶ Use file.writelines(lines) to write multiple lines of text to a file
by specifying the strings to add as a sequence such as a list or
tuple.
Python documentation

▶ Importance of documenting your code.


▶ But if not, then let me quote something Guido
mentioned to me at a recent PyCon:
▶ ―Code is more often read than written.
▶ — Guido van Rossum
▶ When you write code, you write it for two primary
audiences: your users and your developers (including
yourself).
▶ Both audiences are equally important. If you‘re like me,
you‘ve probably opened up old codebases and wondered
to yourself, ―What in the world was I thinking?
Cont..

▶ If you‘re having a problem reading your own code,


imagine what your users or other developers are
experiencing when they‘re trying to use or contribute to
your code.
▶ Conversely, I‘m sure you‘ve run into a situation where
you wanted to do something in Python and found what
looks like a great library that can get the job done.
▶ However, when you start using the library, you look for
examples, write-ups, or even official documentation on
how to do something specific and can‘t immediately
find the solution.
Getting help
▶ Python help()
▶ The help() method calls the built-in Python help system.
▶ The syntax of help() is:
▶ help(object)
▶ help() Parameters
▶ The help() method takes a maximum of one parameter.
▶ object (optional) - you want to generate the help of the
given object
Cont..

▶ How help() works in Python?


▶ The help() method is used for interactive use. It's
recommended to try it in your interpreter when you
need help to write Python program and use Python
modules.
▶ Note: object is passed to help() (not a string)
Cont..

▶ Try these on Python shell.


▶ >>> help(list)
▶ >>> help(dict)
▶ >>> help(print)
▶ >>> help([1, 2, 3])
▶ If string is passed as an argument, name of a module,
function, class, method, keyword, or documentation
topic, and a help page is printed.
▶ Note: string is passed as an argument to help()
Dynamic types

▶ Python variable assignment is different from some of


the popular languages like c, c++ and java. There is no
declaration of a variable, just an assignment statement.
▶ When we declare a variable in C or alike languages,
this sets aside an area of memory for holding values
allowed by the data type of the variable.
▶ The memory allocated will be interpreted as the data
type suggests. If it‘s an integer variable the memory
allocated will be read as an integer and so on.
Cont..

▶ When we assign or initialize it with some value, that


value will get stored at that memory location. At
compile time, initial value or assigned value will be
checked. So we cannot mix types.
▶ Example: initializing a string value to an int variable is
not allowed and the program will not compile.
▶ But Python is a dynamically typed language. It doesn‘t
know about the type of the variable until the code is
run. So declaration is of no use.
▶ As it will get to know the type of the value at run-time.
Output:<class 'int'> <class 'str'>

Example

▶ # This will store 6 in the memory and binds the


▶ # name x to it. After it runs, type of x will
▶ # be int.
▶ x=6
▶ print(type(x))
▶ # This will store 'hello' at some location int
▶ # the memory and binds name x to it. After it
▶ # runs type of x will be str.
▶ x = 'hello'
▶ print(type(x))
▶ Output:
▶ <class 'int'>
▶ <class 'str'>
Python reserved words and naming
conventions
▶ There is one more restriction on identifier names. The Python language
reserves a small set of keywords that designate special language
functionality. No object can have the same name as a reserved word.
▶ In Python 3.6, there are 33 reserved keywords:

Python
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
Python Identifier Naming Rules
▶ Rules for naming Identifiers in Python
▶ So we know what a Python Identifier is. But can we name it
anything? Or do certain rules apply?
▶ Well, we do have five rules to follow when naming identifiers
in Python:
▶ a. A Python identifier can be a combination of lowercase/
uppercase letters, digits, or an underscore. The following
characters are valid:
▶ Lowercase letters (a to z)
▶ Uppercase letters (A to Z)
▶ Digits (0 to 9)
▶ Underscore (_)
Cont..

▶ Some valid names are:


▶ myVar
▶ var_3
▶ this_works_too
▶ b. An identifier cannot begin with a digit.
Some valid names:
▶ _9lives
▶ lives9
▶ An invalid name:
▶ 9lives
Basic syntax

▶ First Python Program

▶ Let us execute programs in different modes of programming.

▶ Interactive Mode Programming

▶ Invoking the interpreter without passing a script file as a parameter brings up the
following prompt −

▶ $ python Python 2.4.3 (#1, Nov 11 2010, 13:34:43) [GCC 4.1.2 20080704 (Red Hat
4.1.2-48)] on linux2 Type "help", "copyright", "credits" or "license" for more
information.

▶ >>>

▶ Type the following text at the Python prompt and press the Enter −

▶ >>> print "Hello, Python!―

▶ If you are running new version of Python, then you would need to use print
statement with parenthesis as in print ("Hello, Python!");. However in Python
version 2.4.3, this produces the following result −

▶ Hello, Python!
Cont..
▶ We assume that you have Python interpreter set in PATH
variable. Now, try to run this program as follows −
▶ $ python test.py
▶ This produces the following result −
▶ Hello, Python! Let us try another way to execute a
Python script. Here is the modified test.py file −
▶ #!/usr/bin/python print "Hello, Python!―
▶ We assume that you have Python interpreter available
in /usr/bin directory. Now, try to run this program as
follows −
▶ $ chmod +x test.py # This is to make file executable
$./test.py
▶ This produces the following result −
▶ Hello, Python!
Comments in Python
▶ Comments are descriptions that help programmers
better understand the intent and functionality of the
program.
▶ They are completely ignored by the Python interpreter.
▶ Advantages of Using Comments
▶ Using comments in programs makes our code more
understandable. It makes the program more readable
which helps us remember why certain blocks of code
were written.
▶ Other than that, comments can also be used to ignore
some code while testing other blocks of code. This
offers a simple way to prevent the execution of some
lines or write a quick pseudo-code for the program.

Single-Line Comments in
Python
▶ In Python, we use the hash symbol # to write a single-
line comment.
▶ Example 1: Writing Single-Line Comments
▶ # printing a string print('Hello world') Output
▶ Hello world
▶ Here, the comment is:
▶ # printing a string
Multi-Line Comments in
Python
▶ Python doesn't offer a separate way to write multiline
comments. However, there are other ways to get around this
issue.
▶ We can use # at the beginning of each line of comment on
multiple lines.
▶ Example 2: Using multiple #
▶ # it is a
▶ # multiline
▶ # comment
▶ Here, each line is treated as a single comment and all of them
are ignored.
Cont..
▶ Strings are amongst the most popular types in Python.
We can create them simply by enclosing characters in
quotes. Python treats single quotes the same as double
quotes. Creating strings is as simple as assigning a value
to a variable. For example −
▶ var1 = 'Hello World!'
▶ var2 = "Python Programming―
▶ Computers do not deal with characters, they deal with
numbers (binary). Even though you may see characters
on your screen, internally it is stored and manipulated
as a combination of 0s and 1s.
▶ This conversion of character to a number is called
encoding, and the reverse process is decoding. ASCII and
Unicode are some of the popular encodings used.
Cont..

▶ In Python, a string is a sequence of Unicode characters.


Unicode was introduced to include every character in all
languages and bring uniformity in encoding. You can
learn about Unicode from Python Unicode.
Accessing Values in Strings

▶ Python does not support a character type; these are


treated as strings of length one, thus also considered a
substring.
▶ To access substrings, use the square brackets for slicing
along with the index or indices to obtain your substring.
For example −
▶ Live Demo
▶ #!/usr/bin/python
▶ var1 = 'Hello World!'
▶ var2 = "Python Programming"
▶ print "var1[0]: ", var1[0]
▶ print "var2[1:5]: ", var2[1:5]
Cont..

▶ When the above code is executed, it produces the


following result −
▶ var1[0]: H
▶ var2[1:5]: ytho
Updating Strings

▶ You can "update" an existing string by (re)assigning a


variable to another string. The new value can be related
to its previous value or to a completely different string
altogether. For example −
▶ #!/usr/bin/python
▶ var1 = 'Hello World!'
▶ print "Updated String :- ", var1[:6] + 'Python‗
▶ When the above code is executed, it produces the
following result −
▶ Updated String :- Hello Python
Escape Characters
▶ Following table is a list of escape or non-printable
characters that can be represented with backslash
notation.
▶ An escape character gets interpreted; in a single quoted
as well as double quoted strings.
Backslash Hexadecimal Description
notation character
\a 0x07 Bell or alert
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
Cont..

\nnn Octal notation,


where n is in the
range 0.7
\r 0x0d Carriage return
\s 0x20 Space
\t 0x09 Tab
\v 0x0b Vertical tab
\x Character x
\xnn Hexadecimal
notation, where n
is in the range 0.9,
a.f, or A.F
String Special Operators
▶ Assume string variable a holds 'Hello' and
variable b holds 'Python', then −

Operator Description Example

+ Concatenation - Adds values on a + b will give HelloPython


either side of the operator

* Repetition - Creates new strings, a*2 will give -HelloHello


concatenating multiple copies of
the same string

[] Slice - Gives the character from a[1] will give e


the given index

[:] Range Slice - Gives the characters a[1:4] will give ell
from the given range

in Membership - Returns true if a H in a will give 1


character exists in the given string
Cont..

Operator Description Example

not in Membership - Returns true if a character does not M not in a will give 1
exist in the given string

r/R Raw String - Suppresses actual meaning of Escape print r'\n' prints \n and print R'\n'prints \n
characters. The syntax for raw strings is exactly
the same as for normal strings with the exception
of the raw string operator, the letter "r," which
precedes the quotation marks. The "r" can be
lowercase (r) or uppercase (R) and must be placed
immediately preceding the first quote mark.

% Format - Performs String formatting See at next section


String Formatting Operator
▶ One of Python's coolest features is the string format
operator %. This operator is unique to strings and makes
up for the pack of having functions from C's printf()
family. Following is a simple example −
▶ #!/usr/bin/python
▶ print "My name is %s and weight is %d kg!" % ('Zara', 21)
▶ When the above code is executed, it produces the
following result −
▶ My name is Zara and weight is 21 kg!
Here is the list of complete set of symbols which can
be used along with % −

Format Symbol Conversion


%c character
%s string conversion via str() prior to
formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase 'e')
Cont..

Format Symbol Conversion

%E exponential notation (with UPPERcase 'E')

%f floating point real number

%g the shorter of %f and %e

%G the shorter of %f and %E


Built-in String Methods
Sr.N Methods with Description
o.

1 capitalize()Capitalizes first letter of string


2 center(width, fillchar)Returns a space-padded string with the original
string centered to a total of width columns.

3 count(str, beg= 0,end=len(string))Counts how many times str occurs in


string or in a substring of string if starting index beg and ending index
end are given.
4 decode(encoding='UTF-8',errors='strict')Decodes the string using the
codec registered for encoding. encoding defaults to the default string
encoding.
5 encode(encoding='UTF-8',errors='strict')Returns encoded string version
of string; on error, default is to raise a ValueError unless errors is given
with 'ignore' or 'replace'.
The format() Method for Formatting
Strings
▶ The format() method that is available with the string
object is very versatile and powerful in formatting
strings.
▶ Format strings contain curly braces {} as placeholders or
replacement fields which get replaced.
Cont..
▶We can use positional arguments or keyword arguments to
specify the order.
▶ # Python string format() method
▶ # default(implicit) order
▶ default_order = "{}, {} and {}".format('John','Bill','Sean')
▶ print('\n--- Default Order ---')
▶ print(default_order)
▶ # order using positional argument
▶ positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')
▶ print('\n--- Positional Order ---')
▶ print(positional_order)
▶ # order using keyword argument
▶ keyword_order = "{s}, {b} and
{j}".format(j='John',b='Bill',s='Sean')
▶ print('\n--- Keyword Order ---')
▶ print(keyword_order)
Common Python String Methods
▶ There are numerous methods available with the string
object. The format() method that we mentioned above
is one of them. Some of the commonly used methods
are lower(), upper(), join(), split(), find(), replace() etc
▶ Here is some of all the built-in methods to work with
strings in Python.
▶ Python String capitalize()
▶ Python String center()
▶ Python String count()
▶ Python String encode()
▶ Python String endswith()
▶ Python String expandtabs()
Numeric data types
▶ Data types are the classification or categorization of
data items. It represents the kind of value that tells
what operations can be performed on a particular data.
Since everything is an object in Python programming,
data types are actually classes and variables are
instance (object) of these classes.
▶ Following are the standard or built-in data type of
Python:
▶ Numeric
▶ Sequence Type
▶ Boolean
▶ Set
▶ Dictionary
Cont..
Cont..
▶ In Python, numeric data type represent the data which has
numeric value. Numeric value can be integer, floating number
or even complex numbers. These values are defined
as int, float and complex class in Python.
▶ Integers – This value is represented by int class. It contains
positive or negative whole numbers (without fraction or
decimal). In Python there is no limit to how long an integer
value can be.
▶ Float – This value is represented by float class. It is a real
number with floating point representation. It is specified by a
decimal point. Optionally, the character e or E followed by a
positive or negative integer may be appended to specify
scientific notation.
▶ Complex Numbers – Complex number is represented by
complex class. It is specified as (real part) + (imaginary part)j.
For example – 2+3j
Conversion function
▶ Type Conversion
▶ We can convert one type of number into another. This is
also known as coercion.
▶ Operations like addition, subtraction coerce integer to
float implicitly (automatically), if one of the operands is
float.
▶ >>> 1 + 2.0 3.0
▶ We can see above that 1 (integer) is coerced into 1.0
(float) for addition and the result is also a floating point
number.
Cont..

▶ We can also use built-in functions


like int(), float() and complex() to convert between
types explicitly. These functions can even convert
from strings.
▶ >>> int(2.3) 2 >>> int(-2.8) -2 >>> float(5) 5.0 >>>
complex('3+5j') (3+5j)When converting from float to
integer, the number gets truncated (decimal parts are
removed).
simple output
▶ The simplest way to produce output is using the print() function where
you can pass zero or more expressions separated by commas. This
function converts the expressions you pass into a string before writing to
the screen.
▶ Syntax: print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
▶ Parameters:
value(s) : Any value, and as many as you like. Will be converted to
string before printed

sep=’separator’ : (Optional) Specify how to separate the objects, if
there is more than one.Default :’ ‘

end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
file : (Optional) An object with a write method. Default :sys.stdout

flush : (Optional) A Boolean, specifying if the output is flushed (True)
or buffered (False). Default: False
▶ Returns: It returns output to the screen.
Cont..
▶ Code #1: Using print() function in Python(2.x)
▶ # One object is passed
▶ print "GeeksForGeeks"
▶ # Four objects are passed
▶ print "Geeks", "For", "Geeks", "Portal"
▶ l = [1, 2, 3, 4, 5]
▶ # printing a list
▶ print l
▶ Output:
▶ GeeksForGeeks
▶ Geeks For Geeks Portal
▶ [1, 2, 3, 4, 5]
Code #2 : Using print() function in Python(3.x)
▶ # One object is passed
▶ print("GeeksForGeeks")
▶ x=5
▶ # Two objects are passed
▶ print("x =", x)
▶ # code for disabling the softspace feature
▶ print('G', 'F', 'G', sep ='')
▶ # using end argument
▶ print("Python", end = '@')
▶ print("GeeksforGeeks")
▶ Output:
▶ GeeksForGeeks
▶ x=5
▶ GFG
▶ Python@GeeksforGeeks
simple input
▶ Most programs today use a dialog box as a way of asking
the user to provide some type of input. While Python
provides us with two inbuilt functions to read the input
from the keyboard.

▶ input ( prompt )
▶ raw_input ( prompt )

▶ input ( ) : This function first takes the input from the


user and then evaluates the expression, which means
Python automatically identifies whether user entered a
string or a number or list. If the input provided is not
correct then either syntax error or exception is raised
by python. For example –
Cont..

▶ # Python program showing


▶ # a use of input()
▶ val = input("Enter your value: ")
▶ print(val)
Cont..
▶ raw_input ( ) : This function works in older version (like
Python 2.x). This function takes exactly what is typed
from the keyboard, convert it to string and then return
it to the variable in which we want to store. For
example –
▶ # Python program showing
▶ # a use of raw_input()
▶ g = raw_input("Enter your name : ")
▶ print g
▶ Here, g is a variable which will get the string value,
typed by user during the execution of program. Typing
of data for the raw_input() function is terminated by
enter key.
Python print()
▶ The print() function prints the given object to the
standard output device (screen) or to the text stream
file.
▶ The full syntax of print() is:
▶ print(*objects, sep=' ', end='\n', file=sys.stdout,
flush=False)
▶ Return Value from print()
▶ It doesn't return any value; returns None.
▶ print() with separator and end parameters
▶ a=5
▶ print("a =", a, sep='00000', end='\n\n\n')
▶ print("a =", a, sep='0', end='')

You might also like