Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
31 views

Python Practice

Uploaded by

anishpujari25
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Python Practice

Uploaded by

anishpujari25
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

python-practice

August 18, 2023

[24]: print('*' * 60)

************************************************************

[25]: print(" O____~")


print(" ||||")

O____~
||||

[26]: print("My name is %s and weight is %d kg!" % ('Zara', 21))

My name is Zara and weight is 21 kg!

[27]: name = input("what is your name? ")


print('Hi ' + name)

what is your name? sarit


Hi sarit

[28]: name = input("what is your name? ")


favourite_colour = input('what is your favourite colour? ')
print(name + ' likes ' + favourite_colour)

what is your name? james


what is your favourite colour? blue
james likes blue

[29]: from datetime import date

today = date.today()
print("Today's date:", today)

Today's date: 2022-05-10

[30]: from datetime import datetime

now = datetime.now()

1
current_time = now.strftime("%H:%M:%S") # format the value using the strftime()␣
↪method to fetch only the time information

print("Current Time is :", current_time)

Current Time is : 16:24:18

[31]: time = now.strftime("%H:%M %p")

print("Current Time is :", time)

Current Time is : 16:24 PM

[32]: # importing date class from datetime module


from datetime import date

# creating the date object of today's date


todays_date = date.today()

# printing todays date


print("Current date: ", todays_date)

# fetching the current year, month and day of today


print("Current year:", todays_date.year)
print("Current month:", todays_date.month)
print("Current day:", todays_date.day)

Current date: 2022-05-10


Current year: 2022
Current month: 5
Current day: 10

[33]: birth_year = int(input('Birth year: '))


print(type(birth_year))
age = todays_date.year - birth_year
print(age)
print(type(age))

Birth year: 1970


<class 'int'>
52
<class 'int'>

[34]: # 1 Pound = 0.453592 Kilograms


# or 1 lb = 0.453592 Kg

pounds = float(input("Enter weight in Pounds to comvert to kilograms: "))

2
kgs = pounds * 0.453592

print("The weight in kgs is", round(kgs,3))

Enter weight in Pounds to comvert to kilograms: 75


The weight in kgs is 34.019

[35]: # signle quote & double quote


name = 'my name is sarit' # signle quote
print(name)
print(name[0]) # index
print(name[-1])# negative index
print(name[0:4])
print(name[0:])
uni = "Alliance university" # double quote
print(uni)

my name is sarit
m
t
my n
my name is sarit
Alliance university

[36]: variable = "Bidisha's favourite colour is pink"


print(variable)

Bidisha's favourite colour is pink

[37]: variable = 'Bidisha loves "Ice-cream"'


print(variable)

Bidisha loves "Ice-cream"

[38]: quote = '''I need to create a python function named poundsToMetric which␣
↪converts weights given

in pounds to kilograms and grams.


for example rather than print out 2.2 kilograms the correct answer would be 2␣
↪kilograms and 200 grams'''

print(quote)

I need to create a python function named poundsToMetric which converts weights


given
in pounds to kilograms and grams.
for example rather than print out 2.2 kilograms the correct answer would be 2
kilograms and 200 grams

3
[39]: # formatted string
first_name = "Rahul"
last_name = "Singh"

# our target is to write a code to print "Rahul [Singh] is my friend"

message = first_name + ' [' + last_name + '] is my friend'


print(message)

msg = f'{first_name} [{last_name}] is my friend'


print(msg)

Rahul [Singh] is my friend


Rahul [Singh] is my friend

[40]: section = "fundamentals of python program"


print(len(section))

30

[41]: print(section.upper()) # upper case method


print(section.lower())

FUNDAMENTALS OF PYTHON PROGRAM


fundamentals of python program

[42]: print(section.find('u'))

[43]: print(section.replace('program', 'programming'))

fundamentals of python programming

[44]: 'python' in section

[44]: True

[45]: # round function


x = 3.8
print(round(x))

[46]: # abs function returns always a positive value


print(abs(-3.9))

3.9

4
Below code accepts a sequence of words as input and prints the words in a sequence
after sorting them alphabetically.
[47]: print ("Enter your full name:")
name = input()

ord_name = name.split()
ord_name.sort()

print("Your name arranged in alphabetical order is:", ord_name)

Enter your full name:


James bond
Your name arranged in alphabetical order is: ['James', 'bond']

Below program accepts a sentence and calculate the number of letters and digits. If
the entered string is: Bond007 Then the output will be: LETTERS: 4 DIGITS:3
[48]: print("Enter a word with letters and numbers:")
word = input()

num = 0
char = 0

print("\nThe numbers in the sentence are:")


numbers = [int(i) for i in str(word) if i.isdigit()]
print(numbers)
for i in word:
if i.isdigit():
num += 1
print("\nDIGITS:", num)

print("\nThe letters in the sentence are:")


letters = [str(i) for i in str(word) if i.isalpha()]
print(str(letters))
for i in word:
if i.isalpha():
char += 1
print("\nLETTERS:", char)

Enter a word with letters and numbers:


james007

The numbers in the sentence are:


[0, 0, 7]

DIGITS: 3

5
The letters in the sentence are:
['j', 'a', 'm', 'e', 's']

LETTERS: 5

[49]: # Program to sort alphabetically the words form a string provided by the user

string = "Hello, I love to drive Ferrari"

# To take input from the user


# string = input("Enter a string: ")

# breakdown the string into a list of words


