Basic Python Examples That Will Help You Learn Fast

https://static1.makeuseofimages.com/wordpress/wp-content/uploads/2016/12/basic-python-examples.jpg

If you’re going to learn a new language today, Python is one of the options out there. Not only is it relatively easy to learn, but it has many practical uses in tech.

Whether you’re coming to Python from another language or learning it for the first time, it helps to start with some basic examples.

Strings

Proper Python string manipulation is a skill every programmer needs to learn. You’ll use strings whether you’re developing a website, making a game, or analyzing data, among other applications.

String Formatting

Let’s say you have two strings:

name = "Joel"
job = "Programmer"

And let’s say you want to concatenate (join together) the two strings into one. You might choose to do this:

title = name + " the " + job
print(title)

But there’s a better way to manipulate strings, resulting in more readable code. Prefer to use the format() method:

title = "{} the {}".format(name, job)
print(title)

The curly braces ({}) are placeholders for the variables passed into the format method in their respective order. The first curly brace is replaced by the name parameter, while the second brace gets replaced by the job parameter.

You can have as many curly braces and parameters as long as the count matches. And these parameters can be of any data type, so you can use an integer, for example.

String Joining

Another nifty Pythonic trick is the join() method, which combines a list of strings into one.

For example:

availability = ["Monday", "Wednesday", "Friday", "Saturday"]
result = " - ".join(availability)
print(result)
# Output: 'Monday - Wednesday - Friday - Saturday'

The separating string (” – “) only goes between items, so you won’t have an extraneous separator at the end.

Conditionals

Programming would be pointless without conditional statements. Fortunately, conditions in Python are clean and easy to wrap your head around.

Boolean Values

Like in other programming languages, comparison operators evaluate to a boolean result, either True or False.

Here are all the comparison operators in Python:

x = 10

print(x == 10)

print(x != 10)

print(x > 5)

print(x < 15)

print(x >= 10)

print(x <= 10)

The if and else statements

As with other programming languages, you can use the if/else statements to represent conditions in Python. You’ll use this a lot in real-world projects:

a = 3
b = 10

if a < b:
print(True)
else:
print(False)

While some other programming languages like JavaScript and C use else…if to pass in more conditions, Python uses elif:

a = 3
b = 10

if a > b:
print("One")
elif a == 3:
print("Two")
else:
print("Three")

The is and not Operators

The is operator is different from the == comparison operator in that the latter only checks if the values of a variable are equal.

If you want to check whether two variables point to the same object in memory, you’ll need to use the is operator:

a = [1,2,3]
b = [1,2,3]
c = a
print(a is b)
print(a is c)
print(a == c)

The expression a is c evaluates to True because c points to a in memory.

You can negate a boolean value by preceding it with the not operator:

a = [1,2,3]
b = [1,2,3]

if a is not b:
print("Not same")

The in Operator

The best way to check if a value exists within an iterable like a list or a dictionary is to use the in operator:

availability = ["Monday", "Tuesday", "Friday"]
request = "Saturday"
if request in availability:
print("Available!")
else:
print("Not available")

Complex Conditionals

You can combine multiple conditional statements using the and and or operators. The and operator evaluates to True if both sides are True, otherwise False.

The or operator evaluates to True if either side is True, otherwise False.

weather = "Sunny"

umbrella = weather == "Rain" or weather == "Sunny"
umbrella1 = weather == "Rain" and weather =="Snow"

print(umbrella)


print(umbrella1)

Loops

The most basic type of loop is Python’s while loop, which keeps repeating as long as a condition evaluates to True:

i = 0

while i < 10:
i = i + 1
print(i)


You can use the break keyword to exit a loop:

i = 0

while True:
i = i + 1
print(i)

You can use continue if you just want to skip the rest of the current loop and jump to the next iteration:

i = 0

while i < 10:
i = i + 1

if i == 4:
continue

print(i)

The for Loop

The more Pythonic approach is to use for loops. The for loop in Python is much like the foreach loop you’ll find in languages like Java or C#.

The for loop iterates over an iterable (like a list or dictionary) using the in operator:

weekdays = ["Monday", "Tuesday", "Wednesday"]

for day in weekdays:
print(day)

The for loop assigns each item in the list to the day variable and outputs each accordingly.

If you just want to run a loop a fixed number of times, you can use Python’s range() method:

for i in range(10):
print(i)

This will iterate from 0 to 9. You can also provide a starting value, so to iterate from 5 to 9:

for i in range(5, 10):
print(i)

If you want to count in intervals other than one by one, you can provide a third parameter.

The following loop is the same as the previous one, except it skips by two instead of one:

for i in range(5, 10, 2):
print(i)


If you’re coming from another language, you might notice that looping through an iterable in Python doesn’t give you the index of the items in the list.

But you can use the index to count items in an iterable with the enumerate() method:

weekdays = ["Monday", "Tuesday", "Friday"]

