As usual we have integers, floats and strings. Here, in Python you really don't need to worry about defining the data types explicitly. You can just keep using any particular variable with any data types at different instances of the program. Python interpreter will figure it out for out (lazyness is awesome! xD).
You can perform comparison operations with different data types (exception: strings). Example:
print(42==42.00)
print(42.00==00042.00)
print(42=='42') # '42' is a string and 42 is an integer. cool?
True True False
type(variable)
or type(data)
¶var = 42
print(type(var))
print(type(42))
print(type(42.00))
print(type('42'))
<class 'int'> <class 'int'> <class 'float'> <class 'str'>
#examples,,,oho by the way a line starts with hash sign,
#it means it's a comment line
#python interpreter will skip those lines
a = 5
b = 6
print("we have number", a, 'and', b)
#one more thing single or double inverted comma will do the same job unless
#you're using inverted comma with in the statements.
#In that case you have to use thise comma alternatively.
we have number 5 and 6
a
and b
, and we want to perform comparisions between them.¶For taking input for a and b from the user, The
input()
function can be used. You can also add a prompt to it (although it's not mandatory), by input("statements")
** Remember, whenever you try store an user-input it gets stored as a string. Therefore, you must convert those inputs into number(or any other specific type). In the next example we have converted an input string to float. You can verify the input data type by using the type(variable)
command, as we stated earlier, in line In[2]
a = float(input("enter a number: "))
b = float(input("enter another number: "))
if(a>b):
print("a is grater than b")
elif(a<b): # it means else if, in some places it is not required,
#and in some places it becomes convenient to have
print("a is less than b")
else:
print("a is equal to b")
enter a number: 10 enter another number: 15 a is less than b
a = float(input("enter a number: "))
b = float(input("enter another number: "))
if(a>b):
print(a, "is grater than", b)
elif(a<b):
print(a, "is less than", b)
else:
print(a, "is equal to", b)
enter a number: 15 enter another number: 15 15.0 is equal to 15.0
if(logical expressions):
instructions
...
...
elif(logical expressions): #elif and else blocks are optional
instructions
...
...
else:
instructions
...
...
In other languages like C or C++ or Java, indentation is an optional thing, i.e. even without indentations, the codes work properly. Do you know the reason? Well, we can use braces there to segmentify/group different regions of the script.
True
and False
. Python is a case sensitive language. So you have to be careful about it. The first letter is capitalized here 'T' and 'F'¶We can have local operators too. like and
, or
and not
just as you do in other languages. For example in C or C++ the equivalent operators are &&, ||
for example we will print 1 to 10 using an infinite loop. Whenever the varibale reach the value 10 the loop will break
Let's try!
num = 0
while True:
num += 1 # shorthand for n=n+1
print(num)
if(num == 10) : break
# you can put the break statement in the next indented line.
1 2 3 4 5 6 7 8 9 10
general syntax:
while(logical expression):
statements
...
...
for
loop¶Syntax:
for var in range(start, end, step):
statements
...
...
start
and step
arguments in the range
are optional. By default those are set to be 0 and 1 respectively.
for i in range(2,17,3):
print(i)
# Notice the output! It doesn't print 17.
# It's because the range function is evaluating "upto" the number 17
2 5 8 11 14
Syntax:
def name(arguments):
statements
...
...
retuen the_resut
let's have a simple addition function.
def addition(a,b):
c = a+b
return c
sum = addition(6,7)
print(sum)
# or we can do
print("Let's try with ccompoisition of print and add function", addition(10,11))
13 Let's try with ccompoisition of print and add function 21
The idea is; take any arbitrary integer. If it is even, divide it by 2 otherwise multiply the number by 3 and then add 1 to it. Repeat this process. It'll get terminated at n=1. But nobody knows why!
# if n is odd then n*3+1
# if n is even then n/2
def collatz(n):
while (n!=1):
if(n%2==0):
n = n//2 # // means integer division
print(n)
else:
n = 3*n+1
print(n)
user_input = int(input("Enter a number="))
collatz(user_input)
Enter a number=30 15 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
........................... And you're done!
These are mutable, that is we can edit the elements of the list. Lists can contain heterogeneous data unlike C/C++/Fortran array. We denote list by a pair of brackets. Example;
a = [2,3,4,5]
b= ['a',2,3.45,['g','e']]
print(a)
print(b)
print(a[1])
print(b[2])
[2, 3, 4, 5] ['a', 2, 3.45, ['g', 'e']] 3 3.45
i. By index
ii. By the elements of the list itself
** NOTE: List index starts from 0
array = [2,['a','b'],'efg', 2.6]
print("Itterating over index")
#len(list_name ) return the length of the array
for i in range(len(array)):
print(array[i])
print("------------")
print("Itterating over elements")
for elements in array:
print(elements)
Itterating over index 2 ['a', 'b'] efg 2.6 ------------ Itterating over elements 2 ['a', 'b'] efg 2.6
matrix = [[1,0,0],[0,1,0],[0,0,1]]
# Print the matrix
for element1 in matrix:
print(element1)
print("----*****-----")
#access the each element and print them
for element1 in matrix:
for element2 in element1:
print(element2)
[1, 0, 0] [0, 1, 0] [0, 0, 1] ----*****----- 1 0 0 0 1 0 0 0 1
Also note that string and tuple are immutable.
You can convert one data type to another with smple built-in functions. like: tuple(var)
, list(var)
, string(var)
# We defined 'a' earlier, so we do not need to do it again,
# if you're doing this
# in ascript, you should be defining `a` otherwise you'll have an error
print(a)
a[2] = 'new'
print("edited a: ", a)
#convert 'a' in to tuple and assign it to a new variable, say b
b = tuple(a)
print('type of a:',type(a),'\n type of b: ', type(b))
# \n means it'll print it in a new line
[2, 3, 4, 5] edited a: [2, 3, 'new', 5] type of a: <class 'list'> type of b: <class 'tuple'>
#Let's try to change the element of the tuple
b[1] = 'x'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-14-1a5b0875d144> in <module> 1 #Let's try to change the element of the tuple ----> 2 b[1] = 'x' TypeError: 'tuple' object does not support item assignment
Say if you have a string variable, name='python'
then name[2] will return 'y'0. Try yourself!
Unlike string, tuple and list, dictionary are consists of key-value pairs. keys are string type data where as values could be anything - lists, string, tuples and even can be another dictionary. We will go easy. Let's say, you want to design a game and you want to keep track of gems, lifes and the user name of the player. btw, dictionaries are mutable objects!
#let us create a dictionary, `game`
game = {'gems':20,'life':3, 'user_name':'abc123'}
print(game)
print("data type of the game: ",type(game))
{'gems': 20, 'life': 3, 'user_name': 'abc123'} data type of the game: <class 'dict'>
# you can access the elements of the game in the following manner
print(game['user_name'])
# as dictionary is mutable you can change the value corresponding to a key
game['life'] -= 1 #equivalent to game['life'] = game['life'] - 1
print('life updated:',game['life'])
abc123 life updated: 1
#you can check a if a particular key exist in a dictionary or not
'token' in game
False
'gems' in game
True
issmall
thins with strings. Actual command isislower()
and isupper()
! My bad, sorry! :")¶string = 'python'
if string.islower():
string = string.upper()
print(string)
PYTHON
let's look into some other methods
isalpha
- is the string is consists of anly alphabets
isalnum
- is the string consists of alphanumeric type data
isdecimal
- is the string consists only of decimals
a = '4Abc4543'
print(a.isdecimal())
print(a.isalnum())
print(a.isalpha())
False True False
What it does? It is helpful to access your clip board
Before running the block below, copy some text from anywhere you like
import pyperclip
test = pyperclip.paste()
print(test)
I copied this text earlier.
That's it for today!!
Practise this elementary stuffs. We will upload the problem set soon, where you need to show some of your creativity to solve those problems. Remember, writing a code is just the 5%; the rest is bug fixing where the learning starts. Before start writing a code, try to write down the idea on paper, how you'll solve the problem. If you do that, you've already done with the 50% of your task. Also, we will introduce you to the random
library in the problem set. Don't worry; we will always be there to solve your confusion and to make you comfortable. You're just an email away!
P.S. We'll try to make the next session less messy. ROFL!