-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonBasicPrograms.py
More file actions
401 lines (357 loc) · 13 KB
/
PythonBasicPrograms.py
File metadata and controls
401 lines (357 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
################################
# Author: Rahim Siddiq
# Python Basic Programs
################################
###Problem 1###
# User Input #
n = int(input("Please enter a number:"))
# Prevent negative values #
while n < 0:
print("Please enter positive integer values.")
n = int(input("Please enter a number:"))
# Condional based on user input #
for i in range(n):
# Inside Loop to make j run i number of times #
for j in range(n):
# print stars and leave a space, end= to keep in same line #
print("*", end = "")
# Once inside loop prints stars, print line numbers #
print("", i + 1)
# Print the number of stars #
print("You displayed", (n * n), "stars.")
###Problem 2###
# User input #
n = int(input("Enter the max number of stars per line"))
# Prevent negative values #
while n < 0:
print("Please enter positive integer values.")
n = int(input("Please enter the max number of stars per line:"))
# Conditional to print stars in ascending order from 1 to user input #
for i in range(1, n + 1):
# Nested loop to print stars in increment #
for j in range(1, i + 1):
# Print stars and format on the same line with end= followed by a space #
print("*", end = "")
# Print the number of the line #
print("", i)
# Contional to print stars in descending order from user input - 1 to 0 in negative increment #
for i in range(n - 1, 0, -1):
# Nested loop to print stars #
for j in range(0, i):
# Print stars on same line with end= followed by a space #
print("*", end = "")
# Print the line number #
print("", i)
###Problem 3###
# User Input #
n = int(input("Please enter the max number of starts per line:"))
# Prevent negative values #
while n < 0:
print("Please enter positive integer values.")
n = int(input("Please enter the max number of starts per line:"))
print("Part I")
# from to to range of user input + 1 so its input inclusive #
for i in range(1, n + 1):
# Nested loop to print starts incrementally #
for j in range(1, i + 1):
# Print starts j times using end= to list on the same line and space #
print(i, end = "")
# Print space, value of i end= to keep in line \n for new line next time through loop #
print(" ", i, end = "\n")
# From user input - 1 to 0 in negative increment #
for i in range(n - 1, 0, -1):
# Loop to print in negative incrament #
for j in range(i, 0, -1):
# Print i j many times end= to keep on same line then a space #
print(i, end = "")
# Print space value of i end= keep line and call for a new line for next loop #
print(" ", i, end = "\n")
print("Part II")
# Loop for invesrse. from user input to 0 decrement by 1 #
for i in range(n, 0, -1):
# Nest loop to print starts #
for j in range(i, 0, -1):
# Print i j number of times decrementally #
print(i, end = "")
# Print value of i end= to keep line and \n to call new line
print(" ", i, end = "\n")
# Similar to start loop except range at 2 to avoid double input from previous loop #
for i in range(2, n + 1):
for j in range(1, i + 1):
print(i, end = "")
print(" ", i, end = "\n")
###Problem 4###
# import random module #
import random
# while function to run program #
while True:
# generate random number 1/2 by calling randint object from random module #
flip = random.randint(1, 3)
# User input to enter choice #
choice = int(input("Enter the number 1 For Heads, 2 For Tails or 0 To Exit"))
# Conditionals based on input continue loop until user quits #
if choice == 0:
print("Goodbye")
break
elif choice == flip:
print("You win")
else:
print("You loose")
###Problem 5###
# Import random module #
import random
# generate random int between 1 - 10 using randint object inside random module #
randomn = random.randint(1, 11)
# Promt user to enter guess #
guess = int(input("Guess any number 1 to 10 or 0 to Exit"))
# Variable to track count #
count = 1
# Loop for program #
while True:
# Option for user exit #
if guess == 0:
print("Goodbye")
break
# Avoid negative inputs #
elif guess < 1:
print("Please enter a valid selection")
guess = int(input("Guess any number 1 to 10 or 0 to Exit"))
# Avoid inputs above range #
elif guess > 10:
print("Please enter a valid selection")
guess = int(input("Guess any number 1 to 10 or 0 to Exit"))
# If incorrect give hint #
elif (guess < randomn):
print("You guessed too low")
# if incorrect give hint #
elif (guess > randomn):
print("You guessed too high")
# Correct input breaks loop, count update for loop and return to user input function #
else:
print("You guessed correctly, it only took you", count, "tries")
break
count = count + 1
guess = int(input("Guess any number 1 to 10 or 0 to Exit"))
###Problem 6###
# User input #
number = int(input("Enter multiplication table you want to see "))
# User input for size of table #
max_number = int(input("Enter max you want your table to go "))
# Prevent negative values #
while max_number < 1:
print("Please enter positive values for table size.")
max_number = int(input("Enter max you want your table to go "))
# Print for formatting #
print("---------------------")
print("The table of %d" % number)
print("---------------------")
# printing table of user entered size #
for i in range(1, max_number + 1):
print(i, "*", number, "=", i * number)
# Formatting print statments #
print("---------------------")
print("Done Counting ...")
print("---------------------")
###Problem 7###
# User input #
st = input("Enter a string:")
# Open file in write format and assign to variable file #
file = open("myfile.txt", "w")
# Write string to file #
file.write("You entered the words below \n")
# New line at the end of string #
file.write(st + "\n")
# split words in string assign to variable words #
words = st.split()
# Write statement to file and start new line #
file.write("The words are split and then sorted \n")
# Variable name for sorted words #
sor = sorted(words)
# Driver code #
for i in sor:
file.write(i + " ")
file.write("\nThe sorted words are:\n")
for i in sor:
file.write(i + "\n")
# Close file open myfile in read format then close file #
file.close()
file1 = open("myfile.txt", "r+")
print(file1.read())
file1.close()
###Problem 8###
# function to check palindrome #
def isPalindrome(s):
# Using reversed to flip order of string #
rev = ''.join(reversed(s))
# Check for equality #
if (s == rev):
return True
return False
# User input #
s = input("Please enter string")
# call def function #
ans = isPalindrome(s)
# Driver code to return print statement input from user in both entered and fliped format #
if (ans):
print("Yes", s, "spelled backwards is", ''.join(reversed(s)))
else:
print("No", s, "spelled backwards is", ''.join(reversed(s)))
###Problem 9###
# User input #
name = input("Please enter your name or 0 to quit:")
# Loop for user input #
while name != "0":
# User input for gender assign suffix or exit #
gender = int(input("Enter your gender(1 = Male, 2 = Female, 0 = Quit):"))
if gender == 1:
suffix = "Mr."
print("Welcome", suffix, name, "!")
elif gender == 2:
suffix = "Ms."
print("Welcome", suffix, name, "!")
elif gender == 0:
break
# User input for calories or distance #
choice = int(input("Number of calories to burn or distance to run?(1 = distance, 2 = cals:)"))
# formula based on distance run converts to calories lost #
if choice == 1:
weight = int(input("Enter your weight in pounds:"))
dist = int(input("Enter the distance run in miles:"))
cals = .653 * weight * dist
print("Congratulations", suffix, name, "you burn", format(cals, ",.2f"), "calories if you run", dist, "miles.")
# formula based on desired calories to burn outputs distance to run #
elif choice == 2:
weight = int(input("Enter your weight in pounds:"))
cals = float(input("Enter calories to burn:"))
dist = cals / (.653 * weight)
print(suffix, name, ", you need to run", format(dist, ",.2f"), "miles, if you want to burn", cals, "calories.")
# Continue loop until user quits #
name = input("Enter your name or 0 to quit:")
print("Good Bye")
###Problem 10###
# Def Fuction #
def calculateParkingFee(count, hr):
# Flat Rate #
parkingfee = 3
# conditional loop for hours past 3 #
if hr > 3:
# Subtract flat rate #
additional = hr - 3
# add a dollar for each hour over flat rate #
parkingfee = parkingfee + (additional * 1)
# conditional for parking over 12 hours #
if parkingfee > 12:
# flat rate 12 #
parkingfee = 12
# Print values and \t for spacing to make tabular then return function #
print(count, "\t" * 2, hr, "\t" * 2, parkingfee)
return parkingfee
# User input for number of cars #
numcars = int(input("Enter the number of cars:"))
# Index for carhours #
carhours = []
# loop from 0 to user input number of cars #
for i in range(0, numcars):
print("Enter the hours of car #:")
# User input for number of hours parked #
hr = int(input("Enter number of hours parked:"))
# Append hours to carhours so we can call value in list #
carhours.append(hr)
# Print headers for table #
print("Customer", "\t", "Hours", "\t" * 2, "Fee")
# Assignment variable for total #
totalfee = 0
# Loop to calculate toatl #
for i in range(0, numcars):
totalfee = totalfee + calculateParkingFee(i + 1, int(carhours[i]))
# Print str tab 3x to bring in line with fee and print total cost of fee #
print("Total Fee", "\t" * 3, totalfee)
###Problem 11###
import random
def read_choice():
print("Select operation.")
return int(input("Enter the number of the operation 1. Add // 2. Subtract // 3. Multiply // 4. Divide // 5. Guessing game coinflip // 6. Guessing game random // 7. Exit):"))
def guessing_game_coinflip():
# import random module #
import random
# while function to run program #
while True:
# generate random number 1/2 by calling randint object from random module #
flip = random.randint(1, 3)
# User input to enter choice #
choice = int(input("Enter the number 1 For Heads, 2 For Tails or 0 To Exit"))
# Conditionals based on input continue loop until user quits #
if choice == 0:
print("Goodbye")
break
elif choice == flip:
print("You win")
else:
print("You loose")
def guessing_game_random():
# Import random module #
import random
# generate random int between 1 - 10 using randint object inside random module #
randomn = random.randint(1, 11)
# Promt user to enter guess #
guess = int(input("Guess any number 1 to 10 or 0 to Exit"))
# Variable to track count #
count = 1
# Loop for program #
while True:
# Option for user exit #
if guess == 0:
print("Goodbe")
break
# Avoid negative inputs #
elif guess < 1:
print("Please enter a valid selection")
guess = int(input("Guess any number 1 to 10 or 0 to Exit"))
# Avoid inputs above range #
elif guess > 10:
print("Please enter a valid selection")
guess = int(input("Guess any number 1 to 10 or 0 to Exit"))
# If incorrect give hint #
elif (guess < randomn):
print("You guessed too low")
# if incorrect give hint #
elif (guess > randomn):
print("You guessed too high")
# Correct input breaks loop, count update for loop and return to user input function #
else:
print("You guessed correctly, it only took you", count, "tries")
break
count = count + 1
guess = int(input("Guess any number 1 to 10 or 0 to Exit"))
def add_numbers(n1, n2):
print("{} + {} = {}".format(n1, n2, n1 + n2))
def subtract_numbers(n1, n2):
print("{} - {} = {}".format(n1, n2, n1 - n2))
def multiply_numbers(n1, n2):
print("{} * {} = {}".format(n1, n2, n1 * n2))
def divide_numbers(n1, n2):
print("{} / {} = {}".format(n1, n2, n1 / n2))
def main():
while True:
choice = read_choice()
if 1 <= choice <= 4:
n1 = int(input("Enter first number: "))
n2 = int(input("Enter second number: "))
if choice == 1:
add_numbers(n1, n2)
elif choice == 2:
subtract_numbers(n1, n2)
elif choice == 3:
multiply_numbers(n1, n2)
elif choice == 4:
divide_numbers(n1, n2)
elif choice == 5:
guessing_game_coinflip()
elif choice == 6:
guessing_game_random()
elif choice == 7:
print("Goodbye")
break
else:
print("Invalid choice!")
main()