words = [word.lower() for word in string.split()]

# sort the list


words.sort()

# display the sorted words


print("The sorted words are:")
for word in words:
print(word)

The sorted words are:


drive
ferrari
hello,
i
love
to

[50]: # pipe-separated sequence of words as input and prints the sorted words

items = [n for n in input().split('|')]


items.sort()
print('|'.join(items))

red|white|blue|green
blue|green|red|white

[51]: # comma-separated sequence of words as input and print the sorted words
items = [n for n in input().split(',')]
items.sort()
words = ','.join(items)
print(words)

red, white, green, black


black, green, white,red

6
[52]: # sort() method with the reverse = True argument to sort the elements in the␣
↪words list in the reverse alphabetical order

words = ['red', 'white', 'black', 'violet']


words.sort(reverse = True)
print(words)

['white', 'violet', 'red', 'black']

Function & Returns


1. abs(x)
• The absolute value of x: the (positive) distance between x and zero.
2. ceil(x)
• The ceiling of x: the smallest integer not less than x
3. cmp(x, y)
• -1 if x < y, 0 if x == y, or 1 if x > y
4. exp(x)
• The exponential of x: ex
5. fabs(x)
• The absolute value of x.
6. floor(x)
• The floor of x: the largest integer not greater than x
7. log(x)
• The natural logarithm of x, for x> 0
8. log10(x)
• The base-10 logarithm of x for x> 0.
9. max(x1, x2,...)
• The largest of its arguments: the value closest to positive infinity
10. min(x1, x2,...)
• The smallest of its arguments: the value closest to negative infinity
11. modf(x)
• The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as
x. The integer part is returned as a float.
12. pow(x, y)
• The value of x**y.
13. round(x [,n])

7
• x rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker:
round(0.5) is 1.0 and round(-0.5) is -1.0.
14. sqrt(x)
• The square root of x for x > 0
[53]: import math # import math module
print(math.ceil(4.7))

[54]: print(math.floor(4.6))

4
https://docs.python.org/3/library/math.html
Python programming language provides following types of decision making statements. #####
if statements - An if statement consists of a boolean expression followed by one or more statements.

if…else statements
• An if statement can be followed by an optional else statement, which executes when the
boolean expression is FALSE.

nested if statements
• We can use one if or else if statement inside another if or else if statement(s).

0.1 Check all individual digits are even in a range


[1]: # Check all individual digits are even in a range
even_digits= []
for x in range(1000,9000):
if int(x) % 2 == 0 and int(x) % 20 < 10 and int (x) % 200 < 100 and int␣
↪(x) % 2000 < 1000:

even_digits.append(str(x))
print (','.join(even_digits))

2000,2002,2004,2006,2008,2020,2022,2024,2026,2028,2040,2042,2044,2046,2048,2060,
2062,2064,2066,2068,2080,2082,2084,2086,2088,2200,2202,2204,2206,2208,2220,2222,
2224,2226,2228,2240,2242,2244,2246,2248,2260,2262,2264,2266,2268,2280,2282,2284,
2286,2288,2400,2402,2404,2406,2408,2420,2422,2424,2426,2428,2440,2442,2444,2446,
2448,2460,2462,2464,2466,2468,2480,2482,2484,2486,2488,2600,2602,2604,2606,2608,
2620,2622,2624,2626,2628,2640,2642,2644,2646,2648,2660,2662,2664,2666,2668,2680,
2682,2684,2686,2688,2800,2802,2804,2806,2808,2820,2822,2824,2826,2828,2840,2842,
2844,2846,2848,2860,2862,2864,2866,2868,2880,2882,2884,2886,2888,4000,4002,4004,
4006,4008,4020,4022,4024,4026,4028,4040,4042,4044,4046,4048,4060,4062,4064,4066,
4068,4080,4082,4084,4086,4088,4200,4202,4204,4206,4208,4220,4222,4224,4226,4228,
4240,4242,4244,4246,4248,4260,4262,4264,4266,4268,4280,4282,4284,4286,4288,4400,

8
4402,4404,4406,4408,4420,4422,4424,4426,4428,4440,4442,4444,4446,4448,4460,4462,
4464,4466,4468,4480,4482,4484,4486,4488,4600,4602,4604,4606,4608,4620,4622,4624,
4626,4628,4640,4642,4644,4646,4648,4660,4662,4664,4666,4668,4680,4682,4684,4686,
4688,4800,4802,4804,4806,4808,4820,4822,4824,4826,4828,4840,4842,4844,4846,4848,
4860,4862,4864,4866,4868,4880,4882,4884,4886,4888,6000,6002,6004,6006,6008,6020,
6022,6024,6026,6028,6040,6042,6044,6046,6048,6060,6062,6064,6066,6068,6080,6082,
6084,6086,6088,6200,6202,6204,6206,6208,6220,6222,6224,6226,6228,6240,6242,6244,
6246,6248,6260,6262,6264,6266,6268,6280,6282,6284,6286,6288,6400,6402,6404,6406,
6408,6420,6422,6424,6426,6428,6440,6442,6444,6446,6448,6460,6462,6464,6466,6468,
6480,6482,6484,6486,6488,6600,6602,6604,6606,6608,6620,6622,6624,6626,6628,6640,
6642,6644,6646,6648,6660,6662,6664,6666,6668,6680,6682,6684,6686,6688,6800,6802,
6804,6806,6808,6820,6822,6824,6826,6828,6840,6842,6844,6846,6848,6860,6862,6864,
6866,6868,6880,6882,6884,6886,6888,8000,8002,8004,8006,8008,8020,8022,8024,8026,
8028,8040,8042,8044,8046,8048,8060,8062,8064,8066,8068,8080,8082,8084,8086,8088,
8200,8202,8204,8206,8208,8220,8222,8224,8226,8228,8240,8242,8244,8246,8248,8260,
8262,8264,8266,8268,8280,8282,8284,8286,8288,8400,8402,8404,8406,8408,8420,8422,
8424,8426,8428,8440,8442,8444,8446,8448,8460,8462,8464,8466,8468,8480,8482,8484,
8486,8488,8600,8602,8604,8606,8608,8620,8622,8624,8626,8628,8640,8642,8644,8646,
8648,8660,8662,8664,8666,8668,8680,8682,8684,8686,8688,8800,8802,8804,8806,8808,
8820,8822,8824,8826,8828,8840,8842,8844,8846,8848,8860,8862,8864,8866,8868,8880,
8882,8884,8886,8888

