Author Archives: timpythondev
While loop in Python
#The while loop in Python uses a counter variable as a #condition. The counter is incremented by 1 at the end of #each iteration of the loop and the condition (counter < 5) #is checked at the beginning of each iteration of the loop. #The while loop will keep looping as long as the condition …
cs circles
0: Hello!
Python Reserved Keywords
List Comprehensions
#define a list named “numbers” with 7 values numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7] #create a newlist using list comprehensions: newlist = [int(x) for x in numbers if x > 0] #printing newlist will only have positive numbers print(newlist)
Classes and Objects in Python
#define the Vehicle class class Vehicle: name = “” kind = “car” color = “” value = 100.00 #class function named description #we define a variable named desc_str and use #string formatting inside the string def description(self): desc_str = “%s is a %s %s worth $%.2f.” % (self.name, self.color, self.kind, self.value) return desc_str #instantiate two …
Conditions in Python
#Conditions x = 2 print(x==2) #prints out True print(x==3) #prints out False print(x<3) #prints out True #Using “and” + “or” keywords name = “John” age = 23 if name == “John” and age == 23: print(“Your name is John, and you are also 23 years old.”) if name == “John” or name == “Rick”: print(“Your …
Basic String Operations in Python
#Basic_String_Operations # <<—this is a comment #can use double or single quotes” astring = “Hello world!” astring2 = ‘Hello world!’ #enclose single quotes inside double quotes print(“single quotes are ‘ ‘”) #print the length of a string print(len(astring)) #print index of string w/ first occurrence of the letter #”o” print(astring.index(“o”)) #count the number of “ls” …
Python String Formatting
data = (“John”, “Doe”, 53.44) format_string = “Hello %s %s. Your current balance is $%s.” print(format_string % data)
Python print statement functionality
The print() statement in Python 3 allows you to specify the result of an if-else statement before the test condition syntax. The example code below has an output of 1.