Monday, July 21, 2014

printf format string in Python

The format operator, % allows us to construct strings, replacing parts of the
strings with the data stored in variables.  But when the first operand is a string, % is the format operator.
The first operand is the format string, which contains one or more format sequences that specify how the second operand is formatted. The result is a string.
For example, the format sequence '%d' means that the second operand should be
formatted as an integer (d stands for “decimal”):
>>> camels = 42
>>> '%d' % camels
'42'
The difference in python and c for print function is that python uses % operator again before variable names

e.g.

IN C language>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int num= 3;
float rate = 3.2;
char letter = 'A';

printf("%d, %f, %c" num, rate, letter);

output:--

3,3.2,A


IN Python >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

 num= 3
 rate = 3.2
letter = 'A'

print "%d %f %c" %(num, rate, letter)

output:--

3,3.2,A

for more about formated string refer this 

Saturday, July 5, 2014

Error while using input() function

 Error while using input() function :---

#!/usr/bin/python
print ('Hello! What is your name?')
myName = input()


 Output:-
 Hello world!
What is your name?
Aman
Traceback (most recent call last):
File "C:/Python24/game.py", line 3, in <module>
myName = input()
File "<string>", line 1, in <module>
NameError: name 'Aman' is not defined



...then this means you are running the program with Python 2, instead of Python 3.

The input() and raw_input() Functions
In Python 2, the function to get input from the keyboard is raw_input(). In Python 3, the input() function does this. You can simply rename the function wherever it appears in your code.
>>> # Python 2
>>> name = raw_input()
>>> # Python 3
>>> name = input()

#!/usr/bin/python
print ('Hello! What is your name?')
myName = raw_input()

Sockets and Ports

A port can be viewed as a rendezvous point between TCP and the application. However, the port is a part of the operating system and the application program can not directly access the port.

  • TCP puts the data in the right port (mail box).
  • The socket transports the data between the port (mail box) and the application.