[2]: # printing only the even numbers (both number included)

start = int(100)
end = int(500)

# iterating each number in list


for num in range(start, end + 1):

# checking condition
if num % 2 == 0:
print(num, end = " ")

100 102 104 106 108 110 112 114 116 118 120 122 124 126 128 130 132 134 136 138
140 142 144 146 148 150 152 154 156 158 160 162 164 166 168 170 172 174 176 178
180 182 184 186 188 190 192 194 196 198 200 202 204 206 208 210 212 214 216 218
220 222 224 226 228 230 232 234 236 238 240 242 244 246 248 250 252 254 256 258
260 262 264 266 268 270 272 274 276 278 280 282 284 286 288 290 292 294 296 298
300 302 304 306 308 310 312 314 316 318 320 322 324 326 328 330 332 334 336 338
340 342 344 346 348 350 352 354 356 358 360 362 364 366 368 370 372 374 376 378
380 382 384 386 388 390 392 394 396 398 400 402 404 406 408 410 412 414 416 418
420 422 424 426 428 430 432 434 436 438 440 442 444 446 448 450 452 454 456 458
460 462 464 466 468 470 472 474 476 478 480 482 484 486 488 490 492 494 496 498
500

9
[6]: # printing only the odd numbers (both number included)

start = int(101)
end = int(501)

# iterating each number in list


for num in range(start, end+1):

# checking condition
if num % 2 != 0:
print(num, end = " ")

101 103 105 107 109 111 113 115 117 119 121 123 125 127 129 131 133 135 137 139
141 143 145 147 149 151 153 155 157 159 161 163 165 167 169 171 173 175 177 179
181 183 185 187 189 191 193 195 197 199 201 203 205 207 209 211 213 215 217 219
221 223 225 227 229 231 233 235 237 239 241 243 245 247 249 251 253 255 257 259
261 263 265 267 269 271 273 275 277 279 281 283 285 287 289 291 293 295 297 299
301 303 305 307 309 311 313 315 317 319 321 323 325 327 329 331 333 335 337 339
341 343 345 347 349 351 353 355 357 359 361 363 365 367 369 371 373 375 377 379
381 383 385 387 389 391 393 395 397 399 401 403 405 407 409 411 413 415 417 419
421 423 425 427 429 431 433 435 437 439 441 443 445 447 449 451 453 455 457 459
461 463 465 467 469 471 473 475 477 479 481 483 485 487 489 491 493 495 497 499
501

[29]: start, end = int(1), int(50)


print('Range 1 to 50:')

for i in range(start, end + 1):


remainder = end % i

if(remainder == 0):
if (i % 2 == 0):
print('Factor is even:', i)
else:
print('Factor is odd:', i)
else:
pass

Range 1 to 50:
Factor is odd: 1
Factor is even: 2
Factor is odd: 5
Factor is even: 10
Factor is odd: 25
Factor is even: 50

10
[32]: # Numbers between two numbers where each digit of a number is an even number␣
↪and printed with comma separated

items = []
for i in range(100, 400):
s = str(i)
if (int(s[0]) % 2 != 0) and (int(s[1]) % 2 == 0) and (int(s[2]) % 2 == 0):
items.append(s)
print( ",".join(items))

100,102,104,106,108,120,122,124,126,128,140,142,144,146,148,160,162,164,166,168,
180,182,184,186,188,300,302,304,306,308,320,322,324,326,328,340,342,344,346,348,
360,362,364,366,368,380,382,384,386,388

[15]: # Numbers between two numbers where each digit of a number is an even number␣
↪and printed with | separated

for num in range(20, 40):


if all (int(n) % 2 == 0 for n in str(num)):
print((num), "|", end=" ")
else:
continue

20 | 22 | 24 | 26 | 28 |

0.1.1 all() function returns true if all the elements of a given iterable (List, Dictionary,
Tuple, set, etc) are True else it returns False. It also returns True if the iterable
object is empty.

[26]: # numbers between 1000 and 3000 (both included) such that each digit of the␣
↪number is an even number

numbers = []
for x in range (1000, 3001):
numSplit = [int(d) for d in str(x)]
odd = False
for y in range (0, len(numSplit)):
if numSplit[y] % 2 != 0:
odd = True
if (odd == False):
numbers.append(x)
print (numbers)

