Skip to content

Instantly share code, notes, and snippets.

@Nahiduzzaman
Last active June 27, 2017 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nahiduzzaman/6bd66e2e38e276567ab530650e32d1fd to your computer and use it in GitHub Desktop.
Save Nahiduzzaman/6bd66e2e38e276567ab530650e32d1fd to your computer and use it in GitHub Desktop.

#1. How to take user input in python?

Ans:

If you want to take simple input not worring about data type! use raw_input

number_of_books = raw_input(); #user press number 4 on keyboard
print number_of_books #'4' a string

raw_input takes everything as string, so after getting the string you have to typecast to his desire format.

number_of_books = int(raw_input()); #user press number 4 on keyboard
print number_of_books # 4 an integer

#2. How to take user input (as many as you can) in python separated by space?

# this will take user input separted by space and returns an array of inputs
number_of_books = raw_input().split(); # user types: 12 13 23
print number_of_books #['12','13','23']

raw_input().split() returns array of string, so you have typecast every input like following:

number_of_books = map(int,raw_input().split()); # user types: 12 13 23
print number_of_books #[12,13,23] array of integers
x = map(int,raw_input().split()) # this will take unlimited user input and returns the array of inputs
x,y,z = map(int,raw_input().split()) # this will take 3 user input and returns the array of 3 inputs. <3 or >3 input will through error

raw_input().split() method is useful when your program has multiple user inputs and you want to store them in an array and use them later.

suppose you want to take first input as string but other as integer, do following.

s = raw_input().split() # user input : insert 0 6
for i in range(1,len(s)):
    s[i] = int(s[i])
print s # output: ['insert', 0, 6]

#3. for loop

Traditional for-loop in JS or C++ is pretty similar

for (var i = 0 ; i < limit ; i++){
}

in python: for - loop looks like following,

Example 1:

limit = 5
for i in range(limit):
    print i # 0 1 2 3 4  (all in new line)

Example 2:

s = [1,4,9,16,25]
for item in s:
    print item # 1,4,9,16,25 [like ng-repeat]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment