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

Python Syntax

The document discusses various ways to take input in Python, including raw_input(), input(), and split(). It also covers typecasting input to integers, floats, and strings. Additionally, it summarizes different methods for formatting output in Python like print(), format strings, and the format() method.

Uploaded by

Subir Mukherjee
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
207 views

Python Syntax

The document discusses various ways to take input in Python, including raw_input(), input(), and split(). It also covers typecasting input to integers, floats, and strings. Additionally, it summarizes different methods for formatting output in Python like print(), format strings, and the format() method.

Uploaded by

Subir Mukherjee
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Input

Taking input in Python


Developers often have a need to interact with users, either to get data or to provide some sort
of result. 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.

 raw_input ( prompt )
 input ( prompt )

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. We can
use raw_input() to enter numeric data also. In that case we use typecasting. For more details
on typecasting refer this.

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.

# Python program showing


# a use of input()
val = input("Enter your value: ")
print(val)
num = input ("Enter number :")
print(num)
name1 = input("Enter name : ")
print(name1)

How the input function works in Python :


 When input() function executes program flow will be stopped until the user has given
an input.
 The text or message display on the output screen to ask a user to enter input value is
optional i.e. the prompt, will be printed on the screen is optional.
 Whatever you enter as input, input function convert it into a string. if you enter an
integer value still input() function convert it into a string. You need to explicitly convert
it into an integer in your code using typecasting.
Typecasting the input to Integer: There might be conditions when you might require
integer input from user/Console, the following code takes two input(integer/float) from
console and typecasts them to integer then prints the sum.

# input
num1 = int(input())
num2 = int(input())

# printing the sum in integer


print(num1 + num2)

Typecasting the input to Float: To convert the input to float the following code will work
out.
# input
num1 = float(input())
num2 = float(input())
# printing the sum in float
print(num1 + num2)

Typecasting the input to String: All kind of input can be converted to string type whether
they are float or integer. We make use of keyword str for typecasting.
# input
string = str(input())
# output
print(string)

Taking multiple inputs from user in Python

Developer often wants a user to enter multiple values or inputs in one line. In C++/C user can
take multiple inputs in one line using scanf but in Python user can take multiple values or
inputs in one line by two methods.
 Using split() method
 Using List comprehension

Using split() method :


This function helps in getting a multiple inputs from user . It breaks the given input by the
specified separator. If separator is not provided then any white space is a separator.
Generally, user use a split() method to split a Python string but one can used it in taking
multiple input.
Syntax :
input().split(separator, maxsplit)
Example :
# Python program showing how to

# multiple input using split


# taking two inputs at a time

x, y = input("Enter a two value: ").split()

print("Number of boys: ", x)

print("Number of girls: ", y)

print()

# taking three inputs at a time

x, y, z = input("Enter a three value: ").split()

print("Total number of students: ", x)

print("Number of boys is : ", y)

print("Number of girls is : ", z)

print()

# taking two inputs at a time

a, b = input("Enter a two value: ").split()

print("First number is {} and second number is {}".format(a, b))

print()

# taking multiple inputs at a time

# and type casting using list() function

x = list(map(int, input("Enter a multiple value: ").split()))

print("List of students: ", x)


Output:
OUTPUT

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)

print() Parameters

objects - object to the printed. * indicates that there may be more than one object

sep - objects are separated by sep. Default value: ' '

end - end is printed at last

file - must be an object with write(string) method. If omitted it, sys.stdout will be used which
prints objects on the screen.

flush - If True, the stream is forcibly flushed. Default value: False

Note: sep, end, file and flush are keyword arguments. If you want to use sep argument, you
have to use:

print(*objects, sep = 'separator')

not

print(*objects, 'separator')

Example 1: How print() works in Python?


print("Python is fun.")

a=5

# Two objects are passed

print("a =", a)

b=a

# Three objects are passed


print('a =', a, '= b')

When you run the program, the output will be:

Python is fun.

a=5

a=5=b

In the above program, only objects parameter is passed to print() function (in all
three print statements).

Hence,

 ' ' separator is used. Notice, the space between two objects in output.
 end parameter '\n' (newline character) is used. Notice, each print statement displays
the output in the new line.
 file is sys.stdout. The output is printed on the screen.
 flush is False. The stream is not forcibly flushed.

Python | end parameter in print()

By default python’s print() function ends with a newline. A programmer with C/C++
background may wonder how to print without newline.

Python’s print() function comes with a parameter called ‘end’. By default, the value of
this parameter is ‘\n’, i.e. the new line character. You can end a print statement with
any character/string using this parameter.

# This Python program must be run with

# Python 3 as it won't work with 2.7.

# ends the output with a <space>

print("Welcome to" , end = ' ')

print("GeeksforGeeks", end = ' ')

Output :

Welcome to GeeksforGeeks

One more program to demonstrate working of end parameter.