[2000, 2002, 2004, 2006, 2008, 2020, 2022, 2024, 2026, 2028, 2040, 2042, 2044,
2046, 2048, 2060, 2062, 2064, 2066, 2068, 2080, 2082, 2084, 2086, 2088, 2200,
2202, 2204, 2206, 2208, 2220, 2222, 2224, 2226, 2228, 2240, 2242, 2244, 2246,
2248, 2260, 2262, 2264, 2266, 2268, 2280, 2282, 2284, 2286, 2288, 2400, 2402,
2404, 2406, 2408, 2420, 2422, 2424, 2426, 2428, 2440, 2442, 2444, 2446, 2448,
2460, 2462, 2464, 2466, 2468, 2480, 2482, 2484, 2486, 2488, 2600, 2602, 2604,
2606, 2608, 2620, 2622, 2624, 2626, 2628, 2640, 2642, 2644, 2646, 2648, 2660,

11
2662, 2664, 2666, 2668, 2680, 2682, 2684, 2686, 2688, 2800, 2802, 2804, 2806,
2808, 2820, 2822, 2824, 2826, 2828, 2840, 2842, 2844, 2846, 2848, 2860, 2862,
2864, 2866, 2868, 2880, 2882, 2884, 2886, 2888]

[9]: # all values true


l = [1, 3, 4, 5]
print(all(l))

# all values false


l = [0, False]
print(all(l))

# one false value


l = [1, 3, 4, 0]
print(all(l))

# one true value


l = [0, False, 5]
print(all(l))

# empty iterable
l = []
print(all(l))

True
False
False
False
True

[6]: # All elements of tuple are true


tup = (2, 4, 6)
print(all(tup))

# All elements of tuple are false


tup = (0, False, False)
print(all(tup))

# Some elements of tuple


# are true while others are false
tup = (5, 0, 3, 1, False)
print(all(tup))

# Empty tuple
tup = ()
print(all(tup))

True

12
False
False
True

How all() works with Python dictionaries? In the case of dictionaries, if all keys (not values)
are true or the dictionary is empty, all() returns True, else, it returns fals

[11]: dictionary = {0: 'False', 1: 'False'}


print(all(dictionary ))

dictionary = {1: 'True', 2: 'True'}


print(all(dictionary ))

dictionary = {1: 'True', False: 0}


print(all(dictionary ))

dictionary = {}
print(all(s))

# 0 is False
# '0' is True
dictionary = {'0': 'True'}
print(all(dictionary ))

False
True
False
True
True

[55]: is_hot = True

if is_hot:
print("It's a hot humid day")
print('Drink lemonade')

else:
print("It's cold")
print("wear sweater & jackets")
print('Have a lovely day!')

It's a hot humid day


Drink lemonade
Have a lovely day!

[56]: is_hot = False


is_cold = True

13
if is_hot:
print("It's a hot humid day")
print('Drink lemonade')

elif is_cold:
print("It's cold winter")
print("wear warm clothes")
else:
print("It's a lovely day!")

print('Have a great day ahead!')

It's cold winter


wear warm clothes
Have a great day ahead!
• Price of an apartment is 1000000.00.
• If I have a good credit rating, I need to pay 10% downpayment, alternately 30% down
payment.
• we will write a program with this rule to display buyer with good credit.
[57]: apartment_price = 1000000
has_good_credit = True

if has_good_credit:
down_payment = apartment_price * 0.1

else:
down_payment = apartment_price * 0.3

print(f"Down Payment: Rs.{down_payment}")

Down Payment: Rs.100000.0

logical AND/OR/NOT operator


• If someone has high income AND good credit rating, he/she is eligible for loan
• If someone has high income OR good credit rating, he/she is eligible for loan
• If someone has high income AND NOT criminal record, he/she is eligible for loan

[58]: has_high_income = True


has_good_credit = True

if has_high_income and has_good_credit:


print('Eligible for loan')

Eligible for loan

14
[59]: has_high_income = True
has_good_credit = True

if has_high_income or has_good_credit:
print('Eligible for loan')

Eligible for loan

[60]: has_high_income = True


has_criminal_record = False

if has_high_income and not has_criminal_record:


print('Eligible for loan')

Eligible for loan


If day’s temperature greater than 30 deg cel, it’s a hot day, if less than 15 deg cel, it’s a cold day,
alternately it’s neither cold nor hot.
[61]: temp = 30

if temp > 30: # ==, !=,


print("It's a hot day")
else:
print("It's not a hot day")

It's not a hot day


If name is less than 3 charecters long - validation error (name must be at-least 3 characters)
otherwise if it’s more than 50 charecters long - validation error(name can be a maximum of 50
characters)
otherwsie - name looks good!
[62]: name = 'Vinay'

if len(name) < 3:
print('name must be at-least 3 characters')
elif len(name) > 50:
print('name must be a maximum of 50 characters')
else:
print('name looks good!')

name looks good!

[63]: weight = int(input("weight: "))


unit = input('(L)bs or (K)g: ')
if unit.upper() == "L":
converted_weight = weight * 0.45

15
print(f"you are {converted_weight} kilos")
else:
converted_weight = weight / 0.45
print(f"you are {converted_weight} pounds")

weight: 72
(L)bs or (K)g: lbs
you are 160.0 pounds

[64]: # celsius to farenhit conversion


# C/5 = (F-32)/9