for i, day in enumerate(weekdays):
print(&quot;{} is weekday {}&quot;.format(day, i))

Dictionaries

The dictionary is one of the most important data types in Python. You’ll use them all the time. They’re fast and easy to use, keeping your code clean and readable.

A mastery of dictionaries is half the battle in learning Python. The good news is that you probably have prior knowledge of dictionaries. Other languages call this type an unordered_map or a HashSet.

Although they have different names, they refer to the same thing: an associative array of key-value pairs. You access the contents of a list via each item’s index, while you access a dictionary’s items via a key.

You can declare an empty dictionary using empty braces:

d = {}

And then assign values to it using square brackets surrounding the key:

d["key1"] = 10
d["key2"] = 25

print(d)

# Output: {'key1': 10, 'key2': 25}

The nice thing about a dictionary is that you can mix and match variable types. It doesn’t matter what you put in there.

To initialize a dictionary more easily, you can use this syntax:

myDictionary = {
"key1": 10,
"List": [1, 2, 3]
}

To access a dictionary value by key, simply reuse the bracket syntax:

print(myDictionary["key1"])

To iterate over the keys in a dictionary, use a for loop like so:

for key in myDictionary:
print(key)

To iterate both keys and values, use the items() method:

for key, values in myDictionary.items():
print(key, values)

You can also remove an item from a dictionary using the del operator:

del(myDictionary["List"])

print(myDictionary)
# Output: {'key1': 10}

Dictionaries have many uses. Here’s a simple example of a mapping between some US states and their capitals:

capitals = {
"Alabama": "Montgomery",
"Alaska": "Juneau",
"Arizona": "Phoenix",
}

Whenever you need the capital of a state, you can access it like so:

print(capitals["Alaska"])

Keep Learning Python: It’s Worth It!

These are just the basic aspects of Python that set it apart from most of the other languages out there. If you understand what we covered in this article, you’re well on mastering Python. Keep at it, and you’ll get there in no time.

If the examples challenge you to go further, some Python project ideas for beginners might be a solid starting point.

MUO – Feed

Land Cruiser Armor Testing

https://theawesomer.com/photos/2022/06/inkas_toyota_land_cruiser_armor_test_t.jpg

Land Cruiser Armor Testing

Link

Toyota vehicles are known for their durability and reliability. But even a Land Cruiser can’t stand up to explosions without the help of some armor. Vehicle security company Inkas shows how their armor systems can help protect occupants of the SUV by hitting it with ammunition, grenades, land mines, and dynamite.

The Awesomer

Crashing

https://theawesomer.com/photos/2022/06/crashing_t.jpg

Crashing

Link

When you feel burnt out, it’s a good plan to take time for yourself. But taking a break sometimes causes everything to come crashing down. Maggie Mae Fish’s relatable short film about living with ADHD explores some of the feelings you might experience when you emerge from your everyday distractions. (Thanks, Rob!)

The Awesomer

The Orcs of The Rings of Power Are Worse Than You’ve Ever Seen Them

https://i.kinja-img.com/gawker-media/image/upload/c_fill,f_auto,fl_progressive,g_center,h_675,pg_1,q_80,w_1200/43bf24a8f271d61ea799d7b3e2372f01.jpg

IGN has revealed a series of photos from the new Lord of the Rings: The Rings of Power, this time showing off the “new and unimproved” Orcs of this age. And for once, worse is actually better here.

In an interview with Jamie Wilson, head of the prosthetics department on The Rings of Power, and Lindsey Weber, an executive producer for the series, we get more details on how the forces of evil will operate in this period of Tolkien’s vast fantasy saga. “We spent a lot of time talking about what it would mean to be an Orc in the Second Age. It felt appropriate that their look would be different, part of a wilder, more raw, Second Age, Middle-earth, closer to where the First Age ends.” Weber said, describing the more desiccated, haunted look of the orcs that we see in the preview images that IGN has been given. “As we meet them, they’re not yet organized into armies, they’re a little more scattered and they’ve been scavenging. So it’s just a different time in their total story.”

Wilson is what’s known as a “Sevener” on set. This means that he’s worked on all the filmed Lord of the Rings productions: the original Peter Jackson trilogy, the Hobbit trilogy, and now The Rings of Power. He’s been around these specific prosthetics and makeup for decades, and has spent a lot of time thinking about how orcs look on screen… and how to make them look that way.

“Time has changed a lot,” Wilson told IGN. “You go back 20 years and we used a basically foam latex, which is like a porous-y kind of rubbery, spongy material with a smooth or whatever textured surface. It was great at the time.”

He mentions that silicon was only in use during the original trilogy towards the end, when they were able to make some pieces for John Rhys-Davies as Gimli. Times, he said, have changed dramatically. “All the ears, noses, Orcs pieces are all made in encapsulated silicon, which is basically two layers of silicon with a moveable piece of silicon in the middle, so when it’s applied to the actor’s face, they can move and it works,” he explained. “It also gets the same temperature as their skin. And you can see the translucency and then you gently paint on the top of it, a bit like doing makeup on a human rather than having to seal and heavily paint like we did in the old days.”

