19
loading...
This website collects cookies to deliver better user experience
# Basic If syntax
x = 2
if x == 2:
print('x is:', x)
if <condition>:
<statement>
# if...else
if <condition>:
<statement>
else:
<statement>
name = 'Kumar'
if name == 'Kumar':
print(f'Hello {name}')
else:
print("You are not 'Kumar'")
# Output: Hello Kumar
'''
In the above code snippet, first <if> evaluates the condition name == 'Kumar', which is true, so the <statement> inside the body of <if> got executed. If the condition would have been false then the interpreter would come to <else> statement.
'''
# if...elif...else
if <condition>:
<statement>
elif <condition>:
<statement>
else:
<statement>
x = 5
if x == 2:
print('Inside the body of if')
elif x == 5:
print('Inside the body of elif')
else:
print('Inside the body of else')
# Output
# Inside the body of elif
'''
Because only <elif> condition is true
'''
s = [1, 2, 3, 4, 5, 6]
print(s[0])
print(s[1])
print(s[2])
print(s[3])
print(s[4])
print(s[5])
# Output
# 1
# 2
# 3
# 4
# 5
# 6
# String
s = "Python is awesome"
for char in s:
print(char)
# Output
# P
# y
# t
# h
# o
# n
#
# i
# s
#
# a
# w
# e
# s
# o
# m
# e
# List
lst = [1, 2, True, 4.234, False, 'List']
for elm in lst:
print(elm)
'''
Output:
1
2
True
4.234
False
List
'''
# Tuple
tup = (1, 2, True, 4.234, False, 'List')
for elm in lst:
print(elm)
'''
Output:
1
2
True
4.234
False
List
'''
person = {'name':'Kumar', 'age':23, 'email': 'kumar.com'}
for key in person:
Person[key]
'''
# Output:
'Kumar'
23
'Kumar.com'
'''
person = {'name':'Kumar', 'age':23, 'email': 'kumar.com'}
for value in person.values():
print(value)
'''
# Output:
Kumar
23
Kumar.com
'''
person = {'name':'Kumar', 'age':23, 'email': 'kumar.com'}
for key, value in person.items():
print(f'{key}:{value}')
'''
# Output:
name:Kumar
age:23
email:kumar.com
'''
s = {1, 2, 4, "hello", False}
for elm in s:
print(elm)
'''
# Output
False
1
2
4
hello
'''