temp = input("Input the temperature we like to convert? (e.g., 45F, 102C etc.)␣
↪: ")

degree = int(temp[:-1])
input_temp = temp[-1]

if input_temp.upper() == "C":
result = int(round((9 * degree) / 5 + 32))
output_temp = "Fahrenheit"
elif input_temp.upper() == "F":
result = int(round((degree - 32) * 5 / 9))
output_temp = "Celsius"
else:
print("Input proper convention.")
quit()
print("The temperature in", output_temp, "is", result, "degrees.")

Input the temperature we like to convert? (e.g., 45F, 102C etc.) : 45F
The temperature in Celsius is 7 degrees.

0.1.2 reverse word


[65]: word = input("Input a word to reverse: ")

for char in range(len(word) - 1, -1, -1):


print(word[char], end = "")

print("\n")

Input a word to reverse: jamesbond


dnobsemaj

Python program to find the numbers which are divisible by 7 and multiple of 5,
between 1500 and 2700 (both included).

16
[66]: num = []
for n in range(1500, 2701):
if (n % 7 == 0) and (n % 5 == 0):
num.append(str(n))
print (','.join(num))

1505,1540,1575,1610,1645,1680,1715,1750,1785,1820,1855,1890,1925,1960,1995,2030,
2065,2100,2135,2170,2205,2240,2275,2310,2345,2380,2415,2450,2485,2520,2555,2590,
2625,2660,2695
In general, statements are executed sequentially: - The first statement in a function is executed
first, - followed by the second, and so on. - There may be a situation when we need to execute a
block of code several number of times.
Programming languages provide various control structures that allow for more complicated execu-
tion paths.
A loop statement allows us to execute a statement or group of statements multiple times.

while loop
• Repeats a statement or group of statements while a given condition is TRUE.
• It tests the condition before executing the loop body.

for loop
• Executes a sequence of statements multiple times and abbreviates the code that manages the
loop variable.

nested loops
• We can use one or more loop inside any another while, for or do..while loop.
[67]: # while loop
index = 1
while index <= 5:
print(index)
index = index + 1
print("complete")

1
2
3
4
5
complete

[68]: # while loop


index = 1
while index <= 5:

17
print("*" * index)
index = index + 1
print("complete")

*
**
***
****
*****
complete

[69]: # Python program to print First 5 Natural numbers using while loop
num = 1
while(num <= 5):
print(num)
num = num + 1

1
2
3
4
5

[70]: # Python program to print First 10 Odd numbers using while loop
num = 1
while(num <= 20):
print(num)
num = num + 2

1
3
5
7
9
11
13
15
17
19

[71]: # Python program to print First 5 Whole numbers using while loop
num = 0
while(num < 5):
print(num)
num = num + 1

0
1

18
2
3
4

[72]: # Python program to print first 5 numbers and their cubes using while loop.
num = 1
print("Numbers\t Cube")
while(num <= 5):
print(num,"\t", num ** 3)
num = num + 1

Numbers Cube
1 1
2 8
3 27
4 64
5 125

[73]: # Python program to print sum of first 10 Natural numbers using while loop.
num = 10
sum = 0

while num >= 1:


sum = sum + num
num= num - 1

print(sum)

55

0.1.3 Guess game:

[74]: secret_number = 9
guess_count = 0
guess_limit = 3

while guess_count < guess_limit:


guess = int(input("Guess: "))
guess_count += 1
if guess == secret_number:
print("You win!")

Guess: 4
Guess: 4
Guess: 1

Loop Control Statements

19
• Loop control statements change execution from its normal sequence.
• When execution leaves a scope, all automatic objects that were created in that scope are
destroyed.
Python supports the following control statements.

break statement
• Terminates the loop statement and transfers execution to the statement immediately following
the loop.

continue statement
• Causes the loop to skip the remainder of its body and immediately retest its condition prior
to reiterating.

pass statement
• The pass statement in Python is used when a statement is required syntactically but we do
not want any command or code to execute.
[75]: secret_number = 9
guess_count = 0
guess_limit = 3

while guess_count < guess_limit:


guess = int(input("Guess: "))
guess_count += 1
if guess == secret_number:
print("You win!")
break

Guess: 2
Guess: 3
Guess: 4

[76]: secret_number = 9
guess_count = 0
guess_limit = 3

while guess_count < guess_limit:


guess = int(input("Guess: "))
guess_count += 1
if guess == secret_number:
print("Congratualtions, You won!")
break
else:
print("Sorry, you have exceeded your limit")

20
Guess: 1
Guess: 2
Guess: 3
Sorry, you have exceeded your limit

[77]: command = ""

while command.lower() != 'quit':


command = input("> ")
if command.lower() == 'start':
print('engine started...')
elif command.lower() == 'stop':
print('engine stopped....')
elif command.lower() == 'help':
print("""
start - start the engine
stop - stop the engine
quit - quit the game
""")
else:
print("sorry, we don't understand that")

> 4
sorry, we don't understand that
> 3
sorry, we don't understand that
> 9
sorry, we don't understand that
> 3
sorry, we don't understand that
> help

start - start the engine


stop - stop the engine
quit - quit the game

> quit
sorry, we don't understand that

[78]: command = ""

while command.lower() != 'quit':


command = input("> ")
if command.lower() == 'start':
print('engine started...')
elif command.lower() == 'stop':
print('engine stopped....')

21
elif command.lower() == 'help':
print("""
start - start the engine
stop - stop the engine
quit - quit the game
""")
elif command == 'quit':
break
else:
print("sorry, we don't understand that")

> quit

[79]: # simplified
command = ""

while True:
command = input("> ").lower()
if command == 'start':
print('engine started...')
elif command == 'stop':
print('engine stopped.')
elif command == 'help':
print("""
start - start the engine
stop - stop the engine
quit - quit the game
""")
elif command == 'quit':
break
else:
print("sorry, we don't understand that")

> 2
sorry, we don't understand that
> start
engine started…
> stop
engine stopped.
> quit

[80]: # simplified
command = ""
started = False

while True:
command = input("> ").lower()

22
if command == 'start':
if started:
print("Engine already started!")
else:
started= True
print('engine started...')
elif command == 'stop':
if not started:
print("engine already stopped")
else:
started = False
print('engine stopped.')
elif command == 'help':
print("""
start - start the engine
stop - stop the engine
quit - quit the game
""")
elif command == 'quit':
break
else:
print("sorry, we don't understand that")

> help

start - start the engine


stop - stop the engine
quit - quit the game

> quit

[81]: # function to return True if the first and last number of a given list is same.
# If numbers are different then return False

def first_last_same(numberList):
print("Given list:", numberList)

first_num = numberList[0]
last_num = numberList[-1]

if first_num == last_num:
return True
else:
return False

x = [10, 20, 30, 40, 10]


print("result is", first_last_same(x))

23
y = [75, 65, 35, 75, 30]
print("result is", first_last_same(y))

Given list: [10, 20, 30, 40, 10]


result is True
Given list: [75, 65, 35, 75, 30]
result is False

[82]: # for loop


for letter in "Python":
print(letter)

P
y
t
h
o
n

[83]: # for loop


for name in ['Vishal', 'Renuka', 'Mily']: # list
print(name)

Vishal
Renuka
Mily

[84]: for number in [1,2,3,4,5]: # list


print(number)

1
2
3
4
5

[85]: for number in range(10): # range function


print(number)

0
1
2
3
4
5
6
7

24
8
9

[86]: for number in range(5, 10): # range function


print(number)

5
6
7
8
9

[87]: for number in range(5, 10, 2): # range function with steps ( increment by 2␣
↪steps)

