Python Syntax
Python Syntax
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()
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.
# input
num1 = int(input())
num2 = int(input())
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)
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
print()
print()
print()
Python print()
The print() function prints the given object to the standard output device (screen) or to the
text stream file.
print() Parameters
objects - object to the printed. * indicates that there may be more than one object
file - must be an object with write(string) method. If omitted it, sys.stdout will be used which
prints objects on the screen.
Note: sep, end, file and flush are keyword arguments. If you want to use sep argument, you
have to use:
not
print(*objects, 'separator')
a=5
print("a =", a)
b=a
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.
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.
Output :
Welcome to GeeksforGeeks
print("GeeksforGeeks")
Output :
Python@GeeksforGeeks
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.
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.
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.
filter_none
edit
play_arrow
brightness_4
# fancier output
Output :
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
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”.
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
Output :
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:
format(12, 00.546))
format(47.42, 11))
Output:
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}
Output:
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
# string() method
Output:
I love geeksforgeeks--------------------
print()
print()
print()
STRING
String Literals
String literals in python are surrounded by either single quotation marks, or double quotation marks.
Example
print("Hello")
print('Hello')
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
Example
You can use three double quotes:
print(a)
Example
print(a)
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:
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:
Syntax
The syntax of a while loop in Python programming language is −
while expression:
statement(s)
Example
count = 0
count = count + 1
It has the ability to iterate over the items of any sequence, such as a list or a string.
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
Example
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 split() method returns a list of numbers as strings excluding the spaces