# This Python program must be run with

# Python 3 as it won't work with 2.7.

# ends the output with '@'

print("Python" , end = '@')

print("GeeksforGeeks")

Output :

Python@GeeksforGeeks

Python | Output Formatting

There are several ways to present the output of a program, data can be printed in a
human-readable form, or written to a file for future use. Sometimes user often wants
more control the formatting of output than simply printing space-separated values.
There are several ways to format output.

To use formatted string literals, begin a string with f or F before the opening
quotation mark or triple quotation mark.

The str.format() method of strings help a user to get a fancier Output

User can do all the string handling by using string slicing and concatenation
operations to create any layout that user wants. The string type has some methods
that perform useful operations for padding strings to a given column width.

Formatting output using String modulo operator(%) :

The % operator can also be used for string formatting. It interprets the left argument
much like a printf()-style format string to be applied to the right argument. In Python,
there is no printf() function but the functionality of the ancient printf is contained in
Python. To this purpose, the modulo operator % is overloaded by the string class to
perform string formatting. Therefore, it is often called string modulo (or sometimes
even called modulus) operator.

String modulo operator ( % ) is still available in Python(3.x) and user is using it


widely. But nowadays the old style of formatting is removed from the language.

filter_none
edit

play_arrow

brightness_4

# Python program showing how to use

# string modulo operator(%) to print

# fancier output

# print integer and float value

print("Geeks : % 2d, Portal : % 5.2f" %(1, 05.333))

# print integer value

print("Total students : % 3d, Boys : % 2d" %(240, 120))

# print octal value

print("% 7.3o"% (25))

# print exponential value

print("% 10.3E"% (356.08977))

Output :

Geeks : 1, Portal : 5.33

Total students : 240, Boys : 120

031

3.561E+02
There are two of those in our example: “%2d” and “%5.2f”. The general syntax for a
format placeholder is:

%[flags][width][.precision]type

Let’s take a look at the placeholders in our example.

The first placeholder “%2d” is used for the first component of our tuple, i.e. the
integer 1. The number will be printed with 2 characters. As 1 consists only of one
digits, the output is padded with 1 leading blanks.

The second one “%8.2f” is a format description for a float number. Like other
placeholders, it is introduced with the % character. This is followed by the total
number of digits the string should contain. This number includes the decimal point
and all the digits, i.e. before and after the decimal point.

Our float number 05.333 has to be formatted with 5 characters. The decimal part of
the number or the precision is set to 2, i.e. the number following the “.” in our
placeholder. Finally, the last character “f” of our placeholder stands for “float”.

Formatting output using format method :

The format() method was added in Python(2.6). Format method of strings requires
more manual effort. User use {} to mark where a variable will be substituted and can
provide detailed formatting directives, but user also needs to provide the information
to be formatted. This method lets us concatenate elements within an output through
positional formatting. For Example –

Code 1:

filter_none

edit

play_arrow

brightness_4
# Python program showing

# use of format() method

# using format() method

print('I love {} for "{}!"'.format('Geeks', 'Geeks'))

# using format() method and refering

# a position of the object

print('{0} and {1}'.format('Geeks', 'Portal'))

print('{1} and {0}'.format('Geeks', 'Portal'))

Output :

I love Geeks for "Geeks!"

Geeks and Portal

Portal and Geeks

The brackets and characters within them (called format fields) are replaced with the
objects passed into the format() method. A number in the brackets can be used to
refer to the position of the object passed into the format() method.

Code 2:

# Python program showing

# a use of format() method

# combining positional and keyword arguments


print('Number one portal is {0}, {1}, and {other}.'

.format('Geeks', 'For', other ='Geeks'))

# using format() method with number

print("Geeks :{0:2d}, Portal :{1:8.2f}".

format(12, 00.546))

# Changing positional argument

print("Second argument: {1:3d}, first one: {0:7.2f}".

format(47.42, 11))

print("Geeks: {a:5d}, Portal: {p:8.2f}".

format(a = 453, p = 59.058))

Output:

Number one portal is Geeks, For, and Geeks.

Geeks :12, Portal : 0.55

Second argument: 11, first one: 47.42

Geeks: 453, Portal: 59.06

The following diagram with an example usage depicts how the format method works
for positional parameters:

Code 3:

# Python program to

# show format () is

# used in dictionary
tab = {'geeks': 4127, 'for': 4098, 'geek': 8637678}

# using format() in dictionary

print('Geeks: {0[geeks]:d}; For: {0[for]:d}; ''Geeks: {0[geek]:d}'.format(tab))

data = dict(fun ="GeeksForGeeks", adj ="Portal")

# using format() in dictionary

print("I love {fun} computer {adj}".format(**data))

Output:

Geeks: 4127; For: 4098; Geeks: 8637678

I love GeeksForGeeks computer Portal

Formatting output using String method :