Both Wilson and Weber also noted that while the prosthetics and practical makeup are incredibly advanced, there is still a lot of CGI in Rings of Power. The show, Weber explains, is simply not reliant on it to make the orcs look good—a lot of the digital enhancements will occur in larger ensemble shots. Close up, you’ll get to see the orcs in all their garish, practically-designed glory.

Lord of the Rings: The Rings of Power debuts September 2 on Prime Video.


Want more io9 news? Check out when to expect the latest Marvel and Star Wars releases, what’s next for the DC Universe on film and TV, and everything you need to know about House of the Dragon and Lord of the Rings: The Rings of Power.

Gizmodo

This New Thor: Love and Thunder Video Is Pure, Infectious Joy

https://i.kinja-img.com/gawker-media/image/upload/c_fill,f_auto,fl_progressive,g_center,h_675,pg_1,q_80,w_1200/9db4b1eccfb5d2a0a2e6db591fa3f69a.jpg

Taika and two Thors.
Screenshot: YouTube/Marvel

This new featurette for Thor: Love and Thunder is more exciting than all of its trailers combined. Which is saying something: the trailers for Taika Waititi’s latest, starring Chris Hemsworth, Natalie Portman, Tessa Thompson, and Christian Bale, have been excellent. There’s just something about seeing all that footage cut with the actors and filmmaker gushing over it that gives a whole new level of energy.

Thor: Love and Thunder opens July 8 and it picks up where Avengers: Endgame left off. Thor (Hemsworth) has left Asgard under the protection of Valkyrie (Thompson) and set back off into space with the Guardians of the Galaxy. For the first time in his life, he has nothing he has to do. But that will change when a villain named Gorr the God Butcher (Bale) emerges to kill the Gods, which brings the Mighty Thor, Jane Foster (Portman), back into Thor’s world.

Below, watch a few of the actors and Waititi talk up this installment with infectious enthusiasm. Or maybe that’s just the Guns ‘N Roses talking.

Marvel Studios’ Thor: Love and Thunder | When Love Meets Thunder Featurette

While I haven’t seen every TV spot released for Thor: Love and Thunder, I do believe there’s some new footage in there too. The characters reacting to Thor’s very Peter Quill outfit. Footage of goats Tanngrisnir and Tanngnjóstr, who are important enough to get their own character posters, and of course that final shot of Thor vs. Gorr… hey that rhymed!

Either way, it’s an awesome featurette for what we hope is an equally awesome movie. It will have to be, to top what the team achieved with Thor: Ragnarok. Thor: Love and Thunder opens July 8, though the first reactions from early screenings will begin this week.


Want more io9 news? Check out when to expect the latest Marvel and Star Wars releases, what’s next for the DC Universe on film and TV, and everything you need to know about House of the Dragon and Lord of the Rings: The Rings of Power.

Gizmodo

Ohio Attorney General Dave Yost Issues Updated CCW Manual

https://www.buckeyefirearms.org/sites/buckeyefirearms.org/files/styles/slideshow/public/field/image/ccwhandbook.jpg?itok=Dk6I3RZZ

Ohio CCW Handbook 2022
by Dean Rieck

As of Monday, June 13, 2022, it is legal for "qualifying adults" to carry a concealed handgun in Ohio without a license.

Attorney General Dave Yost has issued an updated manual summarizing Ohio’s concealed carry laws and explaining the two ways you may now carry in the state, with or without a license.

Click here to view or download the manual as a PDF.

Whether you plan to carry with a license or without one, I highly recommend you read this manual, which covers a number of important topics, including:

  • Two Ways to Carry Concealed
  • A Crucial Difference Between CHL Holders and Permitless Carriers
  • Other Changes in Ohio’s Concealed-Carry Law
  • Training and Educational Requirements for a Concealed-Handgun License
  • Special Considerations for Members of the Armed Forces
  • Forbidden-Carry Zones
  • Transporting in Motor Vehicles
  • Traffic Stops and Other Law Enforcement Encounters
  • Private Property and the Workplace
  • Reciprocity
  • Open Carry
  • Deadly Force
  • Criminal Issues
  • Civil Liability
  • Self-Defense
  • No Duty to Retreat
  • Castle Doctrine
  • Burden of Proof
  • Defense of Others
  • Defense of Property
  • Dispute Resolution

In addition to reading this manual, I urge you to take a concealed carry class from an experienced and competent instructor, even if you do not plan to apply for a license. It is vital that you are familiar with Ohio self-defense law to help you make better decisions and act legally.

You can search for classes on OhioGunClass.org, a website we host for instructors in Ohio.

Dean Rieck is Executive Director of Buckeye Firearms Association, a former competitive shooter, NRA Patron Member, #1 NRA Recruiter for 2013, business owner and partner with Second Call Defense.

Buckeye Firearms Association