Input, Output and data manipulation (Python series)

Input, Output and data manipulation (Python series)

July 12th, 2013 // 7:30 pm @

Welcome back. In this tutorial I am going to go over few basic input and output methods. Like any other programs, Python has its ways to receive data from user and store them into a variable. You can receive data in many different ways but the most common ways are “input” and “raw_input” commands.

Like any other langiage, you have to assciate your input with a variable so Python can store that into the memory. That can be done by simply using the VariableName = DATATYPE(“MESSAGE”)

ex.

Age = input ("Please enter your age: ")
Name = raw_input("Please Enter your name: ") 

As you noticed, I’ve used the same data type for both inputs. That’s because they are all the same. So what Python does, is it’ll show the message to user, and as soon as user enters the data requested by program, python stores that into a variable

same as this command in C

int age = 20;

or for PHP

$Age="20";

now that you have the data stored in the variable you can use the print command to show the message back to user or use other directives to manipulate data and do other things.

here is a simple code that takes some info from user, does some calculations and shows a message

#!usr/bin/python

name = raw_input("Please Enter Your Name : ")
age = input("What's your age? ")
InMonths=int(age)*12
print name+", You are "+InMonths+" months old"

So as you may have already guessed, the program prompts users to enter their name, it adds the name to var ‘name’, then asks for their age, and adds that to var ‘age’.
Then it take age, multiplies that by 12 and prints the user’s name, and their age in months in a constructed message

arad@Ubuntu_t94_srvr:~/Desktop/Pythons$ ./prog.py
 Please Enter Your Name : Arad
 What's your age? 10
 Arad, You are 120 months old
arad@Ubuntu_t94_srvr:~/Desktop/Pythons$

That’s it, it was pretty easy wasn’t it. In the next article I am going to talk about IF statements and how to add some of that into our program.

Cheers,


Category : Linux &Python

2 Comments → “Input, Output and data manipulation (Python series)”


  1. Goerge

    5 years ago

    So can we say {name = raw_input(“Please Enter Your Name : “) } is same as scanf in C?


    • Arad Gharagozli

      5 years ago

      Yes, exactly however, it’s a different stage. SCANF is a seprate operative than “puts” or “printf” but with Python you hit two birds with one stone 😉


On LinkedIn

LinkedIn

.

"I have no special talent.
I am only passionately
curious.
"
Albert Einstein

Subscribe Now