In this output is formatted by using string slicing and concatenation operations. The
string type has some methods that help in formatting a output in an fancier way.
Some of method which help in formatting a output are str.ljust(), str.rjust(),
str.centre()

# Python program to

# format a output using

# string() method

cstr = "I love geeksforgeeks"

# Printing the center aligned

# string with fillchr


print ("Center aligned string with fillchr: ")

print (cstr.center(40, '#'))

# Printing the left aligned

# string with "-" padding

print ("The left aligned string is : ")

print (lstr.ljust(40, '-'))

# Printing the right aligned string

# with "-" padding

print ("The right aligned string is : ")

print (rstr.rjust(40, '-'))

Output:

Center aligned string with fillchr:

##########I love geeksforgeeks##########

The left aligned string is :

I love geeksforgeeks--------------------

The right aligned string is :

--------------------I love geeksforgeeks

Using List comprehension :


List comprehension is an elegant way to define and create list in Python. We can create lists
just like mathematical statements in one line only. It is also used in getting multiple inputs
from a user.
Example:

# Python program showing

# how to take multiple input

# using List comprehension

# taking two input at a time

x, y = [int(x) for x in input("Enter two value: ").split()]

print("First Number is: ", x)

print("Second Number is: ", y)

print()

# taking three input at a time

x, y, z = [int(x) for x in input("Enter three value: ").split()]

print("First Number is: ", x)

print("Second Number is: ", y)

print("Third Number is: ", z)

print()

# taking two inputs at a time

x, y = [int(x) for x in input("Enter two value: ").split()]

print("First number is {} and second number is {}".format(x, y))

print()

# taking multiple inputs at a time

x = [int(x) for x in input("Enter multiple value: ").split()]

print("Number of list is: ", x)


Output :

STRING

String Literals

String literals in python are surrounded by either single quotation marks, or double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example

print("Hello")

print('Hello')

Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal sign and the
string:

Example

a = "Hello"

print(a)

Multiline Strings

You can assign a multiline string to a variable by using three quotes:

Example
You can use three double quotes:

a = """Lorem ipsum dolor sit amet,

consectetur adipiscing elit,

sed do eiusmod tempor incididunt

ut labore et dolore magna aliqua."""

print(a)

Or three single quotes:

Example

a = '''Lorem ipsum dolor sit amet,

consectetur adipiscing elit,

sed do eiusmod tempor incididunt

ut labore et dolore magna aliqua.'''

print(a)

Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of bytes representing
unicode characters.

However, Python does not have a character data type, a single character is simply a string with a
length of 1. Square brackets can be used to access elements of the string.

Example

Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"

print(a[1])

Example
Substring. Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])

Run example »

Example
The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "


print(a.strip()) # returns "Hello, World!"

Run example »

Example
The len() method returns the length of a string:

a = "Hello, World!"
print(len(a))

Run example »

Example
The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower())

Run example »

Example
The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())

Run example »

Example
The replace() method replaces a string with another string:

a = "Hello, World!"
print(a.replace("H", "J"))
Run example »

Example
The split() method splits the string into substrings if it finds instances of the
separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

Run example »

Learn more about String Methods with our String Methods Reference

String Format
As we learned in the Python Variables chapter, we cannot combine strings
and numbers like this:

Example
age = 36
txt = "My name is John, I am " + age
print(txt)

Run example »

But we can combine strings and numbers by using the format() method!

The format() method takes the passed arguments, formats them, and
places them in the string where the placeholders {} are:

Example
Use the format() method to insert numbers into strings:

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

Run example »

The format() method takes unlimited number of arguments, and are placed
into the respective placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

Run example »

You can use index numbers {0} to be sure the arguments are placed in the
correct placeholders:

Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

Loops in Python:

A while loop statement in Python programming language repeatedly executes a target


statement as long as a given condition is true.

Syntax
The syntax of a while loop in Python programming language is −
while expression:
statement(s)
Example

count = 0

while (count < 9):

print (“The count is:”, count)

count = count + 1

print ("Good bye!")

It has the ability to iterate over the items of any sequence, such as a list or a string.

For Loop Syntax

for iterating_var in sequence:

statements(s)

If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is
assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item in
the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is
exhausted.

Flow Diagram

for loop in Python

Example

for letter in 'Python': # First Example

print ('Current Letter :', letter)

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

for fruit in fruits: # Second Example

print ('Current fruit :', fruit)

print "Good bye!"

Array:
n = int(input('How many do you want to read?'))

alist = []

for i in range(n):

x = int(input('-->'))

alist.append(x)

for i in range(n):

print(alist[i])

Alternatively:

The above requires you to only enter a number at a time.

Another way of doing it is just to split the string.

x = input('Enter a bunch of numbers separated by a space:')


alist = [int(i) for i in x.split()]

The split() method returns a list of numbers as strings excluding the spaces

You might also like