print(number)

5
7
9

[88]: prices = [15, 25, 35]


total = 0

for price in prices:


total += price # total = total + price

print(f"Total: {total}") # total cost of all items

Total: 75

[89]: # Print all the numbers from 0 to 6 except 3 and 6


for x in range(6):
if (x == 3 or x == 6):
continue
print(x, end = ' ')

print("\n")

0 1 2 4 5

[90]: numbers = (10, 11, 12, 13, 14, 15, 16, 17, 18, 19) # Declaring the tuple

count_odd = 0
count_even = 0

for x in numbers:
if not x % 2:

25
count_even += 1
else:
count_odd += 1

print("Number of even numbers :", count_even)


print("Number of odd numbers :", count_odd)

Number of even numbers : 5


Number of odd numbers : 5

[91]: # printing only the odd numbers

number = 33
for i in range(1, number + 1):
if number % i == 0:
if i % 2 == 0:
print(str(i), 'is an even number')
else:
print(str(i), 'is an odd number')
else:
continue

1 is an odd number
3 is an odd number
11 is an odd number
33 is an odd number

[92]: # printing only the odd numbers

start = int(1)
end = int(33)

# iterating each number in list


for num in range(start, end + 1):

# checking condition
if num % 2 != 0:
print(num, end = " ")

1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33

[93]: # printing only the even numbers

start = int(1)
end = int(33)

# iterating each number in list

26
for num in range(start, end + 1):

# checking condition
if num % 2 == 0:
print(num, end = " ")

2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32

[94]: print("Printing current and previous number and their sum in a range(10)")
previous_num = 0

# loop from 1 to 10
for i in range(1, 11):
x_sum = previous_num + i
print("Current Number", i, "Previous Number ", previous_num, " Sum: ",␣
↪previous_num + i)

# modify previous number


# set it to the current number
previous_num = i

Printing current and previous number and their sum in a range(10)


Current Number 1 Previous Number 0 Sum: 1
Current Number 2 Previous Number 1 Sum: 3
Current Number 3 Previous Number 2 Sum: 5
Current Number 4 Previous Number 3 Sum: 7
Current Number 5 Previous Number 4 Sum: 9
Current Number 6 Previous Number 5 Sum: 11
Current Number 7 Previous Number 6 Sum: 13
Current Number 8 Previous Number 7 Sum: 15
Current Number 9 Previous Number 8 Sum: 17
Current Number 10 Previous Number 9 Sum: 19

Nested loop
[95]: for x in range(4):
for y in range(3):
print(f'({x}, {y})') # coordinates

(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
(2, 0)
(2, 1)
(2, 2)
(3, 0)

27
(3, 1)
(3, 2)
numbers = [5, 2, 5, 2, 2]
XXXXX XX XXXXX XX XX
[96]: # generate an inner loop to contan all x's as shown above
numbers = [5, 2, 5, 2, 2]
# for x_count in numbers:
# print('x' * x_count)

for x_count in numbers:


output = ""
for count in range(x_count):
output += 'x'
print(output)

xxxxx
xx
xxxxx
xx
xx

Python program to construct the following pattern, using a nested for loop.
o
o o
o o o
o o o o
o o o o o
o o o o
o o o
o o
o
[97]: n = 5;
for i in range(n):
for j in range(i):
print ('o ', end = "")
print('')

for i in range(n, 0, -1):


for j in range(i):
print('o ', end = "")
print('')

o
o o

28
o o o
o o o o
o o o o o
o o o o
o o o
o o
o

[98]: # Calculate the sum of all numbers from 1 to a given number

# s: store sum of all numbers


store = 0
num = int(input("Enter number "))

# run loop n times


# stop: n+1 (because range never include stop number in result)

for i in range(1, num + 1, 1):

# add current number to sum variable


store += i

print("\n")
print("Sum is: ", store)

Enter number 1

Sum is: 1

[99]: num = int(input("Enter number "))


# pass range of numbers to sum() function
x = sum(range(1, num + 1))
print('Sum is:', x)

Enter number 2

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [99], in <cell line: 3>()
1 num = int(input("Enter number "))
2 # pass range of numbers to sum() function
----> 3 x = sum(range(1, num + 1))
4 print('Sum is:', x)

TypeError: 'int' object is not callable

29
Print the following pattern
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
[ ]: n = 5
k = 5
for i in range(0, n+1):
for j in range(k-i, 0, -1):
print(j, end = ' ')
print()

Use else block to display a message “Done” after successful execution of for loop
[ ]: for i in range(5):
print(i)
else:
print("Done!")

0.1.4 Calculate income tax for the given income by adhering to the below rules
Taxable Income Rate (in %)
- First $ 10,000 0
• Next $ 10,000 10 - The remaining 20
Expected Output:
For example, suppose the taxable income is 50000 the income tax payable is
10000 * 0% + 10000 * 10% + 30000 * 20% = $ 7000.
[ ]: income = 50000
tax_payable = 0
print("Total income", income)

if income <= 10000:


tax_payable = 0
elif income <= 20000:
# no tax on first 10,000
x = income - 10000
# 10% tax
tax_payable = x * 10 / 100
else:
# first 10,000
tax_payable = 0

# next 10,000 10% tax

30
tax_payable = 10000 * 10 / 100

# remaining 20%tax
tax_payable += (income - 20000) * 20 / 100

print("Total tax to pay is", tax_payable)

0.1.5 Numbers between two numbers where each digit of a number is an even number

[5]: items = []
for i in range(100, 401):
s = str(i)
if (int(s[0]) % 2 == 0) and (int(s[1]) % 2 == 0) and (int(s[2]) % 2 == 0):
items.append(s)
print( ",".join(items))

200,202,204,206,208,220,222,224,226,228,240,242,244,246,248,260,262,264,266,268,
280,282,284,286,288,400

Below program find factors of given number and find whether the factor is even or
odd
[ ]: number = 2352

for i in range(1, number):


if number % i == 0:
if i % 2 == 0:
print("The factor", str(i), "is even")
else:
print("The factor", str(i), "is odd")
else:
continue

Even Odd Program in Python


• use modulus operator (%) to find even or odd numbers.
• modulus operator returns the remainder obtained after a division is performed.
• If the value returned after the application of the modulus operator is zero, then the program
will print that the input number is even. Else, it will print the number is odd.
[53]: # a simple function
def check(num):
if num % 2 == 0:
print("even number")
else:
print("odd number")
check(12)

31
even number

[41]: # A number is even if division by 2 gives a remainder of 0.


# If the remainder is 1, it is an odd number.

num = int(input("Enter a number: "))


if (num % 2) == 0:
print("{0} is Even".format(num)) # {} is a replacement field for num
else:
print("{0} is Odd".format(num))

Enter a number: 5
5 is Odd

[42]: num = int(input("Enter a number: "))


modify = num % 2
if modify > 0:
print("This is an odd number.")
else:
print("This is an even number.")

Enter a number: 6
This is an even number.

below program will find all the numbers between 100 and 401 (both included) such
that each digit of a number is an even number. The numbers obtained will be printed
in a dash separated sequence on a single line. expected output: 200-202-204-206-208-220-
222-224-226-228-240-242-244-246-248-260-262-264-266-268-280-282-284-286-288-400
[54]: num1 = 100; num2 = 400
values = []
for digit in range(num1, num2 + 1):
s = str(i)
if all(int(digit) % 2 == 0 for digit in s): # either we can use this␣
↪using all() which is more generic or the below

# if (int(s[0]) % 2 == 0) and (int(s[1]) % 2 == 0) and (int(s[2]) % 2 == 0):


values.append(s)
print( "-".join(items))

200-202-204-206-208-220-222-224-226-228-240-242-244-246-248-260-262-264-266-268-
280-282-284-286-288-400

below program will find all the numbers between 500 and 2500 (both included) such
that each digit of a number is an even number. The numbers obtained will be printed
in a tab separated sequence on a single line.
[51]: for num in range(500, 2500):
if all(int(n) % 2 == 0 for n in str(num)):
print((num), "/", end = "")

32
600 /602 /604 /606 /608 /620 /622 /624 /626 /628 /640 /642 /644 /646 /648 /660
/662 /664 /666 /668 /680 /682 /684 /686 /688 /800 /802 /804 /806 /808 /820 /822
/824 /826 /828 /840 /842 /844 /846 /848 /860 /862 /864 /866 /868 /880 /882 /884
/886 /888 /2000 /2002 /2004 /2006 /2008 /2020 /2022 /2024 /2026 /2028 /2040
/2042 /2044 /2046 /2048 /2060 /2062 /2064 /2066 /2068 /2080 /2082 /2084 /2086
/2088 /2200 /2202 /2204 /2206 /2208 /2220 /2222 /2224 /2226 /2228 /2240 /2242
/2244 /2246 /2248 /2260 /2262 /2264 /2266 /2268 /2280 /2282 /2284 /2286 /2288
/2400 /2402 /2404 /2406 /2408 /2420 /2422 /2424 /2426 /2428 /2440 /2442 /2444
/2446 /2448 /2460 /2462 /2464 /2466 /2468 /2480 /2482 /2484 /2486 /2488 /

[ ]: # code to find the given number is Palindrome number or not


number = input("Enter a number:")

newList = list(number)
print("The original list is:", newList)
newList.reverse()
print("The reversed list is:", newList)

if list(number) == newList:
print("The number is a Palindrome.")
else:
print("The number is not a Palindrome.")

[1]: # Program to sort alphabetically the words form a string

string = "Hi, I am Oprah Winfrey"

# To take input from the user


# string = input("Enter a string: ")

# breakdown the string into a list of words


words = [word.lower() for word in string.split()]

# sort the list


words.sort()

# display the sorted words

print("The sorted words are:")


for word in words:
print(word)

The sorted words are:


am
hi,
i
oprah
winfrey

33
[2]: scores = [5, 7, 4, 6, 9, 8]
print('first number of the range: 5')
print('second number of the range: 7')
scores.sort()

print(scores)

first number of the range: 5


second number of the range: 7
[4, 5, 6, 7, 8, 9]

[4]: # Check even or odd number

number = int(input("Enter a number: "))


module = number % 2
if module > 0:
print("This is an odd number.")
else:
print("This is an even number.")

Enter a number: 5
This is an odd number.

[5]: # Numbers between two numbers where each digit of a number is an even number␣
↪and printed with | separated

for num in range(2000, 4000):


if all (int(n) % 2 == 0 for n in str(num)):
print((num), "|", end=" ")
else:
continue

2000 | 2002 | 2004 | 2006 | 2008 | 2020 | 2022 | 2024 | 2026 | 2028 | 2040 |
2042 | 2044 | 2046 | 2048 | 2060 | 2062 | 2064 | 2066 | 2068 | 2080 | 2082 |
2084 | 2086 | 2088 | 2200 | 2202 | 2204 | 2206 | 2208 | 2220 | 2222 | 2224 |
2226 | 2228 | 2240 | 2242 | 2244 | 2246 | 2248 | 2260 | 2262 | 2264 | 2266 |
2268 | 2280 | 2282 | 2284 | 2286 | 2288 | 2400 | 2402 | 2404 | 2406 | 2408 |
2420 | 2422 | 2424 | 2426 | 2428 | 2440 | 2442 | 2444 | 2446 | 2448 | 2460 |
2462 | 2464 | 2466 | 2468 | 2480 | 2482 | 2484 | 2486 | 2488 | 2600 | 2602 |
2604 | 2606 | 2608 | 2620 | 2622 | 2624 | 2626 | 2628 | 2640 | 2642 | 2644 |
2646 | 2648 | 2660 | 2662 | 2664 | 2666 | 2668 | 2680 | 2682 | 2684 | 2686 |
2688 | 2800 | 2802 | 2804 | 2806 | 2808 | 2820 | 2822 | 2824 | 2826 | 2828 |
2840 | 2842 | 2844 | 2846 | 2848 | 2860 | 2862 | 2864 | 2866 | 2868 | 2880 |
2882 | 2884 | 2886 | 2888 |

[6]: # comma separated


items = []
for i in range(100, 401):

34
s = str(i)
if (int(s[0]) % 2 == 0) and (int(s[1]) % 2 == 0) and (int(s[2]) % 2 == 0):
items.append(s)
print( ",".join(items))

200,202,204,206,208,220,222,224,226,228,240,242,244,246,248,260,262,264,266,268,
280,282,284,286,288,400

[2]: # change the value for a different output

string = 'veneZUEllA'
print(string)

# make it suitable for caseless comparison


string = string.casefold()
print(string)

# reverse the string


reverse_string = reversed(string)
print(reverse_string)

veneZUEllA
venezuella
<reversed object at 0x000002A7CAD86340>

[6]: s = 'aac34520'

d = {'DIGITS':0, 'LETTERS':0}

for c in s:
if c.isdigit():
d['DIGITS'] += 1
elif c.isalpha():
d['LETTERS'] += 1
else:
pass

print('LETTERS', d['LETTERS'])
print('DIGITS', d['DIGITS'])

LETTERS 3
DIGITS 5

[14]: string = 'Welcome to Alliance Uni'

# breakdown the sting into a list fo words


words = string.split()

35
print(words)

# sort the list


words.sort()
# display the sorted words
print('display the sorted words:', words)

['Welcome', 'to', 'Alliance', 'Uni']


display the sorted words: ['Alliance', 'Uni', 'Welcome', 'to']

[16]: number = 50

for i in range(1, number + 1):


remainder = number % i

if(remainder == 0):
if (i % 2 == 0):
print('Factor is even:', i)
else:
print('Factor is odd:', i)
else:
pass

Factor is odd: 1
Factor is even: 2
Factor is odd: 5
Factor is even: 10
Factor is odd: 25
Factor is even: 50

